babylon.2.1-alpha.debug.js 1.4 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486
  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, 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, 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, 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.setTranslation = function (vector3) {
  1402. this.m[12] = vector3.x;
  1403. this.m[13] = vector3.y;
  1404. this.m[14] = vector3.z;
  1405. return this;
  1406. };
  1407. Matrix.prototype.multiply = function (other) {
  1408. var result = new Matrix();
  1409. this.multiplyToRef(other, result);
  1410. return result;
  1411. };
  1412. Matrix.prototype.copyFrom = function (other) {
  1413. for (var index = 0; index < 16; index++) {
  1414. this.m[index] = other.m[index];
  1415. }
  1416. return this;
  1417. };
  1418. Matrix.prototype.copyToArray = function (array, offset) {
  1419. if (offset === void 0) { offset = 0; }
  1420. for (var index = 0; index < 16; index++) {
  1421. array[offset + index] = this.m[index];
  1422. }
  1423. return this;
  1424. };
  1425. Matrix.prototype.multiplyToRef = function (other, result) {
  1426. this.multiplyToArray(other, result.m, 0);
  1427. return this;
  1428. };
  1429. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1430. var tm0 = this.m[0];
  1431. var tm1 = this.m[1];
  1432. var tm2 = this.m[2];
  1433. var tm3 = this.m[3];
  1434. var tm4 = this.m[4];
  1435. var tm5 = this.m[5];
  1436. var tm6 = this.m[6];
  1437. var tm7 = this.m[7];
  1438. var tm8 = this.m[8];
  1439. var tm9 = this.m[9];
  1440. var tm10 = this.m[10];
  1441. var tm11 = this.m[11];
  1442. var tm12 = this.m[12];
  1443. var tm13 = this.m[13];
  1444. var tm14 = this.m[14];
  1445. var tm15 = this.m[15];
  1446. var om0 = other.m[0];
  1447. var om1 = other.m[1];
  1448. var om2 = other.m[2];
  1449. var om3 = other.m[3];
  1450. var om4 = other.m[4];
  1451. var om5 = other.m[5];
  1452. var om6 = other.m[6];
  1453. var om7 = other.m[7];
  1454. var om8 = other.m[8];
  1455. var om9 = other.m[9];
  1456. var om10 = other.m[10];
  1457. var om11 = other.m[11];
  1458. var om12 = other.m[12];
  1459. var om13 = other.m[13];
  1460. var om14 = other.m[14];
  1461. var om15 = other.m[15];
  1462. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1463. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1464. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1465. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1466. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1467. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1468. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1469. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1470. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1471. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1472. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1473. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1474. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1475. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1476. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1477. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1478. return this;
  1479. };
  1480. Matrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  1481. if (offset === void 0) { offset = 0; }
  1482. var tm = this.m;
  1483. var om = other.m;
  1484. var om0 = SIMD.float32x4.load(om, 0);
  1485. var om1 = SIMD.float32x4.load(om, 4);
  1486. var om2 = SIMD.float32x4.load(om, 8);
  1487. var om3 = SIMD.float32x4.load(om, 12);
  1488. var tm0 = SIMD.float32x4.load(tm, 0);
  1489. 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)))));
  1490. var tm1 = SIMD.float32x4.load(tm, 4);
  1491. 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)))));
  1492. var tm2 = SIMD.float32x4.load(tm, 8);
  1493. 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)))));
  1494. var tm3 = SIMD.float32x4.load(tm, 12);
  1495. 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)))));
  1496. };
  1497. Matrix.prototype.equals = function (value) {
  1498. 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]);
  1499. };
  1500. Matrix.prototype.clone = function () {
  1501. 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]);
  1502. };
  1503. Matrix.prototype.decompose = function (scale, rotation, translation) {
  1504. translation.x = this.m[12];
  1505. translation.y = this.m[13];
  1506. translation.z = this.m[14];
  1507. var xs = BABYLON.Tools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  1508. var ys = BABYLON.Tools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  1509. var zs = BABYLON.Tools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  1510. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  1511. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  1512. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  1513. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  1514. rotation.x = 0;
  1515. rotation.y = 0;
  1516. rotation.z = 0;
  1517. rotation.w = 1;
  1518. return false;
  1519. }
  1520. 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);
  1521. Quaternion.FromRotationMatrixToRef(rotationMatrix, rotation);
  1522. return true;
  1523. };
  1524. // Statics
  1525. Matrix.FromArray = function (array, offset) {
  1526. var result = new Matrix();
  1527. if (!offset) {
  1528. offset = 0;
  1529. }
  1530. Matrix.FromArrayToRef(array, offset, result);
  1531. return result;
  1532. };
  1533. Matrix.FromArrayToRef = function (array, offset, result) {
  1534. for (var index = 0; index < 16; index++) {
  1535. result.m[index] = array[index + offset];
  1536. }
  1537. };
  1538. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  1539. result.m[0] = initialM11;
  1540. result.m[1] = initialM12;
  1541. result.m[2] = initialM13;
  1542. result.m[3] = initialM14;
  1543. result.m[4] = initialM21;
  1544. result.m[5] = initialM22;
  1545. result.m[6] = initialM23;
  1546. result.m[7] = initialM24;
  1547. result.m[8] = initialM31;
  1548. result.m[9] = initialM32;
  1549. result.m[10] = initialM33;
  1550. result.m[11] = initialM34;
  1551. result.m[12] = initialM41;
  1552. result.m[13] = initialM42;
  1553. result.m[14] = initialM43;
  1554. result.m[15] = initialM44;
  1555. };
  1556. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  1557. var result = new Matrix();
  1558. result.m[0] = initialM11;
  1559. result.m[1] = initialM12;
  1560. result.m[2] = initialM13;
  1561. result.m[3] = initialM14;
  1562. result.m[4] = initialM21;
  1563. result.m[5] = initialM22;
  1564. result.m[6] = initialM23;
  1565. result.m[7] = initialM24;
  1566. result.m[8] = initialM31;
  1567. result.m[9] = initialM32;
  1568. result.m[10] = initialM33;
  1569. result.m[11] = initialM34;
  1570. result.m[12] = initialM41;
  1571. result.m[13] = initialM42;
  1572. result.m[14] = initialM43;
  1573. result.m[15] = initialM44;
  1574. return result;
  1575. };
  1576. Matrix.Compose = function (scale, rotation, translation) {
  1577. var result = Matrix.FromValues(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1);
  1578. var rotationMatrix = Matrix.Identity();
  1579. rotation.toRotationMatrix(rotationMatrix);
  1580. result = result.multiply(rotationMatrix);
  1581. result.setTranslation(translation);
  1582. return result;
  1583. };
  1584. Matrix.Identity = function () {
  1585. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  1586. };
  1587. Matrix.IdentityToRef = function (result) {
  1588. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  1589. };
  1590. Matrix.Zero = function () {
  1591. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  1592. };
  1593. Matrix.RotationX = function (angle) {
  1594. var result = new Matrix();
  1595. Matrix.RotationXToRef(angle, result);
  1596. return result;
  1597. };
  1598. Matrix.Invert = function (source) {
  1599. var result = new Matrix();
  1600. source.invertToRef(result);
  1601. return result;
  1602. };
  1603. Matrix.RotationXToRef = function (angle, result) {
  1604. var s = Math.sin(angle);
  1605. var c = Math.cos(angle);
  1606. result.m[0] = 1.0;
  1607. result.m[15] = 1.0;
  1608. result.m[5] = c;
  1609. result.m[10] = c;
  1610. result.m[9] = -s;
  1611. result.m[6] = s;
  1612. result.m[1] = 0;
  1613. result.m[2] = 0;
  1614. result.m[3] = 0;
  1615. result.m[4] = 0;
  1616. result.m[7] = 0;
  1617. result.m[8] = 0;
  1618. result.m[11] = 0;
  1619. result.m[12] = 0;
  1620. result.m[13] = 0;
  1621. result.m[14] = 0;
  1622. };
  1623. Matrix.RotationY = function (angle) {
  1624. var result = new Matrix();
  1625. Matrix.RotationYToRef(angle, result);
  1626. return result;
  1627. };
  1628. Matrix.RotationYToRef = function (angle, result) {
  1629. var s = Math.sin(angle);
  1630. var c = Math.cos(angle);
  1631. result.m[5] = 1.0;
  1632. result.m[15] = 1.0;
  1633. result.m[0] = c;
  1634. result.m[2] = -s;
  1635. result.m[8] = s;
  1636. result.m[10] = c;
  1637. result.m[1] = 0;
  1638. result.m[3] = 0;
  1639. result.m[4] = 0;
  1640. result.m[6] = 0;
  1641. result.m[7] = 0;
  1642. result.m[9] = 0;
  1643. result.m[11] = 0;
  1644. result.m[12] = 0;
  1645. result.m[13] = 0;
  1646. result.m[14] = 0;
  1647. };
  1648. Matrix.RotationZ = function (angle) {
  1649. var result = new Matrix();
  1650. Matrix.RotationZToRef(angle, result);
  1651. return result;
  1652. };
  1653. Matrix.RotationZToRef = function (angle, result) {
  1654. var s = Math.sin(angle);
  1655. var c = Math.cos(angle);
  1656. result.m[10] = 1.0;
  1657. result.m[15] = 1.0;
  1658. result.m[0] = c;
  1659. result.m[1] = s;
  1660. result.m[4] = -s;
  1661. result.m[5] = c;
  1662. result.m[2] = 0;
  1663. result.m[3] = 0;
  1664. result.m[6] = 0;
  1665. result.m[7] = 0;
  1666. result.m[8] = 0;
  1667. result.m[9] = 0;
  1668. result.m[11] = 0;
  1669. result.m[12] = 0;
  1670. result.m[13] = 0;
  1671. result.m[14] = 0;
  1672. };
  1673. Matrix.RotationAxis = function (axis, angle) {
  1674. var s = Math.sin(-angle);
  1675. var c = Math.cos(-angle);
  1676. var c1 = 1 - c;
  1677. axis.normalize();
  1678. var result = Matrix.Zero();
  1679. result.m[0] = (axis.x * axis.x) * c1 + c;
  1680. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  1681. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  1682. result.m[3] = 0.0;
  1683. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  1684. result.m[5] = (axis.y * axis.y) * c1 + c;
  1685. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  1686. result.m[7] = 0.0;
  1687. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  1688. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  1689. result.m[10] = (axis.z * axis.z) * c1 + c;
  1690. result.m[11] = 0.0;
  1691. result.m[15] = 1.0;
  1692. return result;
  1693. };
  1694. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1695. var result = new Matrix();
  1696. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1697. return result;
  1698. };
  1699. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1700. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  1701. this._tempQuaternion.toRotationMatrix(result);
  1702. };
  1703. Matrix.Scaling = function (x, y, z) {
  1704. var result = Matrix.Zero();
  1705. Matrix.ScalingToRef(x, y, z, result);
  1706. return result;
  1707. };
  1708. Matrix.ScalingToRef = function (x, y, z, result) {
  1709. result.m[0] = x;
  1710. result.m[1] = 0;
  1711. result.m[2] = 0;
  1712. result.m[3] = 0;
  1713. result.m[4] = 0;
  1714. result.m[5] = y;
  1715. result.m[6] = 0;
  1716. result.m[7] = 0;
  1717. result.m[8] = 0;
  1718. result.m[9] = 0;
  1719. result.m[10] = z;
  1720. result.m[11] = 0;
  1721. result.m[12] = 0;
  1722. result.m[13] = 0;
  1723. result.m[14] = 0;
  1724. result.m[15] = 1.0;
  1725. };
  1726. Matrix.Translation = function (x, y, z) {
  1727. var result = Matrix.Identity();
  1728. Matrix.TranslationToRef(x, y, z, result);
  1729. return result;
  1730. };
  1731. Matrix.TranslationToRef = function (x, y, z, result) {
  1732. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  1733. };
  1734. Matrix.LookAtLH = function (eye, target, up) {
  1735. var result = Matrix.Zero();
  1736. Matrix.LookAtLHToRef(eye, target, up, result);
  1737. return result;
  1738. };
  1739. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  1740. // Z axis
  1741. target.subtractToRef(eye, this._zAxis);
  1742. this._zAxis.normalize();
  1743. // X axis
  1744. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  1745. this._xAxis.normalize();
  1746. // Y axis
  1747. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  1748. this._yAxis.normalize();
  1749. // Eye angles
  1750. var ex = -Vector3.Dot(this._xAxis, eye);
  1751. var ey = -Vector3.Dot(this._yAxis, eye);
  1752. var ez = -Vector3.Dot(this._zAxis, eye);
  1753. 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);
  1754. };
  1755. Matrix.OrthoLH = function (width, height, znear, zfar) {
  1756. var matrix = Matrix.Zero();
  1757. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  1758. return matrix;
  1759. };
  1760. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  1761. var hw = 2.0 / width;
  1762. var hh = 2.0 / height;
  1763. var id = 1.0 / (zfar - znear);
  1764. var nid = znear / (znear - zfar);
  1765. Matrix.FromValuesToRef(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1, result);
  1766. };
  1767. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  1768. var matrix = Matrix.Zero();
  1769. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  1770. return matrix;
  1771. };
  1772. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  1773. result.m[0] = 2.0 / (right - left);
  1774. result.m[1] = result.m[2] = result.m[3] = 0;
  1775. result.m[5] = 2.0 / (top - bottom);
  1776. result.m[4] = result.m[6] = result.m[7] = 0;
  1777. result.m[10] = -1.0 / (znear - zfar);
  1778. result.m[8] = result.m[9] = result.m[11] = 0;
  1779. result.m[12] = (left + right) / (left - right);
  1780. result.m[13] = (top + bottom) / (bottom - top);
  1781. result.m[14] = znear / (znear - zfar);
  1782. result.m[15] = 1.0;
  1783. };
  1784. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  1785. var matrix = Matrix.Zero();
  1786. matrix.m[0] = (2.0 * znear) / width;
  1787. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  1788. matrix.m[5] = (2.0 * znear) / height;
  1789. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  1790. matrix.m[10] = -zfar / (znear - zfar);
  1791. matrix.m[8] = matrix.m[9] = 0.0;
  1792. matrix.m[11] = 1.0;
  1793. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  1794. matrix.m[14] = (znear * zfar) / (znear - zfar);
  1795. return matrix;
  1796. };
  1797. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  1798. var matrix = Matrix.Zero();
  1799. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  1800. return matrix;
  1801. };
  1802. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, fovMode) {
  1803. if (fovMode === void 0) { fovMode = BABYLON.Camera.FOVMODE_VERTICAL_FIXED; }
  1804. var tan = 1.0 / (Math.tan(fov * 0.5));
  1805. var v_fixed = (fovMode === BABYLON.Camera.FOVMODE_VERTICAL_FIXED);
  1806. if (v_fixed) {
  1807. result.m[0] = tan / aspect;
  1808. }
  1809. else {
  1810. result.m[0] = tan;
  1811. }
  1812. result.m[1] = result.m[2] = result.m[3] = 0.0;
  1813. if (v_fixed) {
  1814. result.m[5] = tan;
  1815. }
  1816. else {
  1817. result.m[5] = tan * aspect;
  1818. }
  1819. result.m[4] = result.m[6] = result.m[7] = 0.0;
  1820. result.m[8] = result.m[9] = 0.0;
  1821. result.m[10] = -zfar / (znear - zfar);
  1822. result.m[11] = 1.0;
  1823. result.m[12] = result.m[13] = result.m[15] = 0.0;
  1824. result.m[14] = (znear * zfar) / (znear - zfar);
  1825. };
  1826. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  1827. var cw = viewport.width;
  1828. var ch = viewport.height;
  1829. var cx = viewport.x;
  1830. var cy = viewport.y;
  1831. 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);
  1832. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  1833. };
  1834. Matrix.Transpose = function (matrix) {
  1835. var result = new Matrix();
  1836. result.m[0] = matrix.m[0];
  1837. result.m[1] = matrix.m[4];
  1838. result.m[2] = matrix.m[8];
  1839. result.m[3] = matrix.m[12];
  1840. result.m[4] = matrix.m[1];
  1841. result.m[5] = matrix.m[5];
  1842. result.m[6] = matrix.m[9];
  1843. result.m[7] = matrix.m[13];
  1844. result.m[8] = matrix.m[2];
  1845. result.m[9] = matrix.m[6];
  1846. result.m[10] = matrix.m[10];
  1847. result.m[11] = matrix.m[14];
  1848. result.m[12] = matrix.m[3];
  1849. result.m[13] = matrix.m[7];
  1850. result.m[14] = matrix.m[11];
  1851. result.m[15] = matrix.m[15];
  1852. return result;
  1853. };
  1854. Matrix.Reflection = function (plane) {
  1855. var matrix = new Matrix();
  1856. Matrix.ReflectionToRef(plane, matrix);
  1857. return matrix;
  1858. };
  1859. Matrix.ReflectionToRef = function (plane, result) {
  1860. plane.normalize();
  1861. var x = plane.normal.x;
  1862. var y = plane.normal.y;
  1863. var z = plane.normal.z;
  1864. var temp = -2 * x;
  1865. var temp2 = -2 * y;
  1866. var temp3 = -2 * z;
  1867. result.m[0] = (temp * x) + 1;
  1868. result.m[1] = temp2 * x;
  1869. result.m[2] = temp3 * x;
  1870. result.m[3] = 0.0;
  1871. result.m[4] = temp * y;
  1872. result.m[5] = (temp2 * y) + 1;
  1873. result.m[6] = temp3 * y;
  1874. result.m[7] = 0.0;
  1875. result.m[8] = temp * z;
  1876. result.m[9] = temp2 * z;
  1877. result.m[10] = (temp3 * z) + 1;
  1878. result.m[11] = 0.0;
  1879. result.m[12] = temp * plane.d;
  1880. result.m[13] = temp2 * plane.d;
  1881. result.m[14] = temp3 * plane.d;
  1882. result.m[15] = 1.0;
  1883. };
  1884. Matrix._tempQuaternion = new Quaternion();
  1885. Matrix._xAxis = Vector3.Zero();
  1886. Matrix._yAxis = Vector3.Zero();
  1887. Matrix._zAxis = Vector3.Zero();
  1888. return Matrix;
  1889. })();
  1890. BABYLON.Matrix = Matrix;
  1891. var Plane = (function () {
  1892. function Plane(a, b, c, d) {
  1893. this.normal = new Vector3(a, b, c);
  1894. this.d = d;
  1895. }
  1896. Plane.prototype.asArray = function () {
  1897. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  1898. };
  1899. // Methods
  1900. Plane.prototype.clone = function () {
  1901. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  1902. };
  1903. Plane.prototype.normalize = function () {
  1904. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  1905. var magnitude = 0;
  1906. if (norm !== 0) {
  1907. magnitude = 1.0 / norm;
  1908. }
  1909. this.normal.x *= magnitude;
  1910. this.normal.y *= magnitude;
  1911. this.normal.z *= magnitude;
  1912. this.d *= magnitude;
  1913. return this;
  1914. };
  1915. Plane.prototype.transform = function (transformation) {
  1916. var transposedMatrix = Matrix.Transpose(transformation);
  1917. var x = this.normal.x;
  1918. var y = this.normal.y;
  1919. var z = this.normal.z;
  1920. var d = this.d;
  1921. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  1922. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  1923. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  1924. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  1925. return new Plane(normalX, normalY, normalZ, finalD);
  1926. };
  1927. Plane.prototype.dotCoordinate = function (point) {
  1928. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  1929. };
  1930. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  1931. var x1 = point2.x - point1.x;
  1932. var y1 = point2.y - point1.y;
  1933. var z1 = point2.z - point1.z;
  1934. var x2 = point3.x - point1.x;
  1935. var y2 = point3.y - point1.y;
  1936. var z2 = point3.z - point1.z;
  1937. var yz = (y1 * z2) - (z1 * y2);
  1938. var xz = (z1 * x2) - (x1 * z2);
  1939. var xy = (x1 * y2) - (y1 * x2);
  1940. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  1941. var invPyth;
  1942. if (pyth !== 0) {
  1943. invPyth = 1.0 / pyth;
  1944. }
  1945. else {
  1946. invPyth = 0;
  1947. }
  1948. this.normal.x = yz * invPyth;
  1949. this.normal.y = xz * invPyth;
  1950. this.normal.z = xy * invPyth;
  1951. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  1952. return this;
  1953. };
  1954. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  1955. var dot = Vector3.Dot(this.normal, direction);
  1956. return (dot <= epsilon);
  1957. };
  1958. Plane.prototype.signedDistanceTo = function (point) {
  1959. return Vector3.Dot(point, this.normal) + this.d;
  1960. };
  1961. // Statics
  1962. Plane.FromArray = function (array) {
  1963. return new Plane(array[0], array[1], array[2], array[3]);
  1964. };
  1965. Plane.FromPoints = function (point1, point2, point3) {
  1966. var result = new Plane(0, 0, 0, 0);
  1967. result.copyFromPoints(point1, point2, point3);
  1968. return result;
  1969. };
  1970. Plane.FromPositionAndNormal = function (origin, normal) {
  1971. var result = new Plane(0, 0, 0, 0);
  1972. normal.normalize();
  1973. result.normal = normal;
  1974. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  1975. return result;
  1976. };
  1977. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  1978. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  1979. return Vector3.Dot(point, normal) + d;
  1980. };
  1981. return Plane;
  1982. })();
  1983. BABYLON.Plane = Plane;
  1984. var Viewport = (function () {
  1985. function Viewport(x, y, width, height) {
  1986. this.x = x;
  1987. this.y = y;
  1988. this.width = width;
  1989. this.height = height;
  1990. }
  1991. Viewport.prototype.toGlobal = function (engine) {
  1992. var width = engine.getRenderWidth();
  1993. var height = engine.getRenderHeight();
  1994. return new Viewport(this.x * width, this.y * height, this.width * width, this.height * height);
  1995. };
  1996. return Viewport;
  1997. })();
  1998. BABYLON.Viewport = Viewport;
  1999. var Frustum = (function () {
  2000. function Frustum() {
  2001. }
  2002. Frustum.GetPlanes = function (transform) {
  2003. var frustumPlanes = [];
  2004. for (var index = 0; index < 6; index++) {
  2005. frustumPlanes.push(new Plane(0, 0, 0, 0));
  2006. }
  2007. Frustum.GetPlanesToRef(transform, frustumPlanes);
  2008. return frustumPlanes;
  2009. };
  2010. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  2011. // Near
  2012. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  2013. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  2014. frustumPlanes[0].normal.z = transform.m[10] + transform.m[10];
  2015. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  2016. frustumPlanes[0].normalize();
  2017. // Far
  2018. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  2019. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  2020. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  2021. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  2022. frustumPlanes[1].normalize();
  2023. // Left
  2024. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  2025. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  2026. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  2027. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  2028. frustumPlanes[2].normalize();
  2029. // Right
  2030. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  2031. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  2032. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  2033. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  2034. frustumPlanes[3].normalize();
  2035. // Top
  2036. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  2037. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  2038. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  2039. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  2040. frustumPlanes[4].normalize();
  2041. // Bottom
  2042. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  2043. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  2044. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  2045. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  2046. frustumPlanes[5].normalize();
  2047. };
  2048. return Frustum;
  2049. })();
  2050. BABYLON.Frustum = Frustum;
  2051. var Ray = (function () {
  2052. function Ray(origin, direction, length) {
  2053. if (length === void 0) { length = Number.MAX_VALUE; }
  2054. this.origin = origin;
  2055. this.direction = direction;
  2056. this.length = length;
  2057. }
  2058. // Methods
  2059. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  2060. var d = 0.0;
  2061. var maxValue = Number.MAX_VALUE;
  2062. if (Math.abs(this.direction.x) < 0.0000001) {
  2063. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  2064. return false;
  2065. }
  2066. }
  2067. else {
  2068. var inv = 1.0 / this.direction.x;
  2069. var min = (minimum.x - this.origin.x) * inv;
  2070. var max = (maximum.x - this.origin.x) * inv;
  2071. if (max === -Infinity) {
  2072. max = Infinity;
  2073. }
  2074. if (min > max) {
  2075. var temp = min;
  2076. min = max;
  2077. max = temp;
  2078. }
  2079. d = Math.max(min, d);
  2080. maxValue = Math.min(max, maxValue);
  2081. if (d > maxValue) {
  2082. return false;
  2083. }
  2084. }
  2085. if (Math.abs(this.direction.y) < 0.0000001) {
  2086. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  2087. return false;
  2088. }
  2089. }
  2090. else {
  2091. inv = 1.0 / this.direction.y;
  2092. min = (minimum.y - this.origin.y) * inv;
  2093. max = (maximum.y - this.origin.y) * inv;
  2094. if (max === -Infinity) {
  2095. max = Infinity;
  2096. }
  2097. if (min > max) {
  2098. temp = min;
  2099. min = max;
  2100. max = temp;
  2101. }
  2102. d = Math.max(min, d);
  2103. maxValue = Math.min(max, maxValue);
  2104. if (d > maxValue) {
  2105. return false;
  2106. }
  2107. }
  2108. if (Math.abs(this.direction.z) < 0.0000001) {
  2109. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  2110. return false;
  2111. }
  2112. }
  2113. else {
  2114. inv = 1.0 / this.direction.z;
  2115. min = (minimum.z - this.origin.z) * inv;
  2116. max = (maximum.z - this.origin.z) * inv;
  2117. if (max === -Infinity) {
  2118. max = Infinity;
  2119. }
  2120. if (min > max) {
  2121. temp = min;
  2122. min = max;
  2123. max = temp;
  2124. }
  2125. d = Math.max(min, d);
  2126. maxValue = Math.min(max, maxValue);
  2127. if (d > maxValue) {
  2128. return false;
  2129. }
  2130. }
  2131. return true;
  2132. };
  2133. Ray.prototype.intersectsBox = function (box) {
  2134. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  2135. };
  2136. Ray.prototype.intersectsSphere = function (sphere) {
  2137. var x = sphere.center.x - this.origin.x;
  2138. var y = sphere.center.y - this.origin.y;
  2139. var z = sphere.center.z - this.origin.z;
  2140. var pyth = (x * x) + (y * y) + (z * z);
  2141. var rr = sphere.radius * sphere.radius;
  2142. if (pyth <= rr) {
  2143. return true;
  2144. }
  2145. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  2146. if (dot < 0.0) {
  2147. return false;
  2148. }
  2149. var temp = pyth - (dot * dot);
  2150. return temp <= rr;
  2151. };
  2152. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  2153. if (!this._edge1) {
  2154. this._edge1 = Vector3.Zero();
  2155. this._edge2 = Vector3.Zero();
  2156. this._pvec = Vector3.Zero();
  2157. this._tvec = Vector3.Zero();
  2158. this._qvec = Vector3.Zero();
  2159. }
  2160. vertex1.subtractToRef(vertex0, this._edge1);
  2161. vertex2.subtractToRef(vertex0, this._edge2);
  2162. Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  2163. var det = Vector3.Dot(this._edge1, this._pvec);
  2164. if (det === 0) {
  2165. return null;
  2166. }
  2167. var invdet = 1 / det;
  2168. this.origin.subtractToRef(vertex0, this._tvec);
  2169. var bu = Vector3.Dot(this._tvec, this._pvec) * invdet;
  2170. if (bu < 0 || bu > 1.0) {
  2171. return null;
  2172. }
  2173. Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  2174. var bv = Vector3.Dot(this.direction, this._qvec) * invdet;
  2175. if (bv < 0 || bu + bv > 1.0) {
  2176. return null;
  2177. }
  2178. //check if the distance is longer than the predefined length.
  2179. var distance = Vector3.Dot(this._edge2, this._qvec) * invdet;
  2180. if (distance > this.length) {
  2181. return null;
  2182. }
  2183. return new BABYLON.IntersectionInfo(bu, bv, distance);
  2184. };
  2185. // Statics
  2186. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  2187. var start = Vector3.Unproject(new Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  2188. var end = Vector3.Unproject(new Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  2189. var direction = end.subtract(start);
  2190. direction.normalize();
  2191. return new Ray(start, direction);
  2192. };
  2193. /**
  2194. * 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
  2195. * transformed to the given world matrix.
  2196. * @param origin The origin point
  2197. * @param end The end point
  2198. * @param world a matrix to transform the ray to. Default is the identity matrix.
  2199. */
  2200. Ray.CreateNewFromTo = function (origin, end, world) {
  2201. if (world === void 0) { world = Matrix.Identity(); }
  2202. var direction = end.subtract(origin);
  2203. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  2204. direction.normalize();
  2205. return Ray.Transform(new Ray(origin, direction, length), world);
  2206. };
  2207. Ray.Transform = function (ray, matrix) {
  2208. var newOrigin = Vector3.TransformCoordinates(ray.origin, matrix);
  2209. var newDirection = Vector3.TransformNormal(ray.direction, matrix);
  2210. return new Ray(newOrigin, newDirection, ray.length);
  2211. };
  2212. return Ray;
  2213. })();
  2214. BABYLON.Ray = Ray;
  2215. (function (Space) {
  2216. Space[Space["LOCAL"] = 0] = "LOCAL";
  2217. Space[Space["WORLD"] = 1] = "WORLD";
  2218. })(BABYLON.Space || (BABYLON.Space = {}));
  2219. var Space = BABYLON.Space;
  2220. var Axis = (function () {
  2221. function Axis() {
  2222. }
  2223. Axis.X = new Vector3(1, 0, 0);
  2224. Axis.Y = new Vector3(0, 1, 0);
  2225. Axis.Z = new Vector3(0, 0, 1);
  2226. return Axis;
  2227. })();
  2228. BABYLON.Axis = Axis;
  2229. ;
  2230. var BezierCurve = (function () {
  2231. function BezierCurve() {
  2232. }
  2233. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  2234. // Extract X (which is equal to time here)
  2235. var f0 = 1 - 3 * x2 + 3 * x1;
  2236. var f1 = 3 * x2 - 6 * x1;
  2237. var f2 = 3 * x1;
  2238. var refinedT = t;
  2239. for (var i = 0; i < 5; i++) {
  2240. var refinedT2 = refinedT * refinedT;
  2241. var refinedT3 = refinedT2 * refinedT;
  2242. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  2243. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  2244. refinedT -= (x - t) * slope;
  2245. refinedT = Math.min(1, Math.max(0, refinedT));
  2246. }
  2247. // Resolve cubic bezier for the given x
  2248. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 + 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 + Math.pow(refinedT, 3);
  2249. };
  2250. return BezierCurve;
  2251. })();
  2252. BABYLON.BezierCurve = BezierCurve;
  2253. (function (Orientation) {
  2254. Orientation[Orientation["CW"] = 0] = "CW";
  2255. Orientation[Orientation["CCW"] = 1] = "CCW";
  2256. })(BABYLON.Orientation || (BABYLON.Orientation = {}));
  2257. var Orientation = BABYLON.Orientation;
  2258. var Angle = (function () {
  2259. function Angle(radians) {
  2260. var _this = this;
  2261. this.degrees = function () { return _this._radians * 180 / Math.PI; };
  2262. this.radians = function () { return _this._radians; };
  2263. this._radians = radians;
  2264. if (this._radians < 0)
  2265. this._radians += (2 * Math.PI);
  2266. }
  2267. Angle.BetweenTwoPoints = function (a, b) {
  2268. var delta = b.subtract(a);
  2269. var theta = Math.atan2(delta.y, delta.x);
  2270. return new Angle(theta);
  2271. };
  2272. Angle.FromRadians = function (radians) {
  2273. return new Angle(radians);
  2274. };
  2275. Angle.FromDegrees = function (degrees) {
  2276. return new Angle(degrees * Math.PI / 180);
  2277. };
  2278. return Angle;
  2279. })();
  2280. BABYLON.Angle = Angle;
  2281. var Arc2 = (function () {
  2282. function Arc2(startPoint, midPoint, endPoint) {
  2283. this.startPoint = startPoint;
  2284. this.midPoint = midPoint;
  2285. this.endPoint = endPoint;
  2286. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  2287. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  2288. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  2289. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  2290. 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);
  2291. this.radius = this.centerPoint.subtract(this.startPoint).length();
  2292. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  2293. var a1 = this.startAngle.degrees();
  2294. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  2295. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  2296. // angles correction
  2297. if (a2 - a1 > +180.0)
  2298. a2 -= 360.0;
  2299. if (a2 - a1 < -180.0)
  2300. a2 += 360.0;
  2301. if (a3 - a2 > +180.0)
  2302. a3 -= 360.0;
  2303. if (a3 - a2 < -180.0)
  2304. a3 += 360.0;
  2305. this.orientation = (a2 - a1) < 0 ? 0 /* CW */ : 1 /* CCW */;
  2306. this.angle = Angle.FromDegrees(this.orientation === 0 /* CW */ ? a1 - a3 : a3 - a1);
  2307. }
  2308. return Arc2;
  2309. })();
  2310. BABYLON.Arc2 = Arc2;
  2311. var PathCursor = (function () {
  2312. function PathCursor(path) {
  2313. this.path = path;
  2314. this._onchange = new Array();
  2315. this.value = 0;
  2316. this.animations = new Array();
  2317. }
  2318. PathCursor.prototype.getPoint = function () {
  2319. var point = this.path.getPointAtLengthPosition(this.value);
  2320. return new Vector3(point.x, 0, point.y);
  2321. };
  2322. PathCursor.prototype.moveAhead = function (step) {
  2323. if (step === void 0) { step = 0.002; }
  2324. this.move(step);
  2325. return this;
  2326. };
  2327. PathCursor.prototype.moveBack = function (step) {
  2328. if (step === void 0) { step = 0.002; }
  2329. this.move(-step);
  2330. return this;
  2331. };
  2332. PathCursor.prototype.move = function (step) {
  2333. if (Math.abs(step) > 1) {
  2334. throw "step size should be less than 1.";
  2335. }
  2336. this.value += step;
  2337. this.ensureLimits();
  2338. this.raiseOnChange();
  2339. return this;
  2340. };
  2341. PathCursor.prototype.ensureLimits = function () {
  2342. while (this.value > 1) {
  2343. this.value -= 1;
  2344. }
  2345. while (this.value < 0) {
  2346. this.value += 1;
  2347. }
  2348. return this;
  2349. };
  2350. // used by animation engine
  2351. PathCursor.prototype.markAsDirty = function (propertyName) {
  2352. this.ensureLimits();
  2353. this.raiseOnChange();
  2354. return this;
  2355. };
  2356. PathCursor.prototype.raiseOnChange = function () {
  2357. var _this = this;
  2358. this._onchange.forEach(function (f) { return f(_this); });
  2359. return this;
  2360. };
  2361. PathCursor.prototype.onchange = function (f) {
  2362. this._onchange.push(f);
  2363. return this;
  2364. };
  2365. return PathCursor;
  2366. })();
  2367. BABYLON.PathCursor = PathCursor;
  2368. var Path2 = (function () {
  2369. function Path2(x, y) {
  2370. this._points = new Array();
  2371. this._length = 0;
  2372. this.closed = false;
  2373. this._points.push(new Vector2(x, y));
  2374. }
  2375. Path2.prototype.addLineTo = function (x, y) {
  2376. if (closed) {
  2377. BABYLON.Tools.Error("cannot add lines to closed paths");
  2378. return this;
  2379. }
  2380. var newPoint = new Vector2(x, y);
  2381. var previousPoint = this._points[this._points.length - 1];
  2382. this._points.push(newPoint);
  2383. this._length += newPoint.subtract(previousPoint).length();
  2384. return this;
  2385. };
  2386. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  2387. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  2388. if (closed) {
  2389. BABYLON.Tools.Error("cannot add arcs to closed paths");
  2390. return this;
  2391. }
  2392. var startPoint = this._points[this._points.length - 1];
  2393. var midPoint = new Vector2(midX, midY);
  2394. var endPoint = new Vector2(endX, endY);
  2395. var arc = new Arc2(startPoint, midPoint, endPoint);
  2396. var increment = arc.angle.radians() / numberOfSegments;
  2397. if (arc.orientation === 0 /* CW */)
  2398. increment *= -1;
  2399. var currentAngle = arc.startAngle.radians() + increment;
  2400. for (var i = 0; i < numberOfSegments; i++) {
  2401. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  2402. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  2403. this.addLineTo(x, y);
  2404. currentAngle += increment;
  2405. }
  2406. return this;
  2407. };
  2408. Path2.prototype.close = function () {
  2409. this.closed = true;
  2410. return this;
  2411. };
  2412. Path2.prototype.length = function () {
  2413. var result = this._length;
  2414. if (!this.closed) {
  2415. var lastPoint = this._points[this._points.length - 1];
  2416. var firstPoint = this._points[0];
  2417. result += (firstPoint.subtract(lastPoint).length());
  2418. }
  2419. return result;
  2420. };
  2421. Path2.prototype.getPoints = function () {
  2422. return this._points;
  2423. };
  2424. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  2425. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  2426. BABYLON.Tools.Error("normalized length position should be between 0 and 1.");
  2427. return Vector2.Zero();
  2428. }
  2429. var lengthPosition = normalizedLengthPosition * this.length();
  2430. var previousOffset = 0;
  2431. for (var i = 0; i < this._points.length; i++) {
  2432. var j = (i + 1) % this._points.length;
  2433. var a = this._points[i];
  2434. var b = this._points[j];
  2435. var bToA = b.subtract(a);
  2436. var nextOffset = (bToA.length() + previousOffset);
  2437. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  2438. var dir = bToA.normalize();
  2439. var localOffset = lengthPosition - previousOffset;
  2440. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  2441. }
  2442. previousOffset = nextOffset;
  2443. }
  2444. BABYLON.Tools.Error("internal error");
  2445. return Vector2.Zero();
  2446. };
  2447. Path2.StartingAt = function (x, y) {
  2448. return new Path2(x, y);
  2449. };
  2450. return Path2;
  2451. })();
  2452. BABYLON.Path2 = Path2;
  2453. var Path3D = (function () {
  2454. function Path3D(path) {
  2455. this.path = path;
  2456. this._curve = new Array();
  2457. this._distances = new Array();
  2458. this._tangents = new Array();
  2459. this._normals = new Array();
  2460. this._binormals = new Array();
  2461. this._curve = path.slice(); // copy array
  2462. var l = this._curve.length;
  2463. // first and last tangents
  2464. this._tangents[0] = this._curve[1].subtract(this._curve[0]);
  2465. this._tangents[0].normalize();
  2466. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  2467. this._tangents[l - 1].normalize();
  2468. // normals and binormals at first point : arbitrary vector with _normalVector()
  2469. var tg0 = this._tangents[0];
  2470. var pp0 = this._normalVector(this._curve[0], tg0);
  2471. this._normals[0] = pp0;
  2472. this._normals[0].normalize();
  2473. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  2474. this._normals[0].normalize();
  2475. this._distances[0] = 0;
  2476. // normals and binormals : next points
  2477. var prev; // previous vector (segment)
  2478. var cur; // current vector (segment)
  2479. var curTang; // current tangent
  2480. var prevNorm; // previous normal
  2481. var prevBinor; // previous binormal
  2482. for (var i = 1; i < l; i++) {
  2483. // tangents
  2484. prev = this._curve[i].subtract(this._curve[i - 1]);
  2485. if (i < l - 1) {
  2486. cur = this._curve[i + 1].subtract(this._curve[i]);
  2487. this._tangents[i] = prev.add(cur);
  2488. this._tangents[i].normalize();
  2489. }
  2490. this._distances[i] = this._distances[i - 1] + prev.length();
  2491. // normals and binormals
  2492. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  2493. curTang = this._tangents[i];
  2494. prevNorm = this._normals[i - 1];
  2495. prevBinor = this._binormals[i - 1];
  2496. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  2497. this._normals[i].normalize();
  2498. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  2499. this._binormals[i].normalize();
  2500. }
  2501. }
  2502. Path3D.prototype.getCurve = function () {
  2503. return this._curve;
  2504. };
  2505. Path3D.prototype.getTangents = function () {
  2506. return this._tangents;
  2507. };
  2508. Path3D.prototype.getNormals = function () {
  2509. return this._normals;
  2510. };
  2511. Path3D.prototype.getBinormals = function () {
  2512. return this._binormals;
  2513. };
  2514. Path3D.prototype.getDistances = function () {
  2515. return this._distances;
  2516. };
  2517. // private function normalVector(v0, vt) :
  2518. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  2519. Path3D.prototype._normalVector = function (v0, vt) {
  2520. var point;
  2521. if (vt.x !== 1) {
  2522. point = new Vector3(1, 0, 0);
  2523. }
  2524. else if (vt.y !== 1) {
  2525. point = new Vector3(0, 1, 0);
  2526. }
  2527. else if (vt.z !== 1) {
  2528. point = new Vector3(0, 0, 1);
  2529. }
  2530. var normal0 = Vector3.Cross(vt, point);
  2531. normal0.normalize();
  2532. return normal0;
  2533. };
  2534. return Path3D;
  2535. })();
  2536. BABYLON.Path3D = Path3D;
  2537. var Curve3 = (function () {
  2538. function Curve3(points) {
  2539. this._points = points;
  2540. }
  2541. // QuadraticBezier(origin_V3, control_V3, destination_V3 )
  2542. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  2543. nbPoints = nbPoints > 2 ? nbPoints : 3;
  2544. var bez = new Array();
  2545. var step = 1 / nbPoints;
  2546. var equation = function (t, val0, val1, val2) {
  2547. var res = (1 - t) * (1 - t) * val0 + 2 * t * (1 - t) * val1 + t * t * val2;
  2548. return res;
  2549. };
  2550. for (var i = 0; i <= 1; i += step) {
  2551. 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)));
  2552. }
  2553. return new Curve3(bez);
  2554. };
  2555. // CubicBezier(origin_V3, control1_V3, control2_V3, destination_V3)
  2556. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  2557. nbPoints = nbPoints > 3 ? nbPoints : 4;
  2558. var bez = new Array();
  2559. var step = 1 / nbPoints;
  2560. var equation = function (t, val0, val1, val2, val3) {
  2561. 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;
  2562. return res;
  2563. };
  2564. for (var i = 0; i <= 1; i += step) {
  2565. 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)));
  2566. }
  2567. return new Curve3(bez);
  2568. };
  2569. Curve3.prototype.getPoints = function () {
  2570. return this._points;
  2571. };
  2572. return Curve3;
  2573. })();
  2574. BABYLON.Curve3 = Curve3;
  2575. // SIMD
  2576. if (window.SIMD !== undefined) {
  2577. // Replace functions
  2578. Matrix.prototype.multiplyToArray = Matrix.prototype.multiplyToArraySIMD;
  2579. Vector3.TransformCoordinatesToRef = Vector3.TransformCoordinatesToRefSIMD;
  2580. Vector3.TransformCoordinatesFromFloatsToRef = Vector3.TransformCoordinatesFromFloatsToRefSIMD;
  2581. }
  2582. })(BABYLON || (BABYLON = {}));
  2583. //# sourceMappingURL=babylon.math.js.mapvar BABYLON;
  2584. (function (BABYLON) {
  2585. // Screenshots
  2586. var screenshotCanvas;
  2587. var cloneValue = function (source, destinationObject) {
  2588. if (!source)
  2589. return null;
  2590. if (source instanceof BABYLON.Mesh) {
  2591. return null;
  2592. }
  2593. if (source instanceof BABYLON.SubMesh) {
  2594. return source.clone(destinationObject);
  2595. }
  2596. else if (source.clone) {
  2597. return source.clone();
  2598. }
  2599. return null;
  2600. };
  2601. var Tools = (function () {
  2602. function Tools() {
  2603. }
  2604. Tools.GetFilename = function (path) {
  2605. var index = path.lastIndexOf("/");
  2606. if (index < 0)
  2607. return path;
  2608. return path.substring(index + 1);
  2609. };
  2610. Tools.GetDOMTextContent = function (element) {
  2611. var result = "";
  2612. var child = element.firstChild;
  2613. while (child) {
  2614. if (child.nodeType === 3) {
  2615. result += child.textContent;
  2616. }
  2617. child = child.nextSibling;
  2618. }
  2619. return result;
  2620. };
  2621. Tools.ToDegrees = function (angle) {
  2622. return angle * 180 / Math.PI;
  2623. };
  2624. Tools.ToRadians = function (angle) {
  2625. return angle * Math.PI / 180;
  2626. };
  2627. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount) {
  2628. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  2629. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  2630. for (var index = indexStart; index < indexStart + indexCount; index++) {
  2631. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  2632. minimum = BABYLON.Vector3.Minimize(current, minimum);
  2633. maximum = BABYLON.Vector3.Maximize(current, maximum);
  2634. }
  2635. return {
  2636. minimum: minimum,
  2637. maximum: maximum
  2638. };
  2639. };
  2640. Tools.ExtractMinAndMax = function (positions, start, count) {
  2641. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  2642. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  2643. for (var index = start; index < start + count; index++) {
  2644. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  2645. minimum = BABYLON.Vector3.Minimize(current, minimum);
  2646. maximum = BABYLON.Vector3.Maximize(current, maximum);
  2647. }
  2648. return {
  2649. minimum: minimum,
  2650. maximum: maximum
  2651. };
  2652. };
  2653. Tools.MakeArray = function (obj, allowsNullUndefined) {
  2654. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  2655. return undefined;
  2656. return Array.isArray(obj) ? obj : [obj];
  2657. };
  2658. // Misc.
  2659. Tools.GetPointerPrefix = function () {
  2660. var eventPrefix = "pointer";
  2661. // Check if hand.js is referenced or if the browser natively supports pointer events
  2662. if (!navigator.pointerEnabled) {
  2663. eventPrefix = "mouse";
  2664. }
  2665. return eventPrefix;
  2666. };
  2667. Tools.QueueNewFrame = function (func) {
  2668. if (window.requestAnimationFrame)
  2669. window.requestAnimationFrame(func);
  2670. else if (window.msRequestAnimationFrame)
  2671. window.msRequestAnimationFrame(func);
  2672. else if (window.webkitRequestAnimationFrame)
  2673. window.webkitRequestAnimationFrame(func);
  2674. else if (window.mozRequestAnimationFrame)
  2675. window.mozRequestAnimationFrame(func);
  2676. else if (window.oRequestAnimationFrame)
  2677. window.oRequestAnimationFrame(func);
  2678. else {
  2679. window.setTimeout(func, 16);
  2680. }
  2681. };
  2682. Tools.RequestFullscreen = function (element) {
  2683. if (element.requestFullscreen)
  2684. element.requestFullscreen();
  2685. else if (element.msRequestFullscreen)
  2686. element.msRequestFullscreen();
  2687. else if (element.webkitRequestFullscreen)
  2688. element.webkitRequestFullscreen();
  2689. else if (element.mozRequestFullScreen)
  2690. element.mozRequestFullScreen();
  2691. };
  2692. Tools.ExitFullscreen = function () {
  2693. if (document.exitFullscreen) {
  2694. document.exitFullscreen();
  2695. }
  2696. else if (document.mozCancelFullScreen) {
  2697. document.mozCancelFullScreen();
  2698. }
  2699. else if (document.webkitCancelFullScreen) {
  2700. document.webkitCancelFullScreen();
  2701. }
  2702. else if (document.msCancelFullScreen) {
  2703. document.msCancelFullScreen();
  2704. }
  2705. };
  2706. // External files
  2707. Tools.CleanUrl = function (url) {
  2708. url = url.replace(/#/mg, "%23");
  2709. return url;
  2710. };
  2711. Tools.LoadImage = function (url, onload, onerror, database) {
  2712. url = Tools.CleanUrl(url);
  2713. var img = new Image();
  2714. if (url.substr(0, 5) !== "data:")
  2715. img.crossOrigin = 'anonymous';
  2716. img.onload = function () {
  2717. onload(img);
  2718. };
  2719. img.onerror = function (err) {
  2720. onerror(img, err);
  2721. };
  2722. var noIndexedDB = function () {
  2723. img.src = url;
  2724. };
  2725. var loadFromIndexedDB = function () {
  2726. database.loadImageFromDB(url, img);
  2727. };
  2728. //ANY database to do!
  2729. if (database && database.enableTexturesOffline && BABYLON.Database.isUASupportingBlobStorage) {
  2730. database.openAsync(loadFromIndexedDB, noIndexedDB);
  2731. }
  2732. else {
  2733. if (url.indexOf("file:") === -1) {
  2734. noIndexedDB();
  2735. }
  2736. else {
  2737. try {
  2738. var textureName = url.substring(5);
  2739. var blobURL;
  2740. try {
  2741. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  2742. }
  2743. catch (ex) {
  2744. // Chrome doesn't support oneTimeOnly parameter
  2745. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  2746. }
  2747. img.src = blobURL;
  2748. }
  2749. catch (e) {
  2750. Tools.Log("Error while trying to load texture: " + textureName);
  2751. img.src = null;
  2752. }
  2753. }
  2754. }
  2755. return img;
  2756. };
  2757. //ANY
  2758. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  2759. url = Tools.CleanUrl(url);
  2760. var noIndexedDB = function () {
  2761. var request = new XMLHttpRequest();
  2762. var loadUrl = Tools.BaseUrl + url;
  2763. request.open('GET', loadUrl, true);
  2764. if (useArrayBuffer) {
  2765. request.responseType = "arraybuffer";
  2766. }
  2767. request.onprogress = progressCallBack;
  2768. request.onreadystatechange = function () {
  2769. if (request.readyState === 4) {
  2770. if (request.status === 200 || Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  2771. callback(!useArrayBuffer ? request.responseText : request.response);
  2772. }
  2773. else {
  2774. if (onError) {
  2775. onError();
  2776. }
  2777. else {
  2778. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  2779. }
  2780. }
  2781. }
  2782. };
  2783. request.send(null);
  2784. };
  2785. var loadFromIndexedDB = function () {
  2786. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  2787. };
  2788. if (url.indexOf("file:") !== -1) {
  2789. var fileName = url.substring(5);
  2790. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, true);
  2791. }
  2792. else {
  2793. // Caching all files
  2794. if (database && database.enableSceneOffline) {
  2795. database.openAsync(loadFromIndexedDB, noIndexedDB);
  2796. }
  2797. else {
  2798. noIndexedDB();
  2799. }
  2800. }
  2801. };
  2802. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  2803. var reader = new FileReader();
  2804. reader.onload = function (e) {
  2805. //target doesn't have result from ts 1.3
  2806. callback(e.target['result']);
  2807. };
  2808. reader.onprogress = progressCallback;
  2809. reader.readAsDataURL(fileToLoad);
  2810. };
  2811. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  2812. var reader = new FileReader();
  2813. reader.onerror = function (e) {
  2814. Tools.Log("Error while reading file: " + fileToLoad.name);
  2815. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.81, 0], meshes: [], cameras: [], lights: [] }));
  2816. };
  2817. reader.onload = function (e) {
  2818. //target doesn't have result from ts 1.3
  2819. callback(e.target['result']);
  2820. };
  2821. reader.onprogress = progressCallBack;
  2822. if (!useArrayBuffer) {
  2823. // Asynchronous read
  2824. reader.readAsText(fileToLoad);
  2825. }
  2826. else {
  2827. reader.readAsArrayBuffer(fileToLoad);
  2828. }
  2829. };
  2830. // Misc.
  2831. Tools.Clamp = function (value, min, max) {
  2832. if (min === void 0) { min = 0; }
  2833. if (max === void 0) { max = 1; }
  2834. return Math.min(max, Math.max(min, value));
  2835. };
  2836. // Returns -1 when value is a negative number and
  2837. // +1 when value is a positive number.
  2838. Tools.Sign = function (value) {
  2839. value = +value; // convert to a number
  2840. if (value === 0 || isNaN(value))
  2841. return value;
  2842. return value > 0 ? 1 : -1;
  2843. };
  2844. Tools.Format = function (value, decimals) {
  2845. if (decimals === void 0) { decimals = 2; }
  2846. return value.toFixed(decimals);
  2847. };
  2848. Tools.CheckExtends = function (v, min, max) {
  2849. if (v.x < min.x)
  2850. min.x = v.x;
  2851. if (v.y < min.y)
  2852. min.y = v.y;
  2853. if (v.z < min.z)
  2854. min.z = v.z;
  2855. if (v.x > max.x)
  2856. max.x = v.x;
  2857. if (v.y > max.y)
  2858. max.y = v.y;
  2859. if (v.z > max.z)
  2860. max.z = v.z;
  2861. };
  2862. Tools.WithinEpsilon = function (a, b, epsilon) {
  2863. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  2864. var num = a - b;
  2865. return -epsilon <= num && num <= epsilon;
  2866. };
  2867. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  2868. for (var prop in source) {
  2869. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  2870. continue;
  2871. }
  2872. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  2873. continue;
  2874. }
  2875. var sourceValue = source[prop];
  2876. var typeOfSourceValue = typeof sourceValue;
  2877. if (typeOfSourceValue === "function") {
  2878. continue;
  2879. }
  2880. if (typeOfSourceValue === "object") {
  2881. if (sourceValue instanceof Array) {
  2882. destination[prop] = [];
  2883. if (sourceValue.length > 0) {
  2884. if (typeof sourceValue[0] == "object") {
  2885. for (var index = 0; index < sourceValue.length; index++) {
  2886. var clonedValue = cloneValue(sourceValue[index], destination);
  2887. if (destination[prop].indexOf(clonedValue) === -1) {
  2888. destination[prop].push(clonedValue);
  2889. }
  2890. }
  2891. }
  2892. else {
  2893. destination[prop] = sourceValue.slice(0);
  2894. }
  2895. }
  2896. }
  2897. else {
  2898. destination[prop] = cloneValue(sourceValue, destination);
  2899. }
  2900. }
  2901. else {
  2902. destination[prop] = sourceValue;
  2903. }
  2904. }
  2905. };
  2906. Tools.IsEmpty = function (obj) {
  2907. for (var i in obj) {
  2908. return false;
  2909. }
  2910. return true;
  2911. };
  2912. Tools.RegisterTopRootEvents = function (events) {
  2913. for (var index = 0; index < events.length; index++) {
  2914. var event = events[index];
  2915. window.addEventListener(event.name, event.handler, false);
  2916. try {
  2917. if (window.parent) {
  2918. window.parent.addEventListener(event.name, event.handler, false);
  2919. }
  2920. }
  2921. catch (e) {
  2922. }
  2923. }
  2924. };
  2925. Tools.UnregisterTopRootEvents = function (events) {
  2926. for (var index = 0; index < events.length; index++) {
  2927. var event = events[index];
  2928. window.removeEventListener(event.name, event.handler);
  2929. try {
  2930. if (window.parent) {
  2931. window.parent.removeEventListener(event.name, event.handler);
  2932. }
  2933. }
  2934. catch (e) {
  2935. }
  2936. }
  2937. };
  2938. Tools.DumpFramebuffer = function (width, height, engine) {
  2939. // Read the contents of the framebuffer
  2940. var numberOfChannelsByLine = width * 4;
  2941. var halfHeight = height / 2;
  2942. //Reading datas from WebGL
  2943. var data = engine.readPixels(0, 0, width, height);
  2944. for (var i = 0; i < halfHeight; i++) {
  2945. for (var j = 0; j < numberOfChannelsByLine; j++) {
  2946. var currentCell = j + i * numberOfChannelsByLine;
  2947. var targetLine = height - i - 1;
  2948. var targetCell = j + targetLine * numberOfChannelsByLine;
  2949. var temp = data[currentCell];
  2950. data[currentCell] = data[targetCell];
  2951. data[targetCell] = temp;
  2952. }
  2953. }
  2954. // Create a 2D canvas to store the result
  2955. if (!screenshotCanvas) {
  2956. screenshotCanvas = document.createElement('canvas');
  2957. }
  2958. screenshotCanvas.width = width;
  2959. screenshotCanvas.height = height;
  2960. var context = screenshotCanvas.getContext('2d');
  2961. // Copy the pixels to a 2D canvas
  2962. var imageData = context.createImageData(width, height);
  2963. //cast is due to ts error in lib.d.ts, see here - https://github.com/Microsoft/TypeScript/issues/949
  2964. var castData = imageData.data;
  2965. castData.set(data);
  2966. context.putImageData(imageData, 0, 0);
  2967. var base64Image = screenshotCanvas.toDataURL();
  2968. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  2969. if (("download" in document.createElement("a"))) {
  2970. var a = window.document.createElement("a");
  2971. a.href = base64Image;
  2972. var date = new Date();
  2973. var stringDate = date.getFullYear() + "/" + date.getMonth() + "/" + date.getDate() + "-" + date.getHours() + ":" + date.getMinutes();
  2974. a.setAttribute("download", "screenshot-" + stringDate + ".png");
  2975. window.document.body.appendChild(a);
  2976. a.addEventListener("click", function () {
  2977. a.parentElement.removeChild(a);
  2978. });
  2979. a.click();
  2980. }
  2981. else {
  2982. var newWindow = window.open("");
  2983. var img = newWindow.document.createElement("img");
  2984. img.src = base64Image;
  2985. newWindow.document.body.appendChild(img);
  2986. }
  2987. };
  2988. Tools.CreateScreenshot = function (engine, camera, size) {
  2989. var width;
  2990. var height;
  2991. var scene = camera.getScene();
  2992. var previousCamera = null;
  2993. if (scene.activeCamera !== camera) {
  2994. previousCamera = scene.activeCamera;
  2995. scene.activeCamera = camera;
  2996. }
  2997. //If a precision value is specified
  2998. if (size.precision) {
  2999. width = Math.round(engine.getRenderWidth() * size.precision);
  3000. height = Math.round(width / engine.getAspectRatio(camera));
  3001. size = { width: width, height: height };
  3002. }
  3003. else if (size.width && size.height) {
  3004. width = size.width;
  3005. height = size.height;
  3006. }
  3007. else if (size.width && !size.height) {
  3008. width = size.width;
  3009. height = Math.round(width / engine.getAspectRatio(camera));
  3010. size = { width: width, height: height };
  3011. }
  3012. else if (size.height && !size.width) {
  3013. height = size.height;
  3014. width = Math.round(height * engine.getAspectRatio(camera));
  3015. size = { width: width, height: height };
  3016. }
  3017. else if (!isNaN(size)) {
  3018. height = size;
  3019. width = size;
  3020. }
  3021. else {
  3022. Tools.Error("Invalid 'size' parameter !");
  3023. return;
  3024. }
  3025. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  3026. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false);
  3027. texture.renderList = scene.meshes;
  3028. texture.onAfterRender = function () {
  3029. Tools.DumpFramebuffer(width, height, engine);
  3030. };
  3031. scene.incrementRenderId();
  3032. texture.render(true);
  3033. texture.dispose();
  3034. if (previousCamera) {
  3035. scene.activeCamera = previousCamera;
  3036. }
  3037. };
  3038. // XHR response validator for local file scenario
  3039. Tools.ValidateXHRData = function (xhr, dataType) {
  3040. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  3041. if (dataType === void 0) { dataType = 7; }
  3042. try {
  3043. if (dataType & 1) {
  3044. if (xhr.responseText && xhr.responseText.length > 0) {
  3045. return true;
  3046. }
  3047. else if (dataType === 1) {
  3048. return false;
  3049. }
  3050. }
  3051. if (dataType & 2) {
  3052. // Check header width and height since there is no "TGA" magic number
  3053. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  3054. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  3055. return true;
  3056. }
  3057. else if (dataType === 2) {
  3058. return false;
  3059. }
  3060. }
  3061. if (dataType & 4) {
  3062. // Check for the "DDS" magic number
  3063. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  3064. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  3065. return true;
  3066. }
  3067. else {
  3068. return false;
  3069. }
  3070. }
  3071. }
  3072. catch (e) {
  3073. }
  3074. return false;
  3075. };
  3076. Object.defineProperty(Tools, "NoneLogLevel", {
  3077. get: function () {
  3078. return Tools._NoneLogLevel;
  3079. },
  3080. enumerable: true,
  3081. configurable: true
  3082. });
  3083. Object.defineProperty(Tools, "MessageLogLevel", {
  3084. get: function () {
  3085. return Tools._MessageLogLevel;
  3086. },
  3087. enumerable: true,
  3088. configurable: true
  3089. });
  3090. Object.defineProperty(Tools, "WarningLogLevel", {
  3091. get: function () {
  3092. return Tools._WarningLogLevel;
  3093. },
  3094. enumerable: true,
  3095. configurable: true
  3096. });
  3097. Object.defineProperty(Tools, "ErrorLogLevel", {
  3098. get: function () {
  3099. return Tools._ErrorLogLevel;
  3100. },
  3101. enumerable: true,
  3102. configurable: true
  3103. });
  3104. Object.defineProperty(Tools, "AllLogLevel", {
  3105. get: function () {
  3106. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  3107. },
  3108. enumerable: true,
  3109. configurable: true
  3110. });
  3111. Tools._AddLogEntry = function (entry) {
  3112. Tools._LogCache = entry + Tools._LogCache;
  3113. if (Tools.OnNewCacheEntry) {
  3114. Tools.OnNewCacheEntry(entry);
  3115. }
  3116. };
  3117. Tools._FormatMessage = function (message) {
  3118. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  3119. var date = new Date();
  3120. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  3121. };
  3122. Tools._LogDisabled = function (message) {
  3123. // nothing to do
  3124. };
  3125. Tools._LogEnabled = function (message) {
  3126. var formattedMessage = Tools._FormatMessage(message);
  3127. console.log("BJS - " + formattedMessage);
  3128. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  3129. Tools._AddLogEntry(entry);
  3130. };
  3131. Tools._WarnDisabled = function (message) {
  3132. // nothing to do
  3133. };
  3134. Tools._WarnEnabled = function (message) {
  3135. var formattedMessage = Tools._FormatMessage(message);
  3136. console.warn("BJS - " + formattedMessage);
  3137. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  3138. Tools._AddLogEntry(entry);
  3139. };
  3140. Tools._ErrorDisabled = function (message) {
  3141. // nothing to do
  3142. };
  3143. Tools._ErrorEnabled = function (message) {
  3144. var formattedMessage = Tools._FormatMessage(message);
  3145. console.error("BJS - " + formattedMessage);
  3146. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  3147. Tools._AddLogEntry(entry);
  3148. };
  3149. Object.defineProperty(Tools, "LogCache", {
  3150. get: function () {
  3151. return Tools._LogCache;
  3152. },
  3153. enumerable: true,
  3154. configurable: true
  3155. });
  3156. Object.defineProperty(Tools, "LogLevels", {
  3157. set: function (level) {
  3158. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  3159. Tools.Log = Tools._LogEnabled;
  3160. }
  3161. else {
  3162. Tools.Log = Tools._LogDisabled;
  3163. }
  3164. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  3165. Tools.Warn = Tools._WarnEnabled;
  3166. }
  3167. else {
  3168. Tools.Warn = Tools._WarnDisabled;
  3169. }
  3170. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  3171. Tools.Error = Tools._ErrorEnabled;
  3172. }
  3173. else {
  3174. Tools.Error = Tools._ErrorDisabled;
  3175. }
  3176. },
  3177. enumerable: true,
  3178. configurable: true
  3179. });
  3180. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  3181. get: function () {
  3182. return Tools._PerformanceNoneLogLevel;
  3183. },
  3184. enumerable: true,
  3185. configurable: true
  3186. });
  3187. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  3188. get: function () {
  3189. return Tools._PerformanceUserMarkLogLevel;
  3190. },
  3191. enumerable: true,
  3192. configurable: true
  3193. });
  3194. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  3195. get: function () {
  3196. return Tools._PerformanceConsoleLogLevel;
  3197. },
  3198. enumerable: true,
  3199. configurable: true
  3200. });
  3201. Object.defineProperty(Tools, "PerformanceLogLevel", {
  3202. set: function (level) {
  3203. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  3204. Tools.StartPerformanceCounter = Tools._StartUserMark;
  3205. Tools.EndPerformanceCounter = Tools._EndUserMark;
  3206. return;
  3207. }
  3208. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  3209. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  3210. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  3211. return;
  3212. }
  3213. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  3214. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  3215. },
  3216. enumerable: true,
  3217. configurable: true
  3218. });
  3219. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  3220. };
  3221. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  3222. };
  3223. Tools._StartUserMark = function (counterName, condition) {
  3224. if (condition === void 0) { condition = true; }
  3225. if (!condition || !Tools._performance.mark) {
  3226. return;
  3227. }
  3228. Tools._performance.mark(counterName + "-Begin");
  3229. };
  3230. Tools._EndUserMark = function (counterName, condition) {
  3231. if (condition === void 0) { condition = true; }
  3232. if (!condition || !Tools._performance.mark) {
  3233. return;
  3234. }
  3235. Tools._performance.mark(counterName + "-End");
  3236. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  3237. };
  3238. Tools._StartPerformanceConsole = function (counterName, condition) {
  3239. if (condition === void 0) { condition = true; }
  3240. if (!condition) {
  3241. return;
  3242. }
  3243. Tools._StartUserMark(counterName, condition);
  3244. if (console.time) {
  3245. console.time(counterName);
  3246. }
  3247. };
  3248. Tools._EndPerformanceConsole = function (counterName, condition) {
  3249. if (condition === void 0) { condition = true; }
  3250. if (!condition) {
  3251. return;
  3252. }
  3253. Tools._EndUserMark(counterName, condition);
  3254. if (console.time) {
  3255. console.timeEnd(counterName);
  3256. }
  3257. };
  3258. Object.defineProperty(Tools, "Now", {
  3259. get: function () {
  3260. if (window.performance && window.performance.now) {
  3261. return window.performance.now();
  3262. }
  3263. return new Date().getTime();
  3264. },
  3265. enumerable: true,
  3266. configurable: true
  3267. });
  3268. // Deprecated
  3269. Tools.GetFps = function () {
  3270. Tools.Warn("Tools.GetFps() is deprecated. Please use engine.getFps() instead");
  3271. return 0;
  3272. };
  3273. Tools.BaseUrl = "";
  3274. Tools.GetExponantOfTwo = function (value, max) {
  3275. var count = 1;
  3276. do {
  3277. count *= 2;
  3278. } while (count < value);
  3279. if (count > max)
  3280. count = max;
  3281. return count;
  3282. };
  3283. // Logs
  3284. Tools._NoneLogLevel = 0;
  3285. Tools._MessageLogLevel = 1;
  3286. Tools._WarningLogLevel = 2;
  3287. Tools._ErrorLogLevel = 4;
  3288. Tools._LogCache = "";
  3289. Tools.Log = Tools._LogEnabled;
  3290. Tools.Warn = Tools._WarnEnabled;
  3291. Tools.Error = Tools._ErrorEnabled;
  3292. // Performances
  3293. Tools._PerformanceNoneLogLevel = 0;
  3294. Tools._PerformanceUserMarkLogLevel = 1;
  3295. Tools._PerformanceConsoleLogLevel = 2;
  3296. Tools._performance = window.performance;
  3297. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  3298. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  3299. return Tools;
  3300. })();
  3301. BABYLON.Tools = Tools;
  3302. /**
  3303. * An implementation of a loop for asynchronous functions.
  3304. */
  3305. var AsyncLoop = (function () {
  3306. /**
  3307. * Constroctor.
  3308. * @param iterations the number of iterations.
  3309. * @param _fn the function to run each iteration
  3310. * @param _successCallback the callback that will be called upon succesful execution
  3311. * @param offset starting offset.
  3312. */
  3313. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  3314. if (offset === void 0) { offset = 0; }
  3315. this.iterations = iterations;
  3316. this._fn = _fn;
  3317. this._successCallback = _successCallback;
  3318. this.index = offset - 1;
  3319. this._done = false;
  3320. }
  3321. /**
  3322. * Execute the next iteration. Must be called after the last iteration was finished.
  3323. */
  3324. AsyncLoop.prototype.executeNext = function () {
  3325. if (!this._done) {
  3326. if (this.index + 1 < this.iterations) {
  3327. ++this.index;
  3328. this._fn(this);
  3329. }
  3330. else {
  3331. this.breakLoop();
  3332. }
  3333. }
  3334. };
  3335. /**
  3336. * Break the loop and run the success callback.
  3337. */
  3338. AsyncLoop.prototype.breakLoop = function () {
  3339. this._done = true;
  3340. this._successCallback();
  3341. };
  3342. /**
  3343. * Helper function
  3344. */
  3345. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  3346. if (offset === void 0) { offset = 0; }
  3347. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  3348. loop.executeNext();
  3349. return loop;
  3350. };
  3351. /**
  3352. * A for-loop that will run a given number of iterations synchronous and the rest async.
  3353. * @param iterations total number of iterations
  3354. * @param syncedIterations number of synchronous iterations in each async iteration.
  3355. * @param fn the function to call each iteration.
  3356. * @param callback a success call back that will be called when iterating stops.
  3357. * @param breakFunction a break condition (optional)
  3358. * @param timeout timeout settings for the setTimeout function. default - 0.
  3359. * @constructor
  3360. */
  3361. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  3362. if (timeout === void 0) { timeout = 0; }
  3363. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  3364. if (breakFunction && breakFunction())
  3365. loop.breakLoop();
  3366. else {
  3367. setTimeout(function () {
  3368. for (var i = 0; i < syncedIterations; ++i) {
  3369. var iteration = (loop.index * syncedIterations) + i;
  3370. if (iteration >= iterations)
  3371. break;
  3372. fn(iteration);
  3373. if (breakFunction && breakFunction()) {
  3374. loop.breakLoop();
  3375. break;
  3376. }
  3377. }
  3378. loop.executeNext();
  3379. }, timeout);
  3380. }
  3381. }, callback);
  3382. };
  3383. return AsyncLoop;
  3384. })();
  3385. BABYLON.AsyncLoop = AsyncLoop;
  3386. })(BABYLON || (BABYLON = {}));
  3387. //# sourceMappingURL=babylon.tools.js.mapvar BABYLON;
  3388. (function (BABYLON) {
  3389. var _DepthCullingState = (function () {
  3390. function _DepthCullingState() {
  3391. this._isDepthTestDirty = false;
  3392. this._isDepthMaskDirty = false;
  3393. this._isDepthFuncDirty = false;
  3394. this._isCullFaceDirty = false;
  3395. this._isCullDirty = false;
  3396. }
  3397. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  3398. get: function () {
  3399. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty;
  3400. },
  3401. enumerable: true,
  3402. configurable: true
  3403. });
  3404. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  3405. get: function () {
  3406. return this._cullFace;
  3407. },
  3408. set: function (value) {
  3409. if (this._cullFace === value) {
  3410. return;
  3411. }
  3412. this._cullFace = value;
  3413. this._isCullFaceDirty = true;
  3414. },
  3415. enumerable: true,
  3416. configurable: true
  3417. });
  3418. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  3419. get: function () {
  3420. return this._cull;
  3421. },
  3422. set: function (value) {
  3423. if (this._cull === value) {
  3424. return;
  3425. }
  3426. this._cull = value;
  3427. this._isCullDirty = true;
  3428. },
  3429. enumerable: true,
  3430. configurable: true
  3431. });
  3432. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  3433. get: function () {
  3434. return this._depthFunc;
  3435. },
  3436. set: function (value) {
  3437. if (this._depthFunc === value) {
  3438. return;
  3439. }
  3440. this._depthFunc = value;
  3441. this._isDepthFuncDirty = true;
  3442. },
  3443. enumerable: true,
  3444. configurable: true
  3445. });
  3446. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  3447. get: function () {
  3448. return this._depthMask;
  3449. },
  3450. set: function (value) {
  3451. if (this._depthMask === value) {
  3452. return;
  3453. }
  3454. this._depthMask = value;
  3455. this._isDepthMaskDirty = true;
  3456. },
  3457. enumerable: true,
  3458. configurable: true
  3459. });
  3460. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  3461. get: function () {
  3462. return this._depthTest;
  3463. },
  3464. set: function (value) {
  3465. if (this._depthTest === value) {
  3466. return;
  3467. }
  3468. this._depthTest = value;
  3469. this._isDepthTestDirty = true;
  3470. },
  3471. enumerable: true,
  3472. configurable: true
  3473. });
  3474. _DepthCullingState.prototype.reset = function () {
  3475. this._depthMask = true;
  3476. this._depthTest = true;
  3477. this._depthFunc = null;
  3478. this._cull = null;
  3479. this._cullFace = null;
  3480. this._isDepthTestDirty = true;
  3481. this._isDepthMaskDirty = true;
  3482. this._isDepthFuncDirty = false;
  3483. this._isCullFaceDirty = false;
  3484. this._isCullDirty = false;
  3485. };
  3486. _DepthCullingState.prototype.apply = function (gl) {
  3487. if (!this.isDirty) {
  3488. return;
  3489. }
  3490. // Cull
  3491. if (this._isCullDirty) {
  3492. if (this.cull) {
  3493. gl.enable(gl.CULL_FACE);
  3494. }
  3495. else {
  3496. gl.disable(gl.CULL_FACE);
  3497. }
  3498. this._isCullDirty = false;
  3499. }
  3500. // Cull face
  3501. if (this._isCullFaceDirty) {
  3502. gl.cullFace(this.cullFace);
  3503. this._isCullFaceDirty = false;
  3504. }
  3505. // Depth mask
  3506. if (this._isDepthMaskDirty) {
  3507. gl.depthMask(this.depthMask);
  3508. this._isDepthMaskDirty = false;
  3509. }
  3510. // Depth test
  3511. if (this._isDepthTestDirty) {
  3512. if (this.depthTest) {
  3513. gl.enable(gl.DEPTH_TEST);
  3514. }
  3515. else {
  3516. gl.disable(gl.DEPTH_TEST);
  3517. }
  3518. this._isDepthTestDirty = false;
  3519. }
  3520. // Depth func
  3521. if (this._isDepthFuncDirty) {
  3522. gl.depthFunc(this.depthFunc);
  3523. this._isDepthFuncDirty = false;
  3524. }
  3525. };
  3526. return _DepthCullingState;
  3527. })();
  3528. BABYLON._DepthCullingState = _DepthCullingState;
  3529. var _AlphaState = (function () {
  3530. function _AlphaState() {
  3531. this._isAlphaBlendDirty = false;
  3532. this._isBlendFunctionParametersDirty = false;
  3533. this._alphaBlend = false;
  3534. this._blendFunctionParameters = new Array(4);
  3535. }
  3536. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  3537. get: function () {
  3538. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  3539. },
  3540. enumerable: true,
  3541. configurable: true
  3542. });
  3543. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  3544. get: function () {
  3545. return this._alphaBlend;
  3546. },
  3547. set: function (value) {
  3548. if (this._alphaBlend === value) {
  3549. return;
  3550. }
  3551. this._alphaBlend = value;
  3552. this._isAlphaBlendDirty = true;
  3553. },
  3554. enumerable: true,
  3555. configurable: true
  3556. });
  3557. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  3558. if (this._blendFunctionParameters[0] === value0 && this._blendFunctionParameters[1] === value1 && this._blendFunctionParameters[2] === value2 && this._blendFunctionParameters[3] === value3) {
  3559. return;
  3560. }
  3561. this._blendFunctionParameters[0] = value0;
  3562. this._blendFunctionParameters[1] = value1;
  3563. this._blendFunctionParameters[2] = value2;
  3564. this._blendFunctionParameters[3] = value3;
  3565. this._isBlendFunctionParametersDirty = true;
  3566. };
  3567. _AlphaState.prototype.reset = function () {
  3568. this._alphaBlend = false;
  3569. this._blendFunctionParameters[0] = null;
  3570. this._blendFunctionParameters[1] = null;
  3571. this._blendFunctionParameters[2] = null;
  3572. this._blendFunctionParameters[3] = null;
  3573. this._isAlphaBlendDirty = true;
  3574. this._isBlendFunctionParametersDirty = false;
  3575. };
  3576. _AlphaState.prototype.apply = function (gl) {
  3577. if (!this.isDirty) {
  3578. return;
  3579. }
  3580. // Alpha blend
  3581. if (this._isAlphaBlendDirty) {
  3582. if (this._alphaBlend) {
  3583. gl.enable(gl.BLEND);
  3584. }
  3585. else {
  3586. gl.disable(gl.BLEND);
  3587. }
  3588. this._isAlphaBlendDirty = false;
  3589. }
  3590. // Alpha function
  3591. if (this._isBlendFunctionParametersDirty) {
  3592. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  3593. this._isBlendFunctionParametersDirty = false;
  3594. }
  3595. };
  3596. return _AlphaState;
  3597. })();
  3598. BABYLON._AlphaState = _AlphaState;
  3599. var compileShader = function (gl, source, type, defines) {
  3600. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  3601. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  3602. gl.compileShader(shader);
  3603. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  3604. throw new Error(gl.getShaderInfoLog(shader));
  3605. }
  3606. return shader;
  3607. };
  3608. var getWebGLTextureType = function (gl, type) {
  3609. var textureType = gl.UNSIGNED_BYTE;
  3610. if (type === Engine.TEXTURETYPE_FLOAT)
  3611. textureType = gl.FLOAT;
  3612. return textureType;
  3613. };
  3614. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  3615. var magFilter = gl.NEAREST;
  3616. var minFilter = gl.NEAREST;
  3617. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  3618. magFilter = gl.LINEAR;
  3619. if (generateMipMaps) {
  3620. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  3621. }
  3622. else {
  3623. minFilter = gl.LINEAR;
  3624. }
  3625. }
  3626. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  3627. magFilter = gl.LINEAR;
  3628. if (generateMipMaps) {
  3629. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  3630. }
  3631. else {
  3632. minFilter = gl.LINEAR;
  3633. }
  3634. }
  3635. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  3636. magFilter = gl.NEAREST;
  3637. if (generateMipMaps) {
  3638. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  3639. }
  3640. else {
  3641. minFilter = gl.NEAREST;
  3642. }
  3643. }
  3644. return {
  3645. min: minFilter,
  3646. mag: magFilter
  3647. };
  3648. };
  3649. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  3650. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  3651. var engine = scene.getEngine();
  3652. var potWidth = BABYLON.Tools.GetExponantOfTwo(width, engine.getCaps().maxTextureSize);
  3653. var potHeight = BABYLON.Tools.GetExponantOfTwo(height, engine.getCaps().maxTextureSize);
  3654. gl.bindTexture(gl.TEXTURE_2D, texture);
  3655. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  3656. processFunction(potWidth, potHeight);
  3657. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  3658. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  3659. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  3660. if (!noMipmap && !isCompressed) {
  3661. gl.generateMipmap(gl.TEXTURE_2D);
  3662. }
  3663. gl.bindTexture(gl.TEXTURE_2D, null);
  3664. engine._activeTexturesCache = [];
  3665. texture._baseWidth = width;
  3666. texture._baseHeight = height;
  3667. texture._width = potWidth;
  3668. texture._height = potHeight;
  3669. texture.isReady = true;
  3670. texture.samplingMode = samplingMode;
  3671. scene._removePendingData(texture);
  3672. };
  3673. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  3674. var onload = function () {
  3675. loadedImages[index] = img;
  3676. loadedImages._internalCount++;
  3677. scene._removePendingData(img);
  3678. if (loadedImages._internalCount === 6) {
  3679. onfinish(loadedImages);
  3680. }
  3681. };
  3682. var onerror = function () {
  3683. scene._removePendingData(img);
  3684. };
  3685. var img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  3686. scene._addPendingData(img);
  3687. };
  3688. var cascadeLoad = function (rootUrl, scene, onfinish, extensions) {
  3689. var loadedImages = [];
  3690. loadedImages._internalCount = 0;
  3691. for (var index = 0; index < 6; index++) {
  3692. partialLoad(rootUrl + extensions[index], index, loadedImages, scene, onfinish);
  3693. }
  3694. };
  3695. var EngineCapabilities = (function () {
  3696. function EngineCapabilities() {
  3697. }
  3698. return EngineCapabilities;
  3699. })();
  3700. BABYLON.EngineCapabilities = EngineCapabilities;
  3701. /**
  3702. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  3703. */
  3704. var Engine = (function () {
  3705. /**
  3706. * @constructor
  3707. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  3708. * @param {boolean} [antialias] - enable antialias
  3709. * @param options - further options to be sent to the getContext function
  3710. */
  3711. function Engine(canvas, antialias, options) {
  3712. var _this = this;
  3713. // Public members
  3714. this.isFullscreen = false;
  3715. this.isPointerLock = false;
  3716. this.cullBackFaces = true;
  3717. this.renderEvenInBackground = true;
  3718. this.scenes = new Array();
  3719. this._windowIsBackground = false;
  3720. this._loadingDivBackgroundColor = "black";
  3721. this._drawCalls = 0;
  3722. this._renderingQueueLaunched = false;
  3723. this._activeRenderLoops = [];
  3724. // FPS
  3725. this.fpsRange = 60;
  3726. this.previousFramesDuration = [];
  3727. this.fps = 60;
  3728. this.deltaTime = 0;
  3729. // States
  3730. this._depthCullingState = new _DepthCullingState();
  3731. this._alphaState = new _AlphaState();
  3732. this._alphaMode = Engine.ALPHA_DISABLE;
  3733. // Cache
  3734. this._loadedTexturesCache = new Array();
  3735. this._activeTexturesCache = new Array();
  3736. this._compiledEffects = {};
  3737. this._uintIndicesCurrentlySet = false;
  3738. this._renderingCanvas = canvas;
  3739. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  3740. options = options || {};
  3741. options.antialias = antialias;
  3742. try {
  3743. this._gl = canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options);
  3744. }
  3745. catch (e) {
  3746. throw new Error("WebGL not supported");
  3747. }
  3748. if (!this._gl) {
  3749. throw new Error("WebGL not supported");
  3750. }
  3751. this._onBlur = function () {
  3752. _this._windowIsBackground = true;
  3753. };
  3754. this._onFocus = function () {
  3755. _this._windowIsBackground = false;
  3756. };
  3757. window.addEventListener("blur", this._onBlur);
  3758. window.addEventListener("focus", this._onFocus);
  3759. // Textures
  3760. this._workingCanvas = document.createElement("canvas");
  3761. this._workingContext = this._workingCanvas.getContext("2d");
  3762. // Viewport
  3763. this._hardwareScalingLevel = 1.0 / (window.devicePixelRatio || 1.0);
  3764. this.resize();
  3765. // Caps
  3766. this._caps = new EngineCapabilities();
  3767. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  3768. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  3769. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  3770. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  3771. // Infos
  3772. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  3773. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  3774. if (rendererInfo != null) {
  3775. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  3776. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  3777. }
  3778. if (!this._glVendor) {
  3779. this._glVendor = "Unknown vendor";
  3780. }
  3781. if (!this._glRenderer) {
  3782. this._glRenderer = "Unknown renderer";
  3783. }
  3784. // Extensions
  3785. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  3786. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  3787. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  3788. 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');
  3789. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  3790. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  3791. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  3792. // Depth buffer
  3793. this.setDepthBuffer(true);
  3794. this.setDepthFunctionToLessOrEqual();
  3795. this.setDepthWrite(true);
  3796. // Fullscreen
  3797. this._onFullscreenChange = function () {
  3798. if (document.fullscreen !== undefined) {
  3799. _this.isFullscreen = document.fullscreen;
  3800. }
  3801. else if (document.mozFullScreen !== undefined) {
  3802. _this.isFullscreen = document.mozFullScreen;
  3803. }
  3804. else if (document.webkitIsFullScreen !== undefined) {
  3805. _this.isFullscreen = document.webkitIsFullScreen;
  3806. }
  3807. else if (document.msIsFullScreen !== undefined) {
  3808. _this.isFullscreen = document.msIsFullScreen;
  3809. }
  3810. // Pointer lock
  3811. if (_this.isFullscreen && _this._pointerLockRequested) {
  3812. canvas.requestPointerLock = canvas.requestPointerLock || canvas.msRequestPointerLock || canvas.mozRequestPointerLock || canvas.webkitRequestPointerLock;
  3813. if (canvas.requestPointerLock) {
  3814. canvas.requestPointerLock();
  3815. }
  3816. }
  3817. };
  3818. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  3819. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  3820. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  3821. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  3822. // Pointer lock
  3823. this._onPointerLockChange = function () {
  3824. _this.isPointerLock = (document.mozPointerLockElement === canvas || document.webkitPointerLockElement === canvas || document.msPointerLockElement === canvas || document.pointerLockElement === canvas);
  3825. };
  3826. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  3827. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  3828. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  3829. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  3830. if (!Engine.audioEngine) {
  3831. Engine.audioEngine = new BABYLON.AudioEngine();
  3832. }
  3833. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  3834. }
  3835. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  3836. get: function () {
  3837. return Engine._ALPHA_DISABLE;
  3838. },
  3839. enumerable: true,
  3840. configurable: true
  3841. });
  3842. Object.defineProperty(Engine, "ALPHA_ADD", {
  3843. get: function () {
  3844. return Engine._ALPHA_ADD;
  3845. },
  3846. enumerable: true,
  3847. configurable: true
  3848. });
  3849. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  3850. get: function () {
  3851. return Engine._ALPHA_COMBINE;
  3852. },
  3853. enumerable: true,
  3854. configurable: true
  3855. });
  3856. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  3857. get: function () {
  3858. return Engine._DELAYLOADSTATE_NONE;
  3859. },
  3860. enumerable: true,
  3861. configurable: true
  3862. });
  3863. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  3864. get: function () {
  3865. return Engine._DELAYLOADSTATE_LOADED;
  3866. },
  3867. enumerable: true,
  3868. configurable: true
  3869. });
  3870. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  3871. get: function () {
  3872. return Engine._DELAYLOADSTATE_LOADING;
  3873. },
  3874. enumerable: true,
  3875. configurable: true
  3876. });
  3877. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  3878. get: function () {
  3879. return Engine._DELAYLOADSTATE_NOTLOADED;
  3880. },
  3881. enumerable: true,
  3882. configurable: true
  3883. });
  3884. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  3885. get: function () {
  3886. return Engine._TEXTUREFORMAT_ALPHA;
  3887. },
  3888. enumerable: true,
  3889. configurable: true
  3890. });
  3891. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  3892. get: function () {
  3893. return Engine._TEXTUREFORMAT_LUMINANCE;
  3894. },
  3895. enumerable: true,
  3896. configurable: true
  3897. });
  3898. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  3899. get: function () {
  3900. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  3901. },
  3902. enumerable: true,
  3903. configurable: true
  3904. });
  3905. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  3906. get: function () {
  3907. return Engine._TEXTUREFORMAT_RGB;
  3908. },
  3909. enumerable: true,
  3910. configurable: true
  3911. });
  3912. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  3913. get: function () {
  3914. return Engine._TEXTUREFORMAT_RGBA;
  3915. },
  3916. enumerable: true,
  3917. configurable: true
  3918. });
  3919. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  3920. get: function () {
  3921. return Engine._TEXTURETYPE_UNSIGNED_INT;
  3922. },
  3923. enumerable: true,
  3924. configurable: true
  3925. });
  3926. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  3927. get: function () {
  3928. return Engine._TEXTURETYPE_FLOAT;
  3929. },
  3930. enumerable: true,
  3931. configurable: true
  3932. });
  3933. Object.defineProperty(Engine, "Version", {
  3934. get: function () {
  3935. return "2.1.0 alpha";
  3936. },
  3937. enumerable: true,
  3938. configurable: true
  3939. });
  3940. Engine.prototype.getGlInfo = function () {
  3941. return {
  3942. vendor: this._glVendor,
  3943. renderer: this._glRenderer,
  3944. version: this._glVersion
  3945. };
  3946. };
  3947. Engine.prototype.getAspectRatio = function (camera) {
  3948. var viewport = camera.viewport;
  3949. return (this.getRenderWidth() * viewport.width) / (this.getRenderHeight() * viewport.height);
  3950. };
  3951. Engine.prototype.getRenderWidth = function () {
  3952. if (this._currentRenderTarget) {
  3953. return this._currentRenderTarget._width;
  3954. }
  3955. return this._renderingCanvas.width;
  3956. };
  3957. Engine.prototype.getRenderHeight = function () {
  3958. if (this._currentRenderTarget) {
  3959. return this._currentRenderTarget._height;
  3960. }
  3961. return this._renderingCanvas.height;
  3962. };
  3963. Engine.prototype.getRenderingCanvas = function () {
  3964. return this._renderingCanvas;
  3965. };
  3966. Engine.prototype.getRenderingCanvasClientRect = function () {
  3967. return this._renderingCanvas.getBoundingClientRect();
  3968. };
  3969. Engine.prototype.setHardwareScalingLevel = function (level) {
  3970. this._hardwareScalingLevel = level;
  3971. this.resize();
  3972. };
  3973. Engine.prototype.getHardwareScalingLevel = function () {
  3974. return this._hardwareScalingLevel;
  3975. };
  3976. Engine.prototype.getLoadedTexturesCache = function () {
  3977. return this._loadedTexturesCache;
  3978. };
  3979. Engine.prototype.getCaps = function () {
  3980. return this._caps;
  3981. };
  3982. Object.defineProperty(Engine.prototype, "drawCalls", {
  3983. get: function () {
  3984. return this._drawCalls;
  3985. },
  3986. enumerable: true,
  3987. configurable: true
  3988. });
  3989. // Methods
  3990. Engine.prototype.resetDrawCalls = function () {
  3991. this._drawCalls = 0;
  3992. };
  3993. Engine.prototype.setDepthFunctionToGreater = function () {
  3994. this._depthCullingState.depthFunc = this._gl.GREATER;
  3995. };
  3996. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  3997. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  3998. };
  3999. Engine.prototype.setDepthFunctionToLess = function () {
  4000. this._depthCullingState.depthFunc = this._gl.LESS;
  4001. };
  4002. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  4003. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  4004. };
  4005. /**
  4006. * stop executing a render loop function and remove it from the execution array
  4007. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  4008. */
  4009. Engine.prototype.stopRenderLoop = function (renderFunction) {
  4010. if (!renderFunction) {
  4011. this._activeRenderLoops = [];
  4012. return;
  4013. }
  4014. var index = this._activeRenderLoops.indexOf(renderFunction);
  4015. if (index >= 0) {
  4016. this._activeRenderLoops.splice(index, 1);
  4017. }
  4018. };
  4019. Engine.prototype._renderLoop = function () {
  4020. var _this = this;
  4021. var shouldRender = true;
  4022. if (!this.renderEvenInBackground && this._windowIsBackground) {
  4023. shouldRender = false;
  4024. }
  4025. if (shouldRender) {
  4026. // Start new frame
  4027. this.beginFrame();
  4028. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  4029. var renderFunction = this._activeRenderLoops[index];
  4030. renderFunction();
  4031. }
  4032. // Present
  4033. this.endFrame();
  4034. }
  4035. if (this._activeRenderLoops.length > 0) {
  4036. // Register new frame
  4037. BABYLON.Tools.QueueNewFrame(function () {
  4038. _this._renderLoop();
  4039. });
  4040. }
  4041. else {
  4042. this._renderingQueueLaunched = false;
  4043. }
  4044. };
  4045. /**
  4046. * Register and execute a render loop. The engine can have more than one render function.
  4047. * @param {Function} renderFunction - the function to continuesly execute starting the next render loop.
  4048. * @example
  4049. * engine.runRenderLoop(function () {
  4050. * scene.render()
  4051. * })
  4052. */
  4053. Engine.prototype.runRenderLoop = function (renderFunction) {
  4054. var _this = this;
  4055. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  4056. return;
  4057. }
  4058. this._activeRenderLoops.push(renderFunction);
  4059. if (!this._renderingQueueLaunched) {
  4060. this._renderingQueueLaunched = true;
  4061. BABYLON.Tools.QueueNewFrame(function () {
  4062. _this._renderLoop();
  4063. });
  4064. }
  4065. };
  4066. /**
  4067. * Toggle full screen mode.
  4068. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  4069. */
  4070. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  4071. if (this.isFullscreen) {
  4072. BABYLON.Tools.ExitFullscreen();
  4073. }
  4074. else {
  4075. this._pointerLockRequested = requestPointerLock;
  4076. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  4077. }
  4078. };
  4079. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  4080. this.applyStates();
  4081. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  4082. if (this._depthCullingState.depthMask) {
  4083. this._gl.clearDepth(1.0);
  4084. }
  4085. var mode = 0;
  4086. if (backBuffer)
  4087. mode |= this._gl.COLOR_BUFFER_BIT;
  4088. if (depthStencil && this._depthCullingState.depthMask)
  4089. mode |= this._gl.DEPTH_BUFFER_BIT;
  4090. this._gl.clear(mode);
  4091. };
  4092. /**
  4093. * Set the WebGL's viewport
  4094. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  4095. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  4096. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  4097. */
  4098. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  4099. var width = requiredWidth || this._renderingCanvas.width;
  4100. var height = requiredHeight || this._renderingCanvas.height;
  4101. var x = viewport.x || 0;
  4102. var y = viewport.y || 0;
  4103. this._cachedViewport = viewport;
  4104. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  4105. };
  4106. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  4107. this._cachedViewport = null;
  4108. this._gl.viewport(x, y, width, height);
  4109. };
  4110. Engine.prototype.beginFrame = function () {
  4111. this._measureFps();
  4112. };
  4113. Engine.prototype.endFrame = function () {
  4114. //this.flushFramebuffer();
  4115. };
  4116. /**
  4117. * resize the view according to the canvas' size.
  4118. * @example
  4119. * window.addEventListener("resize", function () {
  4120. * engine.resize();
  4121. * });
  4122. */
  4123. Engine.prototype.resize = function () {
  4124. this.setSize(this._renderingCanvas.clientWidth / this._hardwareScalingLevel, this._renderingCanvas.clientHeight / this._hardwareScalingLevel);
  4125. };
  4126. /**
  4127. * force a specific size of the canvas
  4128. * @param {number} width - the new canvas' width
  4129. * @param {number} height - the new canvas' height
  4130. */
  4131. Engine.prototype.setSize = function (width, height) {
  4132. this._renderingCanvas.width = width;
  4133. this._renderingCanvas.height = height;
  4134. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  4135. };
  4136. Engine.prototype.bindFramebuffer = function (texture) {
  4137. this._currentRenderTarget = texture;
  4138. var gl = this._gl;
  4139. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  4140. this._gl.viewport(0, 0, texture._width, texture._height);
  4141. this.wipeCaches();
  4142. };
  4143. Engine.prototype.unBindFramebuffer = function (texture) {
  4144. this._currentRenderTarget = null;
  4145. if (texture.generateMipMaps) {
  4146. var gl = this._gl;
  4147. gl.bindTexture(gl.TEXTURE_2D, texture);
  4148. gl.generateMipmap(gl.TEXTURE_2D);
  4149. gl.bindTexture(gl.TEXTURE_2D, null);
  4150. }
  4151. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  4152. };
  4153. Engine.prototype.flushFramebuffer = function () {
  4154. this._gl.flush();
  4155. };
  4156. Engine.prototype.restoreDefaultFramebuffer = function () {
  4157. this._currentRenderTarget = null;
  4158. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  4159. this.setViewport(this._cachedViewport);
  4160. this.wipeCaches();
  4161. };
  4162. // VBOs
  4163. Engine.prototype._resetVertexBufferBinding = function () {
  4164. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  4165. this._cachedVertexBuffers = null;
  4166. };
  4167. Engine.prototype.createVertexBuffer = function (vertices) {
  4168. var vbo = this._gl.createBuffer();
  4169. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  4170. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  4171. this._resetVertexBufferBinding();
  4172. vbo.references = 1;
  4173. return vbo;
  4174. };
  4175. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  4176. var vbo = this._gl.createBuffer();
  4177. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  4178. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  4179. this._resetVertexBufferBinding();
  4180. vbo.references = 1;
  4181. return vbo;
  4182. };
  4183. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset) {
  4184. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  4185. if (offset === undefined) {
  4186. offset = 0;
  4187. }
  4188. if (vertices instanceof Float32Array) {
  4189. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  4190. }
  4191. else {
  4192. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  4193. }
  4194. this._resetVertexBufferBinding();
  4195. };
  4196. Engine.prototype._resetIndexBufferBinding = function () {
  4197. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  4198. this._cachedIndexBuffer = null;
  4199. };
  4200. Engine.prototype.createIndexBuffer = function (indices) {
  4201. var vbo = this._gl.createBuffer();
  4202. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  4203. // Check for 32 bits indices
  4204. var arrayBuffer;
  4205. var need32Bits = false;
  4206. if (this._caps.uintIndices) {
  4207. for (var index = 0; index < indices.length; index++) {
  4208. if (indices[index] > 65535) {
  4209. need32Bits = true;
  4210. break;
  4211. }
  4212. }
  4213. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  4214. }
  4215. else {
  4216. arrayBuffer = new Uint16Array(indices);
  4217. }
  4218. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  4219. this._resetIndexBufferBinding();
  4220. vbo.references = 1;
  4221. vbo.is32Bits = need32Bits;
  4222. return vbo;
  4223. };
  4224. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  4225. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  4226. this._cachedVertexBuffers = vertexBuffer;
  4227. this._cachedEffectForVertexBuffers = effect;
  4228. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  4229. var offset = 0;
  4230. for (var index = 0; index < vertexDeclaration.length; index++) {
  4231. var order = effect.getAttributeLocation(index);
  4232. if (order >= 0) {
  4233. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  4234. }
  4235. offset += vertexDeclaration[index] * 4;
  4236. }
  4237. }
  4238. if (this._cachedIndexBuffer !== indexBuffer) {
  4239. this._cachedIndexBuffer = indexBuffer;
  4240. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  4241. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  4242. }
  4243. };
  4244. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  4245. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  4246. this._cachedVertexBuffers = vertexBuffers;
  4247. this._cachedEffectForVertexBuffers = effect;
  4248. var attributes = effect.getAttributesNames();
  4249. for (var index = 0; index < attributes.length; index++) {
  4250. var order = effect.getAttributeLocation(index);
  4251. if (order >= 0) {
  4252. var vertexBuffer = vertexBuffers[attributes[index]];
  4253. if (!vertexBuffer) {
  4254. continue;
  4255. }
  4256. var stride = vertexBuffer.getStrideSize();
  4257. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  4258. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  4259. }
  4260. }
  4261. }
  4262. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  4263. this._cachedIndexBuffer = indexBuffer;
  4264. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  4265. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  4266. }
  4267. };
  4268. Engine.prototype._releaseBuffer = function (buffer) {
  4269. buffer.references--;
  4270. if (buffer.references === 0) {
  4271. this._gl.deleteBuffer(buffer);
  4272. return true;
  4273. }
  4274. return false;
  4275. };
  4276. Engine.prototype.createInstancesBuffer = function (capacity) {
  4277. var buffer = this._gl.createBuffer();
  4278. buffer.capacity = capacity;
  4279. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  4280. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  4281. return buffer;
  4282. };
  4283. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  4284. this._gl.deleteBuffer(buffer);
  4285. };
  4286. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  4287. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  4288. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  4289. for (var index = 0; index < 4; index++) {
  4290. var offsetLocation = offsetLocations[index];
  4291. this._gl.enableVertexAttribArray(offsetLocation);
  4292. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  4293. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  4294. }
  4295. };
  4296. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  4297. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  4298. for (var index = 0; index < 4; index++) {
  4299. var offsetLocation = offsetLocations[index];
  4300. this._gl.disableVertexAttribArray(offsetLocation);
  4301. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  4302. }
  4303. };
  4304. Engine.prototype.applyStates = function () {
  4305. this._depthCullingState.apply(this._gl);
  4306. this._alphaState.apply(this._gl);
  4307. };
  4308. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  4309. // Apply states
  4310. this.applyStates();
  4311. this._drawCalls++;
  4312. // Render
  4313. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  4314. if (instancesCount) {
  4315. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * 2, instancesCount);
  4316. return;
  4317. }
  4318. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * 2);
  4319. };
  4320. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  4321. // Apply states
  4322. this.applyStates();
  4323. this._drawCalls++;
  4324. if (instancesCount) {
  4325. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  4326. return;
  4327. }
  4328. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  4329. };
  4330. // Shaders
  4331. Engine.prototype._releaseEffect = function (effect) {
  4332. if (this._compiledEffects[effect._key]) {
  4333. delete this._compiledEffects[effect._key];
  4334. if (effect.getProgram()) {
  4335. this._gl.deleteProgram(effect.getProgram());
  4336. }
  4337. }
  4338. };
  4339. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  4340. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  4341. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  4342. var name = vertex + "+" + fragment + "@" + defines;
  4343. if (this._compiledEffects[name]) {
  4344. return this._compiledEffects[name];
  4345. }
  4346. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  4347. effect._key = name;
  4348. this._compiledEffects[name] = effect;
  4349. return effect;
  4350. };
  4351. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  4352. if (uniformsNames === void 0) { uniformsNames = []; }
  4353. if (samplers === void 0) { samplers = []; }
  4354. if (defines === void 0) { defines = ""; }
  4355. return this.createEffect({
  4356. vertex: "particles",
  4357. fragmentElement: fragmentName
  4358. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  4359. };
  4360. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  4361. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  4362. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  4363. var shaderProgram = this._gl.createProgram();
  4364. this._gl.attachShader(shaderProgram, vertexShader);
  4365. this._gl.attachShader(shaderProgram, fragmentShader);
  4366. this._gl.linkProgram(shaderProgram);
  4367. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  4368. if (!linked) {
  4369. var error = this._gl.getProgramInfoLog(shaderProgram);
  4370. if (error) {
  4371. throw new Error(error);
  4372. }
  4373. }
  4374. this._gl.deleteShader(vertexShader);
  4375. this._gl.deleteShader(fragmentShader);
  4376. return shaderProgram;
  4377. };
  4378. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  4379. var results = [];
  4380. for (var index = 0; index < uniformsNames.length; index++) {
  4381. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  4382. }
  4383. return results;
  4384. };
  4385. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  4386. var results = [];
  4387. for (var index = 0; index < attributesNames.length; index++) {
  4388. try {
  4389. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  4390. }
  4391. catch (e) {
  4392. results.push(-1);
  4393. }
  4394. }
  4395. return results;
  4396. };
  4397. Engine.prototype.enableEffect = function (effect) {
  4398. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  4399. if (effect && effect.onBind) {
  4400. effect.onBind(effect);
  4401. }
  4402. return;
  4403. }
  4404. this._vertexAttribArrays = this._vertexAttribArrays || [];
  4405. // Use program
  4406. this._gl.useProgram(effect.getProgram());
  4407. for (var i in this._vertexAttribArrays) {
  4408. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  4409. continue;
  4410. }
  4411. this._vertexAttribArrays[i] = false;
  4412. this._gl.disableVertexAttribArray(i);
  4413. }
  4414. var attributesCount = effect.getAttributesCount();
  4415. for (var index = 0; index < attributesCount; index++) {
  4416. // Attributes
  4417. var order = effect.getAttributeLocation(index);
  4418. if (order >= 0) {
  4419. this._vertexAttribArrays[order] = true;
  4420. this._gl.enableVertexAttribArray(order);
  4421. }
  4422. }
  4423. this._currentEffect = effect;
  4424. if (effect.onBind) {
  4425. effect.onBind(effect);
  4426. }
  4427. };
  4428. Engine.prototype.setArray = function (uniform, array) {
  4429. if (!uniform)
  4430. return;
  4431. this._gl.uniform1fv(uniform, array);
  4432. };
  4433. Engine.prototype.setArray2 = function (uniform, array) {
  4434. if (!uniform || array.length % 2 !== 0)
  4435. return;
  4436. this._gl.uniform2fv(uniform, array);
  4437. };
  4438. Engine.prototype.setArray3 = function (uniform, array) {
  4439. if (!uniform || array.length % 3 !== 0)
  4440. return;
  4441. this._gl.uniform3fv(uniform, array);
  4442. };
  4443. Engine.prototype.setArray4 = function (uniform, array) {
  4444. if (!uniform || array.length % 4 !== 0)
  4445. return;
  4446. this._gl.uniform4fv(uniform, array);
  4447. };
  4448. Engine.prototype.setMatrices = function (uniform, matrices) {
  4449. if (!uniform)
  4450. return;
  4451. this._gl.uniformMatrix4fv(uniform, false, matrices);
  4452. };
  4453. Engine.prototype.setMatrix = function (uniform, matrix) {
  4454. if (!uniform)
  4455. return;
  4456. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  4457. };
  4458. Engine.prototype.setFloat = function (uniform, value) {
  4459. if (!uniform)
  4460. return;
  4461. this._gl.uniform1f(uniform, value);
  4462. };
  4463. Engine.prototype.setFloat2 = function (uniform, x, y) {
  4464. if (!uniform)
  4465. return;
  4466. this._gl.uniform2f(uniform, x, y);
  4467. };
  4468. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  4469. if (!uniform)
  4470. return;
  4471. this._gl.uniform3f(uniform, x, y, z);
  4472. };
  4473. Engine.prototype.setBool = function (uniform, bool) {
  4474. if (!uniform)
  4475. return;
  4476. this._gl.uniform1i(uniform, bool);
  4477. };
  4478. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  4479. if (!uniform)
  4480. return;
  4481. this._gl.uniform4f(uniform, x, y, z, w);
  4482. };
  4483. Engine.prototype.setColor3 = function (uniform, color3) {
  4484. if (!uniform)
  4485. return;
  4486. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  4487. };
  4488. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  4489. if (!uniform)
  4490. return;
  4491. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  4492. };
  4493. // States
  4494. Engine.prototype.setState = function (culling, force) {
  4495. // Culling
  4496. if (this._depthCullingState.cull !== culling || force) {
  4497. if (culling) {
  4498. this._depthCullingState.cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  4499. this._depthCullingState.cull = true;
  4500. }
  4501. else {
  4502. this._depthCullingState.cull = false;
  4503. }
  4504. }
  4505. };
  4506. Engine.prototype.setDepthBuffer = function (enable) {
  4507. this._depthCullingState.depthTest = enable;
  4508. };
  4509. Engine.prototype.getDepthWrite = function () {
  4510. return this._depthCullingState.depthMask;
  4511. };
  4512. Engine.prototype.setDepthWrite = function (enable) {
  4513. this._depthCullingState.depthMask = enable;
  4514. };
  4515. Engine.prototype.setColorWrite = function (enable) {
  4516. this._gl.colorMask(enable, enable, enable, enable);
  4517. };
  4518. Engine.prototype.setAlphaMode = function (mode) {
  4519. switch (mode) {
  4520. case Engine.ALPHA_DISABLE:
  4521. this.setDepthWrite(true);
  4522. this._alphaState.alphaBlend = false;
  4523. break;
  4524. case Engine.ALPHA_COMBINE:
  4525. this.setDepthWrite(false);
  4526. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  4527. this._alphaState.alphaBlend = true;
  4528. break;
  4529. case Engine.ALPHA_ADD:
  4530. this.setDepthWrite(false);
  4531. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  4532. this._alphaState.alphaBlend = true;
  4533. break;
  4534. }
  4535. this._alphaMode = mode;
  4536. };
  4537. Engine.prototype.getAlphaMode = function () {
  4538. return this._alphaMode;
  4539. };
  4540. Engine.prototype.setAlphaTesting = function (enable) {
  4541. this._alphaTest = enable;
  4542. };
  4543. Engine.prototype.getAlphaTesting = function () {
  4544. return this._alphaTest;
  4545. };
  4546. // Textures
  4547. Engine.prototype.wipeCaches = function () {
  4548. this._activeTexturesCache = [];
  4549. this._currentEffect = null;
  4550. this._depthCullingState.reset();
  4551. this._alphaState.reset();
  4552. this._cachedVertexBuffers = null;
  4553. this._cachedIndexBuffer = null;
  4554. this._cachedEffectForVertexBuffers = null;
  4555. };
  4556. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  4557. var gl = this._gl;
  4558. gl.bindTexture(gl.TEXTURE_2D, texture);
  4559. var magFilter = gl.NEAREST;
  4560. var minFilter = gl.NEAREST;
  4561. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  4562. magFilter = gl.LINEAR;
  4563. minFilter = gl.LINEAR;
  4564. }
  4565. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  4566. magFilter = gl.LINEAR;
  4567. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  4568. }
  4569. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  4570. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  4571. gl.bindTexture(gl.TEXTURE_2D, null);
  4572. texture.samplingMode = samplingMode;
  4573. };
  4574. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  4575. var _this = this;
  4576. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  4577. if (onLoad === void 0) { onLoad = null; }
  4578. if (onError === void 0) { onError = null; }
  4579. if (buffer === void 0) { buffer = null; }
  4580. var texture = this._gl.createTexture();
  4581. var extension;
  4582. var fromData = false;
  4583. if (url.substr(0, 5) === "data:") {
  4584. fromData = true;
  4585. }
  4586. if (!fromData)
  4587. extension = url.substr(url.length - 4, 4).toLowerCase();
  4588. else {
  4589. var oldUrl = url;
  4590. fromData = oldUrl.split(':');
  4591. url = oldUrl;
  4592. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  4593. }
  4594. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  4595. var isTGA = (extension === ".tga");
  4596. scene._addPendingData(texture);
  4597. texture.url = url;
  4598. texture.noMipmap = noMipmap;
  4599. texture.references = 1;
  4600. this._loadedTexturesCache.push(texture);
  4601. var onerror = function () {
  4602. scene._removePendingData(texture);
  4603. if (onError) {
  4604. onError();
  4605. }
  4606. };
  4607. if (isTGA) {
  4608. var callback = function (arrayBuffer) {
  4609. var data = new Uint8Array(arrayBuffer);
  4610. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  4611. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  4612. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  4613. if (onLoad) {
  4614. onLoad();
  4615. }
  4616. }, samplingMode);
  4617. };
  4618. if (!(fromData instanceof Array))
  4619. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  4620. callback(arrayBuffer);
  4621. }, onerror, scene.database, true);
  4622. else
  4623. callback(buffer);
  4624. }
  4625. else if (isDDS) {
  4626. callback = function (data) {
  4627. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  4628. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  4629. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  4630. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  4631. if (onLoad) {
  4632. onLoad();
  4633. }
  4634. }, samplingMode);
  4635. };
  4636. if (!(fromData instanceof Array))
  4637. BABYLON.Tools.LoadFile(url, function (data) {
  4638. callback(data);
  4639. }, onerror, scene.database, true);
  4640. else
  4641. callback(buffer);
  4642. }
  4643. else {
  4644. var onload = function (img) {
  4645. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  4646. var isPot = (img.width === potWidth && img.height === potHeight);
  4647. if (!isPot) {
  4648. _this._workingCanvas.width = potWidth;
  4649. _this._workingCanvas.height = potHeight;
  4650. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  4651. _this._workingContext.imageSmoothingEnabled = false;
  4652. _this._workingContext.mozImageSmoothingEnabled = false;
  4653. _this._workingContext.oImageSmoothingEnabled = false;
  4654. _this._workingContext.webkitImageSmoothingEnabled = false;
  4655. _this._workingContext.msImageSmoothingEnabled = false;
  4656. }
  4657. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  4658. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  4659. _this._workingContext.imageSmoothingEnabled = true;
  4660. _this._workingContext.mozImageSmoothingEnabled = true;
  4661. _this._workingContext.oImageSmoothingEnabled = true;
  4662. _this._workingContext.webkitImageSmoothingEnabled = true;
  4663. _this._workingContext.msImageSmoothingEnabled = true;
  4664. }
  4665. }
  4666. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  4667. if (onLoad) {
  4668. onLoad();
  4669. }
  4670. }, samplingMode);
  4671. };
  4672. if (!(fromData instanceof Array))
  4673. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  4674. else
  4675. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  4676. }
  4677. return texture;
  4678. };
  4679. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode) {
  4680. var texture = this._gl.createTexture();
  4681. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4682. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  4683. // Format
  4684. var internalFormat = this._gl.RGBA;
  4685. switch (format) {
  4686. case Engine.TEXTUREFORMAT_ALPHA:
  4687. internalFormat = this._gl.ALPHA;
  4688. break;
  4689. case Engine.TEXTUREFORMAT_LUMINANCE:
  4690. internalFormat = this._gl.LUMINANCE;
  4691. break;
  4692. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  4693. internalFormat = this._gl.LUMINANCE_ALPHA;
  4694. break;
  4695. case Engine.TEXTUREFORMAT_RGB:
  4696. internalFormat = this._gl.RGB;
  4697. break;
  4698. case Engine.TEXTUREFORMAT_RGBA:
  4699. internalFormat = this._gl.RGBA;
  4700. break;
  4701. }
  4702. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, width, height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  4703. if (generateMipMaps) {
  4704. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  4705. }
  4706. // Filters
  4707. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  4708. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  4709. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  4710. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4711. this._activeTexturesCache = [];
  4712. texture._baseWidth = width;
  4713. texture._baseHeight = height;
  4714. texture._width = width;
  4715. texture._height = height;
  4716. texture.isReady = true;
  4717. texture.references = 1;
  4718. texture.samplingMode = samplingMode;
  4719. this._loadedTexturesCache.push(texture);
  4720. return texture;
  4721. };
  4722. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  4723. var texture = this._gl.createTexture();
  4724. width = BABYLON.Tools.GetExponantOfTwo(width, this._caps.maxTextureSize);
  4725. height = BABYLON.Tools.GetExponantOfTwo(height, this._caps.maxTextureSize);
  4726. this._activeTexturesCache = [];
  4727. texture._baseWidth = width;
  4728. texture._baseHeight = height;
  4729. texture._width = width;
  4730. texture._height = height;
  4731. texture.isReady = false;
  4732. texture.generateMipMaps = generateMipMaps;
  4733. texture.references = 1;
  4734. texture.samplingMode = samplingMode;
  4735. this.updateTextureSamplingMode(samplingMode, texture);
  4736. this._loadedTexturesCache.push(texture);
  4737. return texture;
  4738. };
  4739. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  4740. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  4741. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4742. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  4743. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  4744. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4745. };
  4746. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  4747. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4748. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  4749. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  4750. if (texture.generateMipMaps) {
  4751. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  4752. }
  4753. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4754. this._activeTexturesCache = [];
  4755. texture.isReady = true;
  4756. };
  4757. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  4758. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4759. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  4760. // Scale the video if it is a NPOT using the current working canvas
  4761. if (video.videoWidth !== texture._width || video.videoHeight !== texture._height) {
  4762. if (!texture._workingCanvas) {
  4763. texture._workingCanvas = document.createElement("canvas");
  4764. texture._workingContext = texture._workingCanvas.getContext("2d");
  4765. texture._workingCanvas.width = texture._width;
  4766. texture._workingCanvas.height = texture._height;
  4767. }
  4768. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  4769. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  4770. }
  4771. else {
  4772. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  4773. }
  4774. if (texture.generateMipMaps) {
  4775. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  4776. }
  4777. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4778. this._activeTexturesCache = [];
  4779. texture.isReady = true;
  4780. };
  4781. Engine.prototype.createRenderTargetTexture = function (size, options) {
  4782. // old version had a "generateMipMaps" arg instead of options.
  4783. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  4784. // in the same way, generateDepthBuffer is defaulted to true
  4785. var generateMipMaps = false;
  4786. var generateDepthBuffer = true;
  4787. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  4788. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  4789. if (options !== undefined) {
  4790. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipmaps;
  4791. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  4792. type = options.type === undefined ? type : options.type;
  4793. if (options.samplingMode !== undefined) {
  4794. samplingMode = options.samplingMode;
  4795. }
  4796. if (type === Engine.TEXTURETYPE_FLOAT) {
  4797. // if floating point (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  4798. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  4799. }
  4800. }
  4801. var gl = this._gl;
  4802. var texture = gl.createTexture();
  4803. gl.bindTexture(gl.TEXTURE_2D, texture);
  4804. var width = size.width || size;
  4805. var height = size.height || size;
  4806. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  4807. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  4808. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  4809. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  4810. }
  4811. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  4812. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  4813. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4814. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4815. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  4816. var depthBuffer;
  4817. // Create the depth buffer
  4818. if (generateDepthBuffer) {
  4819. depthBuffer = gl.createRenderbuffer();
  4820. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  4821. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  4822. }
  4823. // Create the framebuffer
  4824. var framebuffer = gl.createFramebuffer();
  4825. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  4826. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  4827. if (generateDepthBuffer) {
  4828. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  4829. }
  4830. // Unbind
  4831. gl.bindTexture(gl.TEXTURE_2D, null);
  4832. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  4833. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  4834. texture._framebuffer = framebuffer;
  4835. if (generateDepthBuffer) {
  4836. texture._depthBuffer = depthBuffer;
  4837. }
  4838. texture._width = width;
  4839. texture._height = height;
  4840. texture.isReady = true;
  4841. texture.generateMipMaps = generateMipMaps;
  4842. texture.references = 1;
  4843. texture.samplingMode = samplingMode;
  4844. this._activeTexturesCache = [];
  4845. this._loadedTexturesCache.push(texture);
  4846. return texture;
  4847. };
  4848. Engine.prototype.createCubeTexture = function (rootUrl, scene, extensions, noMipmap) {
  4849. var _this = this;
  4850. var gl = this._gl;
  4851. var texture = gl.createTexture();
  4852. texture.isCube = true;
  4853. texture.url = rootUrl;
  4854. texture.references = 1;
  4855. this._loadedTexturesCache.push(texture);
  4856. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  4857. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  4858. if (isDDS) {
  4859. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  4860. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  4861. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  4862. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  4863. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  4864. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  4865. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  4866. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  4867. }
  4868. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  4869. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  4870. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4871. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4872. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  4873. _this._activeTexturesCache = [];
  4874. texture._width = info.width;
  4875. texture._height = info.height;
  4876. texture.isReady = true;
  4877. }, null, null, true);
  4878. }
  4879. else {
  4880. cascadeLoad(rootUrl, scene, function (imgs) {
  4881. var width = BABYLON.Tools.GetExponantOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  4882. var height = width;
  4883. _this._workingCanvas.width = width;
  4884. _this._workingCanvas.height = height;
  4885. var faces = [
  4886. gl.TEXTURE_CUBE_MAP_POSITIVE_X,
  4887. gl.TEXTURE_CUBE_MAP_POSITIVE_Y,
  4888. gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  4889. gl.TEXTURE_CUBE_MAP_NEGATIVE_X,
  4890. gl.TEXTURE_CUBE_MAP_NEGATIVE_Y,
  4891. gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  4892. ];
  4893. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  4894. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  4895. for (var index = 0; index < faces.length; index++) {
  4896. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  4897. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  4898. }
  4899. if (!noMipmap) {
  4900. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  4901. }
  4902. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  4903. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  4904. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4905. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4906. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  4907. _this._activeTexturesCache = [];
  4908. texture._width = width;
  4909. texture._height = height;
  4910. texture.isReady = true;
  4911. }, extensions);
  4912. }
  4913. return texture;
  4914. };
  4915. Engine.prototype._releaseTexture = function (texture) {
  4916. var gl = this._gl;
  4917. if (texture._framebuffer) {
  4918. gl.deleteFramebuffer(texture._framebuffer);
  4919. }
  4920. if (texture._depthBuffer) {
  4921. gl.deleteRenderbuffer(texture._depthBuffer);
  4922. }
  4923. gl.deleteTexture(texture);
  4924. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  4925. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  4926. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4927. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  4928. this._activeTexturesCache[channel] = null;
  4929. }
  4930. var index = this._loadedTexturesCache.indexOf(texture);
  4931. if (index !== -1) {
  4932. this._loadedTexturesCache.splice(index, 1);
  4933. }
  4934. };
  4935. Engine.prototype.bindSamplers = function (effect) {
  4936. this._gl.useProgram(effect.getProgram());
  4937. var samplers = effect.getSamplers();
  4938. for (var index = 0; index < samplers.length; index++) {
  4939. var uniform = effect.getUniform(samplers[index]);
  4940. this._gl.uniform1i(uniform, index);
  4941. }
  4942. this._currentEffect = null;
  4943. };
  4944. Engine.prototype._bindTexture = function (channel, texture) {
  4945. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  4946. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4947. this._activeTexturesCache[channel] = null;
  4948. };
  4949. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  4950. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  4951. };
  4952. Engine.prototype.setTexture = function (channel, texture) {
  4953. if (channel < 0) {
  4954. return;
  4955. }
  4956. // Not ready?
  4957. if (!texture || !texture.isReady()) {
  4958. if (this._activeTexturesCache[channel] != null) {
  4959. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  4960. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4961. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  4962. this._activeTexturesCache[channel] = null;
  4963. }
  4964. return;
  4965. }
  4966. // Video
  4967. if (texture instanceof BABYLON.VideoTexture) {
  4968. if (texture.update()) {
  4969. this._activeTexturesCache[channel] = null;
  4970. }
  4971. }
  4972. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  4973. texture.delayLoad();
  4974. return;
  4975. }
  4976. if (this._activeTexturesCache[channel] === texture) {
  4977. return;
  4978. }
  4979. this._activeTexturesCache[channel] = texture;
  4980. var internalTexture = texture.getInternalTexture();
  4981. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  4982. if (internalTexture.isCube) {
  4983. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  4984. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  4985. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  4986. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  4987. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  4988. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  4989. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  4990. }
  4991. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  4992. }
  4993. else {
  4994. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  4995. if (internalTexture._cachedWrapU !== texture.wrapU) {
  4996. internalTexture._cachedWrapU = texture.wrapU;
  4997. switch (texture.wrapU) {
  4998. case BABYLON.Texture.WRAP_ADDRESSMODE:
  4999. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  5000. break;
  5001. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  5002. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  5003. break;
  5004. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  5005. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  5006. break;
  5007. }
  5008. }
  5009. if (internalTexture._cachedWrapV !== texture.wrapV) {
  5010. internalTexture._cachedWrapV = texture.wrapV;
  5011. switch (texture.wrapV) {
  5012. case BABYLON.Texture.WRAP_ADDRESSMODE:
  5013. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  5014. break;
  5015. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  5016. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  5017. break;
  5018. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  5019. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  5020. break;
  5021. }
  5022. }
  5023. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  5024. }
  5025. };
  5026. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  5027. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  5028. var value = texture.anisotropicFilteringLevel;
  5029. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  5030. value = 1;
  5031. }
  5032. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  5033. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  5034. texture._cachedAnisotropicFilteringLevel = value;
  5035. }
  5036. };
  5037. Engine.prototype.readPixels = function (x, y, width, height) {
  5038. var data = new Uint8Array(height * width * 4);
  5039. this._gl.readPixels(0, 0, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  5040. return data;
  5041. };
  5042. // Dispose
  5043. Engine.prototype.dispose = function () {
  5044. this.hideLoadingUI();
  5045. this.stopRenderLoop();
  5046. while (this.scenes.length) {
  5047. this.scenes[0].dispose();
  5048. }
  5049. // Release audio engine
  5050. Engine.audioEngine.dispose();
  5051. for (var name in this._compiledEffects) {
  5052. this._gl.deleteProgram(this._compiledEffects[name]._program);
  5053. }
  5054. for (var i in this._vertexAttribArrays) {
  5055. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  5056. continue;
  5057. }
  5058. this._gl.disableVertexAttribArray(i);
  5059. }
  5060. // Events
  5061. window.removeEventListener("blur", this._onBlur);
  5062. window.removeEventListener("focus", this._onFocus);
  5063. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  5064. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  5065. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  5066. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  5067. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  5068. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  5069. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  5070. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  5071. };
  5072. // Loading screen
  5073. Engine.prototype.displayLoadingUI = function () {
  5074. var _this = this;
  5075. this._loadingDiv = document.createElement("div");
  5076. this._loadingDiv.style.opacity = "0";
  5077. this._loadingDiv.style.transition = "opacity 1.5s ease";
  5078. // Loading text
  5079. this._loadingTextDiv = document.createElement("div");
  5080. this._loadingTextDiv.style.position = "absolute";
  5081. this._loadingTextDiv.style.left = "0";
  5082. this._loadingTextDiv.style.top = "50%";
  5083. this._loadingTextDiv.style.marginTop = "80px";
  5084. this._loadingTextDiv.style.width = "100%";
  5085. this._loadingTextDiv.style.height = "20px";
  5086. this._loadingTextDiv.style.fontFamily = "Arial";
  5087. this._loadingTextDiv.style.fontSize = "14px";
  5088. this._loadingTextDiv.style.color = "white";
  5089. this._loadingTextDiv.style.textAlign = "center";
  5090. this._loadingTextDiv.innerHTML = "Loading";
  5091. this._loadingDiv.appendChild(this._loadingTextDiv);
  5092. // Loading img
  5093. var imgBack = new Image();
  5094. 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==";
  5095. imgBack.style.position = "absolute";
  5096. imgBack.style.left = "50%";
  5097. imgBack.style.top = "50%";
  5098. imgBack.style.marginLeft = "-50px";
  5099. imgBack.style.marginTop = "-50px";
  5100. imgBack.style.transition = "transform 1.0s ease";
  5101. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  5102. var deg = 360;
  5103. var onTransitionEnd = function () {
  5104. deg += 360;
  5105. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  5106. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  5107. };
  5108. imgBack.addEventListener("transitionend", onTransitionEnd);
  5109. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  5110. this._loadingDiv.appendChild(imgBack);
  5111. // front image
  5112. var imgFront = new Image();
  5113. 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=";
  5114. imgFront.style.position = "absolute";
  5115. imgFront.style.left = "50%";
  5116. imgFront.style.top = "50%";
  5117. imgFront.style.marginLeft = "-50px";
  5118. imgFront.style.marginTop = "-50px";
  5119. this._loadingDiv.appendChild(imgFront);
  5120. // Resize
  5121. this._resizeLoadingUI = function () {
  5122. var canvasRect = _this.getRenderingCanvasClientRect();
  5123. _this._loadingDiv.style.position = "absolute";
  5124. _this._loadingDiv.style.left = canvasRect.left + "px";
  5125. _this._loadingDiv.style.top = canvasRect.top + "px";
  5126. _this._loadingDiv.style.width = canvasRect.width + "px";
  5127. _this._loadingDiv.style.height = canvasRect.height + "px";
  5128. };
  5129. this._resizeLoadingUI();
  5130. window.addEventListener("resize", this._resizeLoadingUI);
  5131. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  5132. document.body.appendChild(this._loadingDiv);
  5133. setTimeout(function () {
  5134. _this._loadingDiv.style.opacity = "1";
  5135. imgBack.style.transform = "rotateZ(360deg)";
  5136. imgBack.style.webkitTransform = "rotateZ(360deg)";
  5137. }, 0);
  5138. };
  5139. Object.defineProperty(Engine.prototype, "loadingUIText", {
  5140. set: function (text) {
  5141. if (!this._loadingDiv) {
  5142. return;
  5143. }
  5144. this._loadingTextDiv.innerHTML = text;
  5145. },
  5146. enumerable: true,
  5147. configurable: true
  5148. });
  5149. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  5150. get: function () {
  5151. return this._loadingDivBackgroundColor;
  5152. },
  5153. set: function (color) {
  5154. this._loadingDivBackgroundColor = color;
  5155. if (!this._loadingDiv) {
  5156. return;
  5157. }
  5158. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  5159. },
  5160. enumerable: true,
  5161. configurable: true
  5162. });
  5163. Engine.prototype.hideLoadingUI = function () {
  5164. var _this = this;
  5165. if (!this._loadingDiv) {
  5166. return;
  5167. }
  5168. var onTransitionEnd = function () {
  5169. if (!_this._loadingDiv) {
  5170. return;
  5171. }
  5172. document.body.removeChild(_this._loadingDiv);
  5173. window.removeEventListener("resize", _this._resizeLoadingUI);
  5174. _this._loadingDiv = null;
  5175. };
  5176. this._loadingDiv.style.opacity = "0";
  5177. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  5178. };
  5179. // FPS
  5180. Engine.prototype.getFps = function () {
  5181. return this.fps;
  5182. };
  5183. Engine.prototype.getDeltaTime = function () {
  5184. return this.deltaTime;
  5185. };
  5186. Engine.prototype._measureFps = function () {
  5187. this.previousFramesDuration.push(BABYLON.Tools.Now);
  5188. var length = this.previousFramesDuration.length;
  5189. if (length >= 2) {
  5190. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  5191. }
  5192. if (length >= this.fpsRange) {
  5193. if (length > this.fpsRange) {
  5194. this.previousFramesDuration.splice(0, 1);
  5195. length = this.previousFramesDuration.length;
  5196. }
  5197. var sum = 0;
  5198. for (var id = 0; id < length - 1; id++) {
  5199. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  5200. }
  5201. this.fps = 1000.0 / (sum / (length - 1));
  5202. }
  5203. };
  5204. // Statics
  5205. Engine.isSupported = function () {
  5206. try {
  5207. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  5208. if (navigator.isCocoonJS) {
  5209. return true;
  5210. }
  5211. var tempcanvas = document.createElement("canvas");
  5212. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  5213. return gl != null && !!window.WebGLRenderingContext;
  5214. }
  5215. catch (e) {
  5216. return false;
  5217. }
  5218. };
  5219. // Const statics
  5220. Engine._ALPHA_DISABLE = 0;
  5221. Engine._ALPHA_ADD = 1;
  5222. Engine._ALPHA_COMBINE = 2;
  5223. Engine._DELAYLOADSTATE_NONE = 0;
  5224. Engine._DELAYLOADSTATE_LOADED = 1;
  5225. Engine._DELAYLOADSTATE_LOADING = 2;
  5226. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  5227. Engine._TEXTUREFORMAT_ALPHA = 0;
  5228. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  5229. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  5230. Engine._TEXTUREFORMAT_RGB = 4;
  5231. Engine._TEXTUREFORMAT_RGBA = 4;
  5232. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  5233. Engine._TEXTURETYPE_FLOAT = 1;
  5234. // Updatable statics so stick with vars here
  5235. Engine.Epsilon = 0.001;
  5236. Engine.CollisionsEpsilon = 0.001;
  5237. Engine.ShadersRepository = "Babylon/Shaders/";
  5238. return Engine;
  5239. })();
  5240. BABYLON.Engine = Engine;
  5241. })(BABYLON || (BABYLON = {}));
  5242. //# sourceMappingURL=babylon.engine.js.mapvar BABYLON;
  5243. (function (BABYLON) {
  5244. /**
  5245. * Node is the basic class for all scene objects (Mesh, Light Camera).
  5246. */
  5247. var Node = (function () {
  5248. /**
  5249. * @constructor
  5250. * @param {string} name - the name and id to be given to this node
  5251. * @param {BABYLON.Scene} the scene this node will be added to
  5252. */
  5253. function Node(name, scene) {
  5254. this.state = "";
  5255. this.animations = new Array();
  5256. this._childrenFlag = -1;
  5257. this._isEnabled = true;
  5258. this._isReady = true;
  5259. this._currentRenderId = -1;
  5260. this.name = name;
  5261. this.id = name;
  5262. this._scene = scene;
  5263. this._initCache();
  5264. }
  5265. Node.prototype.getScene = function () {
  5266. return this._scene;
  5267. };
  5268. Node.prototype.getEngine = function () {
  5269. return this._scene.getEngine();
  5270. };
  5271. // override it in derived class
  5272. Node.prototype.getWorldMatrix = function () {
  5273. return BABYLON.Matrix.Identity();
  5274. };
  5275. // override it in derived class if you add new variables to the cache
  5276. // and call the parent class method
  5277. Node.prototype._initCache = function () {
  5278. this._cache = {};
  5279. this._cache.parent = undefined;
  5280. };
  5281. Node.prototype.updateCache = function (force) {
  5282. if (!force && this.isSynchronized())
  5283. return;
  5284. this._cache.parent = this.parent;
  5285. this._updateCache();
  5286. };
  5287. // override it in derived class if you add new variables to the cache
  5288. // and call the parent class method if !ignoreParentClass
  5289. Node.prototype._updateCache = function (ignoreParentClass) {
  5290. };
  5291. // override it in derived class if you add new variables to the cache
  5292. Node.prototype._isSynchronized = function () {
  5293. return true;
  5294. };
  5295. Node.prototype.isSynchronizedWithParent = function () {
  5296. return this.parent ? this.parent._currentRenderId <= this._currentRenderId : true;
  5297. };
  5298. Node.prototype.isSynchronized = function (updateCache) {
  5299. var check = this.hasNewParent();
  5300. check = check || !this.isSynchronizedWithParent();
  5301. check = check || !this._isSynchronized();
  5302. if (updateCache)
  5303. this.updateCache(true);
  5304. return !check;
  5305. };
  5306. Node.prototype.hasNewParent = function (update) {
  5307. if (this._cache.parent === this.parent)
  5308. return false;
  5309. if (update)
  5310. this._cache.parent = this.parent;
  5311. return true;
  5312. };
  5313. /**
  5314. * Is this node ready to be used/rendered
  5315. * @return {boolean} is it ready
  5316. */
  5317. Node.prototype.isReady = function () {
  5318. return this._isReady;
  5319. };
  5320. /**
  5321. * Is this node enabled.
  5322. * If the node has a parent and is enabled, the parent will be inspected as well.
  5323. * @return {boolean} whether this node (and its parent) is enabled.
  5324. * @see setEnabled
  5325. */
  5326. Node.prototype.isEnabled = function () {
  5327. if (!this._isEnabled) {
  5328. return false;
  5329. }
  5330. if (this.parent) {
  5331. return this.parent.isEnabled();
  5332. }
  5333. return true;
  5334. };
  5335. /**
  5336. * Set the enabled state of this node.
  5337. * @param {boolean} value - the new enabled state
  5338. * @see isEnabled
  5339. */
  5340. Node.prototype.setEnabled = function (value) {
  5341. this._isEnabled = value;
  5342. };
  5343. /**
  5344. * Is this node a descendant of the given node.
  5345. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  5346. * @param {BABYLON.Node} ancestor - The parent node to inspect
  5347. * @see parent
  5348. */
  5349. Node.prototype.isDescendantOf = function (ancestor) {
  5350. if (this.parent) {
  5351. if (this.parent === ancestor) {
  5352. return true;
  5353. }
  5354. return this.parent.isDescendantOf(ancestor);
  5355. }
  5356. return false;
  5357. };
  5358. Node.prototype._getDescendants = function (list, results) {
  5359. for (var index = 0; index < list.length; index++) {
  5360. var item = list[index];
  5361. if (item.isDescendantOf(this)) {
  5362. results.push(item);
  5363. }
  5364. }
  5365. };
  5366. /**
  5367. * Will return all nodes that have this node as parent.
  5368. * @return {BABYLON.Node[]} all children nodes of all types.
  5369. */
  5370. Node.prototype.getDescendants = function () {
  5371. var results = [];
  5372. this._getDescendants(this._scene.meshes, results);
  5373. this._getDescendants(this._scene.lights, results);
  5374. this._getDescendants(this._scene.cameras, results);
  5375. return results;
  5376. };
  5377. Node.prototype._setReady = function (state) {
  5378. if (state == this._isReady) {
  5379. return;
  5380. }
  5381. if (!state) {
  5382. this._isReady = false;
  5383. return;
  5384. }
  5385. this._isReady = true;
  5386. if (this.onReady) {
  5387. this.onReady(this);
  5388. }
  5389. };
  5390. return Node;
  5391. })();
  5392. BABYLON.Node = Node;
  5393. })(BABYLON || (BABYLON = {}));
  5394. //# sourceMappingURL=babylon.node.js.mapvar BABYLON;
  5395. (function (BABYLON) {
  5396. var BoundingSphere = (function () {
  5397. function BoundingSphere(minimum, maximum) {
  5398. this.minimum = minimum;
  5399. this.maximum = maximum;
  5400. this._tempRadiusVector = BABYLON.Vector3.Zero();
  5401. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  5402. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  5403. this.radius = distance * 0.5;
  5404. this.centerWorld = BABYLON.Vector3.Zero();
  5405. this._update(BABYLON.Matrix.Identity());
  5406. }
  5407. // Methods
  5408. BoundingSphere.prototype._update = function (world) {
  5409. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  5410. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  5411. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  5412. };
  5413. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  5414. for (var i = 0; i < 6; i++) {
  5415. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  5416. return false;
  5417. }
  5418. return true;
  5419. };
  5420. BoundingSphere.prototype.intersectsPoint = function (point) {
  5421. var x = this.centerWorld.x - point.x;
  5422. var y = this.centerWorld.y - point.y;
  5423. var z = this.centerWorld.z - point.z;
  5424. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  5425. if (Math.abs(this.radiusWorld - distance) < BABYLON.Engine.Epsilon)
  5426. return false;
  5427. return true;
  5428. };
  5429. // Statics
  5430. BoundingSphere.Intersects = function (sphere0, sphere1) {
  5431. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  5432. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  5433. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  5434. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  5435. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  5436. return false;
  5437. return true;
  5438. };
  5439. return BoundingSphere;
  5440. })();
  5441. BABYLON.BoundingSphere = BoundingSphere;
  5442. })(BABYLON || (BABYLON = {}));
  5443. //# sourceMappingURL=babylon.boundingSphere.js.mapvar BABYLON;
  5444. (function (BABYLON) {
  5445. var BoundingBox = (function () {
  5446. function BoundingBox(minimum, maximum) {
  5447. this.minimum = minimum;
  5448. this.maximum = maximum;
  5449. this.vectors = new Array();
  5450. this.vectorsWorld = new Array();
  5451. // Bounding vectors
  5452. this.vectors.push(this.minimum.clone());
  5453. this.vectors.push(this.maximum.clone());
  5454. this.vectors.push(this.minimum.clone());
  5455. this.vectors[2].x = this.maximum.x;
  5456. this.vectors.push(this.minimum.clone());
  5457. this.vectors[3].y = this.maximum.y;
  5458. this.vectors.push(this.minimum.clone());
  5459. this.vectors[4].z = this.maximum.z;
  5460. this.vectors.push(this.maximum.clone());
  5461. this.vectors[5].z = this.minimum.z;
  5462. this.vectors.push(this.maximum.clone());
  5463. this.vectors[6].x = this.minimum.x;
  5464. this.vectors.push(this.maximum.clone());
  5465. this.vectors[7].y = this.minimum.y;
  5466. // OBB
  5467. this.center = this.maximum.add(this.minimum).scale(0.5);
  5468. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  5469. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  5470. for (var index = 0; index < this.vectors.length; index++) {
  5471. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  5472. }
  5473. this.minimumWorld = BABYLON.Vector3.Zero();
  5474. this.maximumWorld = BABYLON.Vector3.Zero();
  5475. this._update(BABYLON.Matrix.Identity());
  5476. }
  5477. // Methods
  5478. BoundingBox.prototype.getWorldMatrix = function () {
  5479. return this._worldMatrix;
  5480. };
  5481. BoundingBox.prototype._update = function (world) {
  5482. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  5483. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  5484. for (var index = 0; index < this.vectors.length; index++) {
  5485. var v = this.vectorsWorld[index];
  5486. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  5487. if (v.x < this.minimumWorld.x)
  5488. this.minimumWorld.x = v.x;
  5489. if (v.y < this.minimumWorld.y)
  5490. this.minimumWorld.y = v.y;
  5491. if (v.z < this.minimumWorld.z)
  5492. this.minimumWorld.z = v.z;
  5493. if (v.x > this.maximumWorld.x)
  5494. this.maximumWorld.x = v.x;
  5495. if (v.y > this.maximumWorld.y)
  5496. this.maximumWorld.y = v.y;
  5497. if (v.z > this.maximumWorld.z)
  5498. this.maximumWorld.z = v.z;
  5499. }
  5500. // OBB
  5501. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  5502. this.center.scaleInPlace(0.5);
  5503. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  5504. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  5505. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  5506. this._worldMatrix = world;
  5507. };
  5508. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  5509. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  5510. };
  5511. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  5512. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  5513. };
  5514. BoundingBox.prototype.intersectsPoint = function (point) {
  5515. var delta = BABYLON.Engine.Epsilon;
  5516. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  5517. return false;
  5518. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  5519. return false;
  5520. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  5521. return false;
  5522. return true;
  5523. };
  5524. BoundingBox.prototype.intersectsSphere = function (sphere) {
  5525. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  5526. };
  5527. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  5528. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  5529. return false;
  5530. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  5531. return false;
  5532. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  5533. return false;
  5534. return true;
  5535. };
  5536. // Statics
  5537. BoundingBox.Intersects = function (box0, box1) {
  5538. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  5539. return false;
  5540. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  5541. return false;
  5542. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  5543. return false;
  5544. return true;
  5545. };
  5546. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  5547. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  5548. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  5549. return (num <= (sphereRadius * sphereRadius));
  5550. };
  5551. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  5552. for (var p = 0; p < 6; p++) {
  5553. for (var i = 0; i < 8; i++) {
  5554. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  5555. return false;
  5556. }
  5557. }
  5558. }
  5559. return true;
  5560. };
  5561. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  5562. for (var p = 0; p < 6; p++) {
  5563. var inCount = 8;
  5564. for (var i = 0; i < 8; i++) {
  5565. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  5566. --inCount;
  5567. }
  5568. else {
  5569. break;
  5570. }
  5571. }
  5572. if (inCount === 0)
  5573. return false;
  5574. }
  5575. return true;
  5576. };
  5577. return BoundingBox;
  5578. })();
  5579. BABYLON.BoundingBox = BoundingBox;
  5580. })(BABYLON || (BABYLON = {}));
  5581. //# sourceMappingURL=babylon.boundingBox.js.mapvar BABYLON;
  5582. (function (BABYLON) {
  5583. var computeBoxExtents = function (axis, box) {
  5584. var p = BABYLON.Vector3.Dot(box.center, axis);
  5585. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  5586. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  5587. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  5588. var r = r0 + r1 + r2;
  5589. return {
  5590. min: p - r,
  5591. max: p + r
  5592. };
  5593. };
  5594. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  5595. var axisOverlap = function (axis, box0, box1) {
  5596. var result0 = computeBoxExtents(axis, box0);
  5597. var result1 = computeBoxExtents(axis, box1);
  5598. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  5599. };
  5600. var BoundingInfo = (function () {
  5601. function BoundingInfo(minimum, maximum) {
  5602. this.minimum = minimum;
  5603. this.maximum = maximum;
  5604. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  5605. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  5606. }
  5607. // Methods
  5608. BoundingInfo.prototype._update = function (world) {
  5609. this.boundingBox._update(world);
  5610. this.boundingSphere._update(world);
  5611. };
  5612. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  5613. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  5614. return false;
  5615. return this.boundingBox.isInFrustum(frustumPlanes);
  5616. };
  5617. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  5618. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  5619. };
  5620. BoundingInfo.prototype._checkCollision = function (collider) {
  5621. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  5622. };
  5623. BoundingInfo.prototype.intersectsPoint = function (point) {
  5624. if (!this.boundingSphere.centerWorld) {
  5625. return false;
  5626. }
  5627. if (!this.boundingSphere.intersectsPoint(point)) {
  5628. return false;
  5629. }
  5630. if (!this.boundingBox.intersectsPoint(point)) {
  5631. return false;
  5632. }
  5633. return true;
  5634. };
  5635. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  5636. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  5637. return false;
  5638. }
  5639. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  5640. return false;
  5641. }
  5642. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  5643. return false;
  5644. }
  5645. if (!precise) {
  5646. return true;
  5647. }
  5648. var box0 = this.boundingBox;
  5649. var box1 = boundingInfo.boundingBox;
  5650. if (!axisOverlap(box0.directions[0], box0, box1))
  5651. return false;
  5652. if (!axisOverlap(box0.directions[1], box0, box1))
  5653. return false;
  5654. if (!axisOverlap(box0.directions[2], box0, box1))
  5655. return false;
  5656. if (!axisOverlap(box1.directions[0], box0, box1))
  5657. return false;
  5658. if (!axisOverlap(box1.directions[1], box0, box1))
  5659. return false;
  5660. if (!axisOverlap(box1.directions[2], box0, box1))
  5661. return false;
  5662. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  5663. return false;
  5664. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  5665. return false;
  5666. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  5667. return false;
  5668. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  5669. return false;
  5670. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  5671. return false;
  5672. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  5673. return false;
  5674. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  5675. return false;
  5676. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  5677. return false;
  5678. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  5679. return false;
  5680. return true;
  5681. };
  5682. return BoundingInfo;
  5683. })();
  5684. BABYLON.BoundingInfo = BoundingInfo;
  5685. })(BABYLON || (BABYLON = {}));
  5686. //# sourceMappingURL=babylon.boundingInfo.js.map
  5687. var BABYLON;
  5688. (function (BABYLON) {
  5689. var Light = (function (_super) {
  5690. __extends(Light, _super);
  5691. function Light(name, scene) {
  5692. _super.call(this, name, scene);
  5693. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  5694. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  5695. this.intensity = 1.0;
  5696. this.range = Number.MAX_VALUE;
  5697. this.includedOnlyMeshes = new Array();
  5698. this.excludedMeshes = new Array();
  5699. this._excludedMeshesIds = new Array();
  5700. this._includedOnlyMeshesIds = new Array();
  5701. scene.lights.push(this);
  5702. }
  5703. Light.prototype.getShadowGenerator = function () {
  5704. return this._shadowGenerator;
  5705. };
  5706. Light.prototype.getAbsolutePosition = function () {
  5707. return BABYLON.Vector3.Zero();
  5708. };
  5709. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  5710. };
  5711. Light.prototype._getWorldMatrix = function () {
  5712. return BABYLON.Matrix.Identity();
  5713. };
  5714. Light.prototype.canAffectMesh = function (mesh) {
  5715. if (!mesh) {
  5716. return true;
  5717. }
  5718. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  5719. return false;
  5720. }
  5721. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  5722. return false;
  5723. }
  5724. return true;
  5725. };
  5726. Light.prototype.getWorldMatrix = function () {
  5727. this._currentRenderId = this.getScene().getRenderId();
  5728. var worldMatrix = this._getWorldMatrix();
  5729. if (this.parent && this.parent.getWorldMatrix) {
  5730. if (!this._parentedWorldMatrix) {
  5731. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  5732. }
  5733. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  5734. return this._parentedWorldMatrix;
  5735. }
  5736. return worldMatrix;
  5737. };
  5738. Light.prototype.dispose = function () {
  5739. if (this._shadowGenerator) {
  5740. this._shadowGenerator.dispose();
  5741. this._shadowGenerator = null;
  5742. }
  5743. // Remove from scene
  5744. var index = this.getScene().lights.indexOf(this);
  5745. this.getScene().lights.splice(index, 1);
  5746. };
  5747. return Light;
  5748. })(BABYLON.Node);
  5749. BABYLON.Light = Light;
  5750. })(BABYLON || (BABYLON = {}));
  5751. //# sourceMappingURL=babylon.light.js.map
  5752. var BABYLON;
  5753. (function (BABYLON) {
  5754. var PointLight = (function (_super) {
  5755. __extends(PointLight, _super);
  5756. function PointLight(name, position, scene) {
  5757. _super.call(this, name, scene);
  5758. this.position = position;
  5759. }
  5760. PointLight.prototype.getAbsolutePosition = function () {
  5761. return this._transformedPosition ? this._transformedPosition : this.position;
  5762. };
  5763. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  5764. if (this.parent && this.parent.getWorldMatrix) {
  5765. if (!this._transformedPosition) {
  5766. this._transformedPosition = BABYLON.Vector3.Zero();
  5767. }
  5768. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this._transformedPosition);
  5769. effect.setFloat4(positionUniformName, this._transformedPosition.x, this._transformedPosition.y, this._transformedPosition.z, 0);
  5770. return;
  5771. }
  5772. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  5773. };
  5774. PointLight.prototype.getShadowGenerator = function () {
  5775. return null;
  5776. };
  5777. PointLight.prototype._getWorldMatrix = function () {
  5778. if (!this._worldMatrix) {
  5779. this._worldMatrix = BABYLON.Matrix.Identity();
  5780. }
  5781. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  5782. return this._worldMatrix;
  5783. };
  5784. return PointLight;
  5785. })(BABYLON.Light);
  5786. BABYLON.PointLight = PointLight;
  5787. })(BABYLON || (BABYLON = {}));
  5788. //# sourceMappingURL=babylon.pointLight.js.map
  5789. var BABYLON;
  5790. (function (BABYLON) {
  5791. var SpotLight = (function (_super) {
  5792. __extends(SpotLight, _super);
  5793. function SpotLight(name, position, direction, angle, exponent, scene) {
  5794. _super.call(this, name, scene);
  5795. this.position = position;
  5796. this.direction = direction;
  5797. this.angle = angle;
  5798. this.exponent = exponent;
  5799. }
  5800. SpotLight.prototype.getAbsolutePosition = function () {
  5801. return this.transformedPosition ? this.transformedPosition : this.position;
  5802. };
  5803. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  5804. var activeCamera = this.getScene().activeCamera;
  5805. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  5806. };
  5807. SpotLight.prototype.supportsVSM = function () {
  5808. return true;
  5809. };
  5810. SpotLight.prototype.needRefreshPerFrame = function () {
  5811. return false;
  5812. };
  5813. SpotLight.prototype.setDirectionToTarget = function (target) {
  5814. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  5815. return this.direction;
  5816. };
  5817. SpotLight.prototype.computeTransformedPosition = function () {
  5818. if (this.parent && this.parent.getWorldMatrix) {
  5819. if (!this.transformedPosition) {
  5820. this.transformedPosition = BABYLON.Vector3.Zero();
  5821. }
  5822. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  5823. return true;
  5824. }
  5825. return false;
  5826. };
  5827. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  5828. var normalizeDirection;
  5829. if (this.parent && this.parent.getWorldMatrix) {
  5830. if (!this._transformedDirection) {
  5831. this._transformedDirection = BABYLON.Vector3.Zero();
  5832. }
  5833. this.computeTransformedPosition();
  5834. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  5835. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  5836. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  5837. }
  5838. else {
  5839. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  5840. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  5841. }
  5842. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  5843. };
  5844. SpotLight.prototype._getWorldMatrix = function () {
  5845. if (!this._worldMatrix) {
  5846. this._worldMatrix = BABYLON.Matrix.Identity();
  5847. }
  5848. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  5849. return this._worldMatrix;
  5850. };
  5851. return SpotLight;
  5852. })(BABYLON.Light);
  5853. BABYLON.SpotLight = SpotLight;
  5854. })(BABYLON || (BABYLON = {}));
  5855. //# sourceMappingURL=babylon.spotLight.js.map
  5856. var BABYLON;
  5857. (function (BABYLON) {
  5858. var DirectionalLight = (function (_super) {
  5859. __extends(DirectionalLight, _super);
  5860. function DirectionalLight(name, direction, scene) {
  5861. _super.call(this, name, scene);
  5862. this.direction = direction;
  5863. this.shadowOrthoScale = 0.1;
  5864. this.position = direction.scale(-1);
  5865. }
  5866. DirectionalLight.prototype.getAbsolutePosition = function () {
  5867. return this.transformedPosition ? this.transformedPosition : this.position;
  5868. };
  5869. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  5870. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  5871. return this.direction;
  5872. };
  5873. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  5874. var orthoLeft = Number.MAX_VALUE;
  5875. var orthoRight = Number.MIN_VALUE;
  5876. var orthoTop = Number.MIN_VALUE;
  5877. var orthoBottom = Number.MAX_VALUE;
  5878. var tempVector3 = BABYLON.Vector3.Zero();
  5879. var activeCamera = this.getScene().activeCamera;
  5880. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  5881. var mesh = renderList[meshIndex];
  5882. if (!mesh) {
  5883. continue;
  5884. }
  5885. var boundingInfo = mesh.getBoundingInfo();
  5886. if (!boundingInfo) {
  5887. continue;
  5888. }
  5889. var boundingBox = boundingInfo.boundingBox;
  5890. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  5891. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  5892. if (tempVector3.x < orthoLeft)
  5893. orthoLeft = tempVector3.x;
  5894. if (tempVector3.y < orthoBottom)
  5895. orthoBottom = tempVector3.y;
  5896. if (tempVector3.x > orthoRight)
  5897. orthoRight = tempVector3.x;
  5898. if (tempVector3.y > orthoTop)
  5899. orthoTop = tempVector3.y;
  5900. }
  5901. }
  5902. var xOffset = orthoRight - orthoLeft;
  5903. var yOffset = orthoTop - orthoBottom;
  5904. BABYLON.Matrix.OrthoOffCenterLHToRef(orthoLeft - xOffset * this.shadowOrthoScale, orthoRight + xOffset * this.shadowOrthoScale, orthoBottom - yOffset * this.shadowOrthoScale, orthoTop + yOffset * this.shadowOrthoScale, -activeCamera.maxZ, activeCamera.maxZ, matrix);
  5905. };
  5906. DirectionalLight.prototype.supportsVSM = function () {
  5907. return true;
  5908. };
  5909. DirectionalLight.prototype.needRefreshPerFrame = function () {
  5910. return true;
  5911. };
  5912. DirectionalLight.prototype.computeTransformedPosition = function () {
  5913. if (this.parent && this.parent.getWorldMatrix) {
  5914. if (!this.transformedPosition) {
  5915. this.transformedPosition = BABYLON.Vector3.Zero();
  5916. }
  5917. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  5918. return true;
  5919. }
  5920. return false;
  5921. };
  5922. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  5923. if (this.parent && this.parent.getWorldMatrix) {
  5924. if (!this._transformedDirection) {
  5925. this._transformedDirection = BABYLON.Vector3.Zero();
  5926. }
  5927. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  5928. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  5929. return;
  5930. }
  5931. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  5932. };
  5933. DirectionalLight.prototype._getWorldMatrix = function () {
  5934. if (!this._worldMatrix) {
  5935. this._worldMatrix = BABYLON.Matrix.Identity();
  5936. }
  5937. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  5938. return this._worldMatrix;
  5939. };
  5940. return DirectionalLight;
  5941. })(BABYLON.Light);
  5942. BABYLON.DirectionalLight = DirectionalLight;
  5943. })(BABYLON || (BABYLON = {}));
  5944. //# sourceMappingURL=babylon.directionalLight.js.mapvar BABYLON;
  5945. (function (BABYLON) {
  5946. var ShadowGenerator = (function () {
  5947. function ShadowGenerator(mapSize, light) {
  5948. var _this = this;
  5949. // Members
  5950. this._filter = ShadowGenerator.FILTER_NONE;
  5951. this.blurScale = 2;
  5952. this._blurBoxOffset = 0;
  5953. this._bias = 0.00005;
  5954. this._darkness = 0;
  5955. this._transparencyShadow = false;
  5956. this._viewMatrix = BABYLON.Matrix.Zero();
  5957. this._projectionMatrix = BABYLON.Matrix.Zero();
  5958. this._transformMatrix = BABYLON.Matrix.Zero();
  5959. this._worldViewProjection = BABYLON.Matrix.Zero();
  5960. this._light = light;
  5961. this._scene = light.getScene();
  5962. this._mapSize = mapSize;
  5963. light._shadowGenerator = this;
  5964. // Render target
  5965. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false);
  5966. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  5967. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  5968. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  5969. this._shadowMap.renderParticles = false;
  5970. this._shadowMap.onAfterUnbind = function () {
  5971. if (!_this.useBlurVarianceShadowMap) {
  5972. return;
  5973. }
  5974. if (!_this._shadowMap2) {
  5975. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false);
  5976. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  5977. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  5978. _this._shadowMap2.anisotropicFilteringLevel = 16;
  5979. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  5980. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, _this._scene.getEngine());
  5981. _this._downSamplePostprocess.onApply = function (effect) {
  5982. effect.setTexture("textureSampler", _this._shadowMap);
  5983. };
  5984. _this.blurBoxOffset = 1;
  5985. }
  5986. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  5987. };
  5988. // Custom render function
  5989. var renderSubMesh = function (subMesh) {
  5990. var mesh = subMesh.getRenderingMesh();
  5991. var scene = _this._scene;
  5992. var engine = scene.getEngine();
  5993. // Culling
  5994. engine.setState(subMesh.getMaterial().backFaceCulling);
  5995. // Managing instances
  5996. var batch = mesh._getInstancesRenderList(subMesh._id);
  5997. if (batch.mustReturn) {
  5998. return;
  5999. }
  6000. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  6001. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  6002. engine.enableEffect(_this._effect);
  6003. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  6004. var material = subMesh.getMaterial();
  6005. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  6006. // Alpha test
  6007. if (material && material.needAlphaTesting()) {
  6008. var alphaTexture = material.getAlphaTestTexture();
  6009. _this._effect.setTexture("diffuseSampler", alphaTexture);
  6010. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  6011. }
  6012. // Bones
  6013. if (mesh.useBones) {
  6014. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  6015. }
  6016. // Draw
  6017. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  6018. }
  6019. else {
  6020. // Need to reset refresh rate of the shadowMap
  6021. _this._shadowMap.resetRefreshCounter();
  6022. }
  6023. };
  6024. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  6025. var index;
  6026. for (index = 0; index < opaqueSubMeshes.length; index++) {
  6027. renderSubMesh(opaqueSubMeshes.data[index]);
  6028. }
  6029. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  6030. renderSubMesh(alphaTestSubMeshes.data[index]);
  6031. }
  6032. if (_this._transparencyShadow) {
  6033. for (index = 0; index < transparentSubMeshes.length; index++) {
  6034. renderSubMesh(transparentSubMeshes.data[index]);
  6035. }
  6036. }
  6037. };
  6038. this._shadowMap.onClear = function (engine) {
  6039. if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
  6040. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true);
  6041. }
  6042. else {
  6043. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  6044. }
  6045. };
  6046. }
  6047. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  6048. // Static
  6049. get: function () {
  6050. return ShadowGenerator._FILTER_NONE;
  6051. },
  6052. enumerable: true,
  6053. configurable: true
  6054. });
  6055. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  6056. get: function () {
  6057. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  6058. },
  6059. enumerable: true,
  6060. configurable: true
  6061. });
  6062. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  6063. get: function () {
  6064. return ShadowGenerator._FILTER_POISSONSAMPLING;
  6065. },
  6066. enumerable: true,
  6067. configurable: true
  6068. });
  6069. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  6070. get: function () {
  6071. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  6072. },
  6073. enumerable: true,
  6074. configurable: true
  6075. });
  6076. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  6077. get: function () {
  6078. return this._bias;
  6079. },
  6080. set: function (bias) {
  6081. this._bias = bias;
  6082. },
  6083. enumerable: true,
  6084. configurable: true
  6085. });
  6086. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  6087. get: function () {
  6088. return this._blurBoxOffset;
  6089. },
  6090. set: function (value) {
  6091. var _this = this;
  6092. if (this._blurBoxOffset === value) {
  6093. return;
  6094. }
  6095. this._blurBoxOffset = value;
  6096. if (this._boxBlurPostprocess) {
  6097. this._boxBlurPostprocess.dispose();
  6098. }
  6099. 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);
  6100. this._boxBlurPostprocess.onApply = function (effect) {
  6101. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  6102. };
  6103. },
  6104. enumerable: true,
  6105. configurable: true
  6106. });
  6107. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  6108. get: function () {
  6109. return this._filter;
  6110. },
  6111. set: function (value) {
  6112. if (this._filter === value) {
  6113. return;
  6114. }
  6115. this._filter = value;
  6116. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  6117. this._shadowMap.anisotropicFilteringLevel = 16;
  6118. this._shadowMap.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  6119. }
  6120. else {
  6121. this._shadowMap.anisotropicFilteringLevel = 1;
  6122. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  6123. }
  6124. },
  6125. enumerable: true,
  6126. configurable: true
  6127. });
  6128. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  6129. get: function () {
  6130. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  6131. },
  6132. set: function (value) {
  6133. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  6134. },
  6135. enumerable: true,
  6136. configurable: true
  6137. });
  6138. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  6139. get: function () {
  6140. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING || (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP || this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
  6141. },
  6142. set: function (value) {
  6143. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  6144. },
  6145. enumerable: true,
  6146. configurable: true
  6147. });
  6148. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  6149. get: function () {
  6150. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  6151. },
  6152. set: function (value) {
  6153. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  6154. },
  6155. enumerable: true,
  6156. configurable: true
  6157. });
  6158. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  6159. var defines = [];
  6160. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  6161. defines.push("#define VSM");
  6162. }
  6163. var attribs = [BABYLON.VertexBuffer.PositionKind];
  6164. var mesh = subMesh.getMesh();
  6165. var material = subMesh.getMaterial();
  6166. // Alpha test
  6167. if (material && material.needAlphaTesting()) {
  6168. defines.push("#define ALPHATEST");
  6169. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  6170. attribs.push(BABYLON.VertexBuffer.UVKind);
  6171. defines.push("#define UV1");
  6172. }
  6173. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  6174. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  6175. defines.push("#define UV2");
  6176. }
  6177. }
  6178. // Bones
  6179. if (mesh.useBones) {
  6180. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  6181. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  6182. defines.push("#define BONES");
  6183. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  6184. }
  6185. // Instances
  6186. if (useInstances) {
  6187. defines.push("#define INSTANCES");
  6188. attribs.push("world0");
  6189. attribs.push("world1");
  6190. attribs.push("world2");
  6191. attribs.push("world3");
  6192. }
  6193. // Get correct effect
  6194. var join = defines.join("\n");
  6195. if (this._cachedDefines !== join) {
  6196. this._cachedDefines = join;
  6197. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  6198. }
  6199. return this._effect.isReady();
  6200. };
  6201. ShadowGenerator.prototype.getShadowMap = function () {
  6202. return this._shadowMap;
  6203. };
  6204. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  6205. if (this._shadowMap2) {
  6206. return this._shadowMap2;
  6207. }
  6208. return this._shadowMap;
  6209. };
  6210. ShadowGenerator.prototype.getLight = function () {
  6211. return this._light;
  6212. };
  6213. // Methods
  6214. ShadowGenerator.prototype.getTransformMatrix = function () {
  6215. var scene = this._scene;
  6216. if (this._currentRenderID === scene.getRenderId()) {
  6217. return this._transformMatrix;
  6218. }
  6219. this._currentRenderID = scene.getRenderId();
  6220. var lightPosition = this._light.position;
  6221. var lightDirection = this._light.direction;
  6222. if (this._light.computeTransformedPosition()) {
  6223. lightPosition = this._light.transformedPosition;
  6224. }
  6225. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !lightDirection.equals(this._cachedDirection)) {
  6226. this._cachedPosition = lightPosition.clone();
  6227. this._cachedDirection = lightDirection.clone();
  6228. BABYLON.Matrix.LookAtLHToRef(lightPosition, this._light.position.add(lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  6229. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  6230. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  6231. }
  6232. return this._transformMatrix;
  6233. };
  6234. ShadowGenerator.prototype.getDarkness = function () {
  6235. return this._darkness;
  6236. };
  6237. ShadowGenerator.prototype.setDarkness = function (darkness) {
  6238. if (darkness >= 1.0)
  6239. this._darkness = 1.0;
  6240. else if (darkness <= 0.0)
  6241. this._darkness = 0.0;
  6242. else
  6243. this._darkness = darkness;
  6244. };
  6245. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  6246. this._transparencyShadow = hasShadow;
  6247. };
  6248. ShadowGenerator.prototype._packHalf = function (depth) {
  6249. var scale = depth * 255.0;
  6250. var fract = scale - Math.floor(scale);
  6251. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  6252. };
  6253. ShadowGenerator.prototype.dispose = function () {
  6254. this._shadowMap.dispose();
  6255. if (this._shadowMap2) {
  6256. this._shadowMap2.dispose();
  6257. }
  6258. if (this._downSamplePostprocess) {
  6259. this._downSamplePostprocess.dispose();
  6260. }
  6261. if (this._boxBlurPostprocess) {
  6262. this._boxBlurPostprocess.dispose();
  6263. }
  6264. };
  6265. ShadowGenerator._FILTER_NONE = 0;
  6266. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  6267. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  6268. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  6269. return ShadowGenerator;
  6270. })();
  6271. BABYLON.ShadowGenerator = ShadowGenerator;
  6272. })(BABYLON || (BABYLON = {}));
  6273. //# sourceMappingURL=babylon.shadowGenerator.js.map
  6274. var BABYLON;
  6275. (function (BABYLON) {
  6276. var HemisphericLight = (function (_super) {
  6277. __extends(HemisphericLight, _super);
  6278. function HemisphericLight(name, direction, scene) {
  6279. _super.call(this, name, scene);
  6280. this.direction = direction;
  6281. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  6282. }
  6283. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  6284. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  6285. return this.direction;
  6286. };
  6287. HemisphericLight.prototype.getShadowGenerator = function () {
  6288. return null;
  6289. };
  6290. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  6291. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  6292. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  6293. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  6294. };
  6295. HemisphericLight.prototype._getWorldMatrix = function () {
  6296. if (!this._worldMatrix) {
  6297. this._worldMatrix = BABYLON.Matrix.Identity();
  6298. }
  6299. return this._worldMatrix;
  6300. };
  6301. return HemisphericLight;
  6302. })(BABYLON.Light);
  6303. BABYLON.HemisphericLight = HemisphericLight;
  6304. })(BABYLON || (BABYLON = {}));
  6305. //# sourceMappingURL=babylon.hemisphericLight.js.mapvar BABYLON;
  6306. (function (BABYLON) {
  6307. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  6308. if (boxMin.x > sphereCenter.x + sphereRadius)
  6309. return false;
  6310. if (sphereCenter.x - sphereRadius > boxMax.x)
  6311. return false;
  6312. if (boxMin.y > sphereCenter.y + sphereRadius)
  6313. return false;
  6314. if (sphereCenter.y - sphereRadius > boxMax.y)
  6315. return false;
  6316. if (boxMin.z > sphereCenter.z + sphereRadius)
  6317. return false;
  6318. if (sphereCenter.z - sphereRadius > boxMax.z)
  6319. return false;
  6320. return true;
  6321. };
  6322. var getLowestRoot = function (a, b, c, maxR) {
  6323. var determinant = b * b - 4.0 * a * c;
  6324. var result = { root: 0, found: false };
  6325. if (determinant < 0)
  6326. return result;
  6327. var sqrtD = Math.sqrt(determinant);
  6328. var r1 = (-b - sqrtD) / (2.0 * a);
  6329. var r2 = (-b + sqrtD) / (2.0 * a);
  6330. if (r1 > r2) {
  6331. var temp = r2;
  6332. r2 = r1;
  6333. r1 = temp;
  6334. }
  6335. if (r1 > 0 && r1 < maxR) {
  6336. result.root = r1;
  6337. result.found = true;
  6338. return result;
  6339. }
  6340. if (r2 > 0 && r2 < maxR) {
  6341. result.root = r2;
  6342. result.found = true;
  6343. return result;
  6344. }
  6345. return result;
  6346. };
  6347. var Collider = (function () {
  6348. function Collider() {
  6349. this.radius = new BABYLON.Vector3(1, 1, 1);
  6350. this.retry = 0;
  6351. this.basePointWorld = BABYLON.Vector3.Zero();
  6352. this.velocityWorld = BABYLON.Vector3.Zero();
  6353. this.normalizedVelocity = BABYLON.Vector3.Zero();
  6354. this._collisionPoint = BABYLON.Vector3.Zero();
  6355. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  6356. this._tempVector = BABYLON.Vector3.Zero();
  6357. this._tempVector2 = BABYLON.Vector3.Zero();
  6358. this._tempVector3 = BABYLON.Vector3.Zero();
  6359. this._tempVector4 = BABYLON.Vector3.Zero();
  6360. this._edge = BABYLON.Vector3.Zero();
  6361. this._baseToVertex = BABYLON.Vector3.Zero();
  6362. this._destinationPoint = BABYLON.Vector3.Zero();
  6363. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  6364. this._displacementVector = BABYLON.Vector3.Zero();
  6365. }
  6366. // Methods
  6367. Collider.prototype._initialize = function (source, dir, e) {
  6368. this.velocity = dir;
  6369. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  6370. this.basePoint = source;
  6371. source.multiplyToRef(this.radius, this.basePointWorld);
  6372. dir.multiplyToRef(this.radius, this.velocityWorld);
  6373. this.velocityWorldLength = this.velocityWorld.length();
  6374. this.epsilon = e;
  6375. this.collisionFound = false;
  6376. };
  6377. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  6378. pa.subtractToRef(point, this._tempVector);
  6379. pb.subtractToRef(point, this._tempVector2);
  6380. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  6381. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  6382. if (d < 0)
  6383. return false;
  6384. pc.subtractToRef(point, this._tempVector3);
  6385. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  6386. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  6387. if (d < 0)
  6388. return false;
  6389. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  6390. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  6391. return d >= 0;
  6392. };
  6393. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  6394. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  6395. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  6396. if (distance > this.velocityWorldLength + max + sphereRadius) {
  6397. return false;
  6398. }
  6399. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  6400. return false;
  6401. return true;
  6402. };
  6403. Collider.prototype._testTriangle = function (faceIndex, subMesh, p1, p2, p3) {
  6404. var t0;
  6405. var embeddedInPlane = false;
  6406. if (!subMesh._trianglePlanes) {
  6407. subMesh._trianglePlanes = [];
  6408. }
  6409. if (!subMesh._trianglePlanes[faceIndex]) {
  6410. subMesh._trianglePlanes[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  6411. subMesh._trianglePlanes[faceIndex].copyFromPoints(p1, p2, p3);
  6412. }
  6413. var trianglePlane = subMesh._trianglePlanes[faceIndex];
  6414. if ((!subMesh.getMaterial()) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  6415. return;
  6416. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  6417. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  6418. if (normalDotVelocity == 0) {
  6419. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  6420. return;
  6421. embeddedInPlane = true;
  6422. t0 = 0;
  6423. }
  6424. else {
  6425. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  6426. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  6427. if (t0 > t1) {
  6428. var temp = t1;
  6429. t1 = t0;
  6430. t0 = temp;
  6431. }
  6432. if (t0 > 1.0 || t1 < 0.0)
  6433. return;
  6434. if (t0 < 0)
  6435. t0 = 0;
  6436. if (t0 > 1.0)
  6437. t0 = 1.0;
  6438. }
  6439. this._collisionPoint.copyFromFloats(0, 0, 0);
  6440. var found = false;
  6441. var t = 1.0;
  6442. if (!embeddedInPlane) {
  6443. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  6444. this.velocity.scaleToRef(t0, this._tempVector);
  6445. this._planeIntersectionPoint.addInPlace(this._tempVector);
  6446. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  6447. found = true;
  6448. t = t0;
  6449. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  6450. }
  6451. }
  6452. if (!found) {
  6453. var velocitySquaredLength = this.velocity.lengthSquared();
  6454. var a = velocitySquaredLength;
  6455. this.basePoint.subtractToRef(p1, this._tempVector);
  6456. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  6457. var c = this._tempVector.lengthSquared() - 1.0;
  6458. var lowestRoot = getLowestRoot(a, b, c, t);
  6459. if (lowestRoot.found) {
  6460. t = lowestRoot.root;
  6461. found = true;
  6462. this._collisionPoint.copyFrom(p1);
  6463. }
  6464. this.basePoint.subtractToRef(p2, this._tempVector);
  6465. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  6466. c = this._tempVector.lengthSquared() - 1.0;
  6467. lowestRoot = getLowestRoot(a, b, c, t);
  6468. if (lowestRoot.found) {
  6469. t = lowestRoot.root;
  6470. found = true;
  6471. this._collisionPoint.copyFrom(p2);
  6472. }
  6473. this.basePoint.subtractToRef(p3, this._tempVector);
  6474. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  6475. c = this._tempVector.lengthSquared() - 1.0;
  6476. lowestRoot = getLowestRoot(a, b, c, t);
  6477. if (lowestRoot.found) {
  6478. t = lowestRoot.root;
  6479. found = true;
  6480. this._collisionPoint.copyFrom(p3);
  6481. }
  6482. p2.subtractToRef(p1, this._edge);
  6483. p1.subtractToRef(this.basePoint, this._baseToVertex);
  6484. var edgeSquaredLength = this._edge.lengthSquared();
  6485. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  6486. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  6487. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  6488. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  6489. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  6490. lowestRoot = getLowestRoot(a, b, c, t);
  6491. if (lowestRoot.found) {
  6492. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  6493. if (f >= 0.0 && f <= 1.0) {
  6494. t = lowestRoot.root;
  6495. found = true;
  6496. this._edge.scaleInPlace(f);
  6497. p1.addToRef(this._edge, this._collisionPoint);
  6498. }
  6499. }
  6500. p3.subtractToRef(p2, this._edge);
  6501. p2.subtractToRef(this.basePoint, this._baseToVertex);
  6502. edgeSquaredLength = this._edge.lengthSquared();
  6503. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  6504. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  6505. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  6506. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  6507. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  6508. lowestRoot = getLowestRoot(a, b, c, t);
  6509. if (lowestRoot.found) {
  6510. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  6511. if (f >= 0.0 && f <= 1.0) {
  6512. t = lowestRoot.root;
  6513. found = true;
  6514. this._edge.scaleInPlace(f);
  6515. p2.addToRef(this._edge, this._collisionPoint);
  6516. }
  6517. }
  6518. p1.subtractToRef(p3, this._edge);
  6519. p3.subtractToRef(this.basePoint, this._baseToVertex);
  6520. edgeSquaredLength = this._edge.lengthSquared();
  6521. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  6522. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  6523. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  6524. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  6525. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  6526. lowestRoot = getLowestRoot(a, b, c, t);
  6527. if (lowestRoot.found) {
  6528. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  6529. if (f >= 0.0 && f <= 1.0) {
  6530. t = lowestRoot.root;
  6531. found = true;
  6532. this._edge.scaleInPlace(f);
  6533. p3.addToRef(this._edge, this._collisionPoint);
  6534. }
  6535. }
  6536. }
  6537. if (found) {
  6538. var distToCollision = t * this.velocity.length();
  6539. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  6540. if (!this.intersectionPoint) {
  6541. this.intersectionPoint = this._collisionPoint.clone();
  6542. }
  6543. else {
  6544. this.intersectionPoint.copyFrom(this._collisionPoint);
  6545. }
  6546. this.nearestDistance = distToCollision;
  6547. this.collisionFound = true;
  6548. this.collidedMesh = subMesh.getMesh();
  6549. }
  6550. }
  6551. };
  6552. Collider.prototype._collide = function (subMesh, pts, indices, indexStart, indexEnd, decal) {
  6553. for (var i = indexStart; i < indexEnd; i += 3) {
  6554. var p1 = pts[indices[i] - decal];
  6555. var p2 = pts[indices[i + 1] - decal];
  6556. var p3 = pts[indices[i + 2] - decal];
  6557. this._testTriangle(i, subMesh, p3, p2, p1);
  6558. }
  6559. };
  6560. Collider.prototype._getResponse = function (pos, vel) {
  6561. pos.addToRef(vel, this._destinationPoint);
  6562. vel.scaleInPlace((this.nearestDistance / vel.length()));
  6563. this.basePoint.addToRef(vel, pos);
  6564. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  6565. this._slidePlaneNormal.normalize();
  6566. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  6567. pos.addInPlace(this._displacementVector);
  6568. this.intersectionPoint.addInPlace(this._displacementVector);
  6569. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  6570. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  6571. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  6572. };
  6573. return Collider;
  6574. })();
  6575. BABYLON.Collider = Collider;
  6576. })(BABYLON || (BABYLON = {}));
  6577. //# sourceMappingURL=babylon.collider.js.map
  6578. var BABYLON;
  6579. (function (BABYLON) {
  6580. var Camera = (function (_super) {
  6581. __extends(Camera, _super);
  6582. function Camera(name, position, scene) {
  6583. _super.call(this, name, scene);
  6584. this.position = position;
  6585. // Members
  6586. this.upVector = BABYLON.Vector3.Up();
  6587. this.orthoLeft = null;
  6588. this.orthoRight = null;
  6589. this.orthoBottom = null;
  6590. this.orthoTop = null;
  6591. this.fov = 0.8;
  6592. this.minZ = 1.0;
  6593. this.maxZ = 10000.0;
  6594. this.inertia = 0.9;
  6595. this.mode = Camera.PERSPECTIVE_CAMERA;
  6596. this.isIntermediate = false;
  6597. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  6598. this.subCameras = [];
  6599. this.layerMask = 0xFFFFFFFF;
  6600. this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  6601. this._computedViewMatrix = BABYLON.Matrix.Identity();
  6602. this._projectionMatrix = new BABYLON.Matrix();
  6603. this._postProcesses = new Array();
  6604. this._postProcessesTakenIndices = [];
  6605. this._activeMeshes = new BABYLON.SmartArray(256);
  6606. scene.cameras.push(this);
  6607. if (!scene.activeCamera) {
  6608. scene.activeCamera = this;
  6609. }
  6610. }
  6611. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  6612. get: function () {
  6613. return Camera._PERSPECTIVE_CAMERA;
  6614. },
  6615. enumerable: true,
  6616. configurable: true
  6617. });
  6618. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  6619. get: function () {
  6620. return Camera._ORTHOGRAPHIC_CAMERA;
  6621. },
  6622. enumerable: true,
  6623. configurable: true
  6624. });
  6625. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  6626. get: function () {
  6627. return Camera._FOVMODE_VERTICAL_FIXED;
  6628. },
  6629. enumerable: true,
  6630. configurable: true
  6631. });
  6632. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  6633. get: function () {
  6634. return Camera._FOVMODE_HORIZONTAL_FIXED;
  6635. },
  6636. enumerable: true,
  6637. configurable: true
  6638. });
  6639. Camera.prototype.getActiveMeshes = function () {
  6640. return this._activeMeshes;
  6641. };
  6642. Camera.prototype.isActiveMesh = function (mesh) {
  6643. return (this._activeMeshes.indexOf(mesh) !== -1);
  6644. };
  6645. //Cache
  6646. Camera.prototype._initCache = function () {
  6647. _super.prototype._initCache.call(this);
  6648. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6649. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6650. this._cache.mode = undefined;
  6651. this._cache.minZ = undefined;
  6652. this._cache.maxZ = undefined;
  6653. this._cache.fov = undefined;
  6654. this._cache.aspectRatio = undefined;
  6655. this._cache.orthoLeft = undefined;
  6656. this._cache.orthoRight = undefined;
  6657. this._cache.orthoBottom = undefined;
  6658. this._cache.orthoTop = undefined;
  6659. this._cache.renderWidth = undefined;
  6660. this._cache.renderHeight = undefined;
  6661. };
  6662. Camera.prototype._updateCache = function (ignoreParentClass) {
  6663. if (!ignoreParentClass) {
  6664. _super.prototype._updateCache.call(this);
  6665. }
  6666. var engine = this.getEngine();
  6667. this._cache.position.copyFrom(this.position);
  6668. this._cache.upVector.copyFrom(this.upVector);
  6669. this._cache.mode = this.mode;
  6670. this._cache.minZ = this.minZ;
  6671. this._cache.maxZ = this.maxZ;
  6672. this._cache.fov = this.fov;
  6673. this._cache.aspectRatio = engine.getAspectRatio(this);
  6674. this._cache.orthoLeft = this.orthoLeft;
  6675. this._cache.orthoRight = this.orthoRight;
  6676. this._cache.orthoBottom = this.orthoBottom;
  6677. this._cache.orthoTop = this.orthoTop;
  6678. this._cache.renderWidth = engine.getRenderWidth();
  6679. this._cache.renderHeight = engine.getRenderHeight();
  6680. };
  6681. Camera.prototype._updateFromScene = function () {
  6682. this.updateCache();
  6683. this._update();
  6684. };
  6685. // Synchronized
  6686. Camera.prototype._isSynchronized = function () {
  6687. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  6688. };
  6689. Camera.prototype._isSynchronizedViewMatrix = function () {
  6690. if (!_super.prototype._isSynchronized.call(this))
  6691. return false;
  6692. return this._cache.position.equals(this.position) && this._cache.upVector.equals(this.upVector) && this.isSynchronizedWithParent();
  6693. };
  6694. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  6695. var check = this._cache.mode === this.mode && this._cache.minZ === this.minZ && this._cache.maxZ === this.maxZ;
  6696. if (!check) {
  6697. return false;
  6698. }
  6699. var engine = this.getEngine();
  6700. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  6701. check = this._cache.fov === this.fov && this._cache.aspectRatio === engine.getAspectRatio(this);
  6702. }
  6703. else {
  6704. 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();
  6705. }
  6706. return check;
  6707. };
  6708. // Controls
  6709. Camera.prototype.attachControl = function (element) {
  6710. };
  6711. Camera.prototype.detachControl = function (element) {
  6712. };
  6713. Camera.prototype._update = function () {
  6714. };
  6715. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  6716. if (insertAt === void 0) { insertAt = null; }
  6717. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  6718. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  6719. return 0;
  6720. }
  6721. if (insertAt == null || insertAt < 0) {
  6722. this._postProcesses.push(postProcess);
  6723. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  6724. return this._postProcesses.length - 1;
  6725. }
  6726. var add = 0;
  6727. if (this._postProcesses[insertAt]) {
  6728. var start = this._postProcesses.length - 1;
  6729. for (var i = start; i >= insertAt + 1; --i) {
  6730. this._postProcesses[i + 1] = this._postProcesses[i];
  6731. }
  6732. add = 1;
  6733. }
  6734. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  6735. if (this._postProcessesTakenIndices[i] < insertAt) {
  6736. continue;
  6737. }
  6738. start = this._postProcessesTakenIndices.length - 1;
  6739. for (var j = start; j >= i; --j) {
  6740. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  6741. }
  6742. this._postProcessesTakenIndices[i] = insertAt;
  6743. break;
  6744. }
  6745. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) == -1) {
  6746. this._postProcessesTakenIndices.push(insertAt);
  6747. }
  6748. var result = insertAt + add;
  6749. this._postProcesses[result] = postProcess;
  6750. return result;
  6751. };
  6752. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  6753. if (atIndices === void 0) { atIndices = null; }
  6754. var result = [];
  6755. if (!atIndices) {
  6756. var length = this._postProcesses.length;
  6757. for (var i = 0; i < length; i++) {
  6758. if (this._postProcesses[i] !== postProcess) {
  6759. continue;
  6760. }
  6761. delete this._postProcesses[i];
  6762. var index = this._postProcessesTakenIndices.indexOf(i);
  6763. this._postProcessesTakenIndices.splice(index, 1);
  6764. }
  6765. }
  6766. else {
  6767. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  6768. for (i = 0; i < atIndices.length; i++) {
  6769. var foundPostProcess = this._postProcesses[atIndices[i]];
  6770. if (foundPostProcess !== postProcess) {
  6771. result.push(i);
  6772. continue;
  6773. }
  6774. delete this._postProcesses[atIndices[i]];
  6775. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  6776. this._postProcessesTakenIndices.splice(index, 1);
  6777. }
  6778. }
  6779. return result;
  6780. };
  6781. Camera.prototype.getWorldMatrix = function () {
  6782. if (!this._worldMatrix) {
  6783. this._worldMatrix = BABYLON.Matrix.Identity();
  6784. }
  6785. var viewMatrix = this.getViewMatrix();
  6786. viewMatrix.invertToRef(this._worldMatrix);
  6787. return this._worldMatrix;
  6788. };
  6789. Camera.prototype._getViewMatrix = function () {
  6790. return BABYLON.Matrix.Identity();
  6791. };
  6792. Camera.prototype.getViewMatrix = function () {
  6793. this._computedViewMatrix = this._computeViewMatrix();
  6794. if (!this.parent || !this.parent.getWorldMatrix || this.isSynchronized()) {
  6795. return this._computedViewMatrix;
  6796. }
  6797. if (!this._worldMatrix) {
  6798. this._worldMatrix = BABYLON.Matrix.Identity();
  6799. }
  6800. this._computedViewMatrix.invertToRef(this._worldMatrix);
  6801. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  6802. this._computedViewMatrix.invert();
  6803. this._currentRenderId = this.getScene().getRenderId();
  6804. return this._computedViewMatrix;
  6805. };
  6806. Camera.prototype._computeViewMatrix = function (force) {
  6807. if (!force && this._isSynchronizedViewMatrix()) {
  6808. return this._computedViewMatrix;
  6809. }
  6810. this._computedViewMatrix = this._getViewMatrix();
  6811. if (!this.parent || !this.parent.getWorldMatrix) {
  6812. this._currentRenderId = this.getScene().getRenderId();
  6813. }
  6814. return this._computedViewMatrix;
  6815. };
  6816. Camera.prototype.getProjectionMatrix = function (force) {
  6817. if (!force && this._isSynchronizedProjectionMatrix()) {
  6818. return this._projectionMatrix;
  6819. }
  6820. var engine = this.getEngine();
  6821. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  6822. if (this.minZ <= 0) {
  6823. this.minZ = 0.1;
  6824. }
  6825. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode);
  6826. return this._projectionMatrix;
  6827. }
  6828. var halfWidth = engine.getRenderWidth() / 2.0;
  6829. var halfHeight = engine.getRenderHeight() / 2.0;
  6830. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  6831. return this._projectionMatrix;
  6832. };
  6833. Camera.prototype.dispose = function () {
  6834. // Remove from scene
  6835. var index = this.getScene().cameras.indexOf(this);
  6836. this.getScene().cameras.splice(index, 1);
  6837. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  6838. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  6839. }
  6840. };
  6841. // Statics
  6842. Camera._PERSPECTIVE_CAMERA = 0;
  6843. Camera._ORTHOGRAPHIC_CAMERA = 1;
  6844. Camera._FOVMODE_VERTICAL_FIXED = 0;
  6845. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  6846. return Camera;
  6847. })(BABYLON.Node);
  6848. BABYLON.Camera = Camera;
  6849. })(BABYLON || (BABYLON = {}));
  6850. //# sourceMappingURL=babylon.camera.js.map
  6851. var BABYLON;
  6852. (function (BABYLON) {
  6853. var TargetCamera = (function (_super) {
  6854. __extends(TargetCamera, _super);
  6855. function TargetCamera(name, position, scene) {
  6856. _super.call(this, name, position, scene);
  6857. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  6858. this.cameraRotation = new BABYLON.Vector2(0, 0);
  6859. this.rotation = new BABYLON.Vector3(0, 0, 0);
  6860. this.speed = 2.0;
  6861. this.noRotationConstraint = false;
  6862. this.lockedTarget = null;
  6863. this._currentTarget = BABYLON.Vector3.Zero();
  6864. this._viewMatrix = BABYLON.Matrix.Zero();
  6865. this._camMatrix = BABYLON.Matrix.Zero();
  6866. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  6867. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  6868. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  6869. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  6870. this._lookAtTemp = BABYLON.Matrix.Zero();
  6871. this._tempMatrix = BABYLON.Matrix.Zero();
  6872. }
  6873. TargetCamera.prototype._getLockedTargetPosition = function () {
  6874. if (!this.lockedTarget) {
  6875. return null;
  6876. }
  6877. return this.lockedTarget.position || this.lockedTarget;
  6878. };
  6879. // Cache
  6880. TargetCamera.prototype._initCache = function () {
  6881. _super.prototype._initCache.call(this);
  6882. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6883. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6884. };
  6885. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  6886. if (!ignoreParentClass) {
  6887. _super.prototype._updateCache.call(this);
  6888. }
  6889. var lockedTargetPosition = this._getLockedTargetPosition();
  6890. if (!lockedTargetPosition) {
  6891. this._cache.lockedTarget = null;
  6892. }
  6893. else {
  6894. if (!this._cache.lockedTarget) {
  6895. this._cache.lockedTarget = lockedTargetPosition.clone();
  6896. }
  6897. else {
  6898. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  6899. }
  6900. }
  6901. this._cache.rotation.copyFrom(this.rotation);
  6902. };
  6903. // Synchronized
  6904. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  6905. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  6906. return false;
  6907. }
  6908. var lockedTargetPosition = this._getLockedTargetPosition();
  6909. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition) && this._cache.rotation.equals(this.rotation);
  6910. };
  6911. // Methods
  6912. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  6913. var engine = this.getEngine();
  6914. return this.speed * ((engine.getDeltaTime() / (engine.getFps() * 10.0)));
  6915. };
  6916. // Target
  6917. TargetCamera.prototype.setTarget = function (target) {
  6918. this.upVector.normalize();
  6919. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  6920. this._camMatrix.invert();
  6921. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  6922. var vDir = target.subtract(this.position);
  6923. if (vDir.x >= 0.0) {
  6924. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  6925. }
  6926. else {
  6927. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  6928. }
  6929. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  6930. if (isNaN(this.rotation.x)) {
  6931. this.rotation.x = 0;
  6932. }
  6933. if (isNaN(this.rotation.y)) {
  6934. this.rotation.y = 0;
  6935. }
  6936. if (isNaN(this.rotation.z)) {
  6937. this.rotation.z = 0;
  6938. }
  6939. };
  6940. TargetCamera.prototype.getTarget = function () {
  6941. return this._currentTarget;
  6942. };
  6943. TargetCamera.prototype._decideIfNeedsToMove = function () {
  6944. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  6945. };
  6946. TargetCamera.prototype._updatePosition = function () {
  6947. this.position.addInPlace(this.cameraDirection);
  6948. };
  6949. TargetCamera.prototype._update = function () {
  6950. var needToMove = this._decideIfNeedsToMove();
  6951. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  6952. // Move
  6953. if (needToMove) {
  6954. this._updatePosition();
  6955. }
  6956. // Rotate
  6957. if (needToRotate) {
  6958. this.rotation.x += this.cameraRotation.x;
  6959. this.rotation.y += this.cameraRotation.y;
  6960. if (!this.noRotationConstraint) {
  6961. var limit = (Math.PI / 2) * 0.95;
  6962. if (this.rotation.x > limit)
  6963. this.rotation.x = limit;
  6964. if (this.rotation.x < -limit)
  6965. this.rotation.x = -limit;
  6966. }
  6967. }
  6968. // Inertia
  6969. if (needToMove) {
  6970. if (Math.abs(this.cameraDirection.x) < BABYLON.Engine.Epsilon) {
  6971. this.cameraDirection.x = 0;
  6972. }
  6973. if (Math.abs(this.cameraDirection.y) < BABYLON.Engine.Epsilon) {
  6974. this.cameraDirection.y = 0;
  6975. }
  6976. if (Math.abs(this.cameraDirection.z) < BABYLON.Engine.Epsilon) {
  6977. this.cameraDirection.z = 0;
  6978. }
  6979. this.cameraDirection.scaleInPlace(this.inertia);
  6980. }
  6981. if (needToRotate) {
  6982. if (Math.abs(this.cameraRotation.x) < BABYLON.Engine.Epsilon) {
  6983. this.cameraRotation.x = 0;
  6984. }
  6985. if (Math.abs(this.cameraRotation.y) < BABYLON.Engine.Epsilon) {
  6986. this.cameraRotation.y = 0;
  6987. }
  6988. this.cameraRotation.scaleInPlace(this.inertia);
  6989. }
  6990. };
  6991. TargetCamera.prototype._getViewMatrix = function () {
  6992. if (!this.lockedTarget) {
  6993. // Compute
  6994. if (this.upVector.x != 0 || this.upVector.y != 1.0 || this.upVector.z != 0) {
  6995. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  6996. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  6997. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  6998. this._lookAtTemp.invert();
  6999. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  7000. }
  7001. else {
  7002. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  7003. }
  7004. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  7005. // Computing target and final matrix
  7006. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  7007. }
  7008. else {
  7009. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  7010. }
  7011. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  7012. return this._viewMatrix;
  7013. };
  7014. return TargetCamera;
  7015. })(BABYLON.Camera);
  7016. BABYLON.TargetCamera = TargetCamera;
  7017. })(BABYLON || (BABYLON = {}));
  7018. //# sourceMappingURL=babylon.targetCamera.js.map
  7019. var BABYLON;
  7020. (function (BABYLON) {
  7021. var FollowCamera = (function (_super) {
  7022. __extends(FollowCamera, _super);
  7023. function FollowCamera(name, position, scene) {
  7024. _super.call(this, name, position, scene);
  7025. this.radius = 12;
  7026. this.rotationOffset = 0;
  7027. this.heightOffset = 4;
  7028. this.cameraAcceleration = 0.05;
  7029. this.maxCameraSpeed = 20;
  7030. }
  7031. FollowCamera.prototype.getRadians = function (degrees) {
  7032. return degrees * Math.PI / 180;
  7033. };
  7034. FollowCamera.prototype.follow = function (cameraTarget) {
  7035. if (!cameraTarget)
  7036. return;
  7037. var radians = this.getRadians(this.rotationOffset) + cameraTarget.rotation.y;
  7038. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  7039. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  7040. var dx = targetX - this.position.x;
  7041. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  7042. var dz = (targetZ) - this.position.z;
  7043. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  7044. var vy = dy * this.cameraAcceleration;
  7045. var vz = dz * this.cameraAcceleration * 2;
  7046. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  7047. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  7048. }
  7049. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  7050. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  7051. }
  7052. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  7053. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  7054. }
  7055. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  7056. this.setTarget(cameraTarget.position);
  7057. };
  7058. FollowCamera.prototype._update = function () {
  7059. _super.prototype._update.call(this);
  7060. this.follow(this.target);
  7061. };
  7062. return FollowCamera;
  7063. })(BABYLON.TargetCamera);
  7064. BABYLON.FollowCamera = FollowCamera;
  7065. })(BABYLON || (BABYLON = {}));
  7066. //# sourceMappingURL=babylon.followCamera.js.map
  7067. var BABYLON;
  7068. (function (BABYLON) {
  7069. var FreeCamera = (function (_super) {
  7070. __extends(FreeCamera, _super);
  7071. function FreeCamera(name, position, scene) {
  7072. _super.call(this, name, position, scene);
  7073. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  7074. this.keysUp = [38];
  7075. this.keysDown = [40];
  7076. this.keysLeft = [37];
  7077. this.keysRight = [39];
  7078. this.checkCollisions = false;
  7079. this.applyGravity = false;
  7080. this.angularSensibility = 2000.0;
  7081. this._keys = [];
  7082. this._collider = new BABYLON.Collider();
  7083. this._needMoveForGravity = true;
  7084. this._oldPosition = BABYLON.Vector3.Zero();
  7085. this._diffPosition = BABYLON.Vector3.Zero();
  7086. this._newPosition = BABYLON.Vector3.Zero();
  7087. }
  7088. // Controls
  7089. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  7090. var _this = this;
  7091. var previousPosition;
  7092. var engine = this.getEngine();
  7093. if (this._attachedElement) {
  7094. return;
  7095. }
  7096. this._attachedElement = element;
  7097. if (this._onMouseDown === undefined) {
  7098. this._onMouseDown = function (evt) {
  7099. previousPosition = {
  7100. x: evt.clientX,
  7101. y: evt.clientY
  7102. };
  7103. if (!noPreventDefault) {
  7104. evt.preventDefault();
  7105. }
  7106. };
  7107. this._onMouseUp = function (evt) {
  7108. previousPosition = null;
  7109. if (!noPreventDefault) {
  7110. evt.preventDefault();
  7111. }
  7112. };
  7113. this._onMouseOut = function (evt) {
  7114. previousPosition = null;
  7115. _this._keys = [];
  7116. if (!noPreventDefault) {
  7117. evt.preventDefault();
  7118. }
  7119. };
  7120. this._onMouseMove = function (evt) {
  7121. if (!previousPosition && !engine.isPointerLock) {
  7122. return;
  7123. }
  7124. var offsetX;
  7125. var offsetY;
  7126. if (!engine.isPointerLock) {
  7127. offsetX = evt.clientX - previousPosition.x;
  7128. offsetY = evt.clientY - previousPosition.y;
  7129. }
  7130. else {
  7131. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  7132. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  7133. }
  7134. _this.cameraRotation.y += offsetX / _this.angularSensibility;
  7135. _this.cameraRotation.x += offsetY / _this.angularSensibility;
  7136. previousPosition = {
  7137. x: evt.clientX,
  7138. y: evt.clientY
  7139. };
  7140. if (!noPreventDefault) {
  7141. evt.preventDefault();
  7142. }
  7143. };
  7144. this._onKeyDown = function (evt) {
  7145. 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) {
  7146. var index = _this._keys.indexOf(evt.keyCode);
  7147. if (index === -1) {
  7148. _this._keys.push(evt.keyCode);
  7149. }
  7150. if (!noPreventDefault) {
  7151. evt.preventDefault();
  7152. }
  7153. }
  7154. };
  7155. this._onKeyUp = function (evt) {
  7156. 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) {
  7157. var index = _this._keys.indexOf(evt.keyCode);
  7158. if (index >= 0) {
  7159. _this._keys.splice(index, 1);
  7160. }
  7161. if (!noPreventDefault) {
  7162. evt.preventDefault();
  7163. }
  7164. }
  7165. };
  7166. this._onLostFocus = function () {
  7167. _this._keys = [];
  7168. };
  7169. this._reset = function () {
  7170. _this._keys = [];
  7171. previousPosition = null;
  7172. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  7173. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  7174. };
  7175. }
  7176. element.addEventListener("mousedown", this._onMouseDown, false);
  7177. element.addEventListener("mouseup", this._onMouseUp, false);
  7178. element.addEventListener("mouseout", this._onMouseOut, false);
  7179. element.addEventListener("mousemove", this._onMouseMove, false);
  7180. BABYLON.Tools.RegisterTopRootEvents([
  7181. { name: "keydown", handler: this._onKeyDown },
  7182. { name: "keyup", handler: this._onKeyUp },
  7183. { name: "blur", handler: this._onLostFocus }
  7184. ]);
  7185. };
  7186. FreeCamera.prototype.detachControl = function (element) {
  7187. if (this._attachedElement != element) {
  7188. return;
  7189. }
  7190. element.removeEventListener("mousedown", this._onMouseDown);
  7191. element.removeEventListener("mouseup", this._onMouseUp);
  7192. element.removeEventListener("mouseout", this._onMouseOut);
  7193. element.removeEventListener("mousemove", this._onMouseMove);
  7194. BABYLON.Tools.UnregisterTopRootEvents([
  7195. { name: "keydown", handler: this._onKeyDown },
  7196. { name: "keyup", handler: this._onKeyUp },
  7197. { name: "blur", handler: this._onLostFocus }
  7198. ]);
  7199. this._attachedElement = null;
  7200. if (this._reset) {
  7201. this._reset();
  7202. }
  7203. };
  7204. FreeCamera.prototype._collideWithWorld = function (velocity) {
  7205. var globalPosition;
  7206. if (this.parent) {
  7207. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  7208. }
  7209. else {
  7210. globalPosition = this.position;
  7211. }
  7212. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  7213. this._collider.radius = this.ellipsoid;
  7214. this.getScene()._getNewPosition(this._oldPosition, velocity, this._collider, 3, this._newPosition);
  7215. this._newPosition.subtractToRef(this._oldPosition, this._diffPosition);
  7216. if (this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  7217. this.position.addInPlace(this._diffPosition);
  7218. if (this.onCollide) {
  7219. this.onCollide(this._collider.collidedMesh);
  7220. }
  7221. }
  7222. };
  7223. FreeCamera.prototype._checkInputs = function () {
  7224. if (!this._localDirection) {
  7225. this._localDirection = BABYLON.Vector3.Zero();
  7226. this._transformedDirection = BABYLON.Vector3.Zero();
  7227. }
  7228. for (var index = 0; index < this._keys.length; index++) {
  7229. var keyCode = this._keys[index];
  7230. var speed = this._computeLocalCameraSpeed();
  7231. if (this.keysLeft.indexOf(keyCode) !== -1) {
  7232. this._localDirection.copyFromFloats(-speed, 0, 0);
  7233. }
  7234. else if (this.keysUp.indexOf(keyCode) !== -1) {
  7235. this._localDirection.copyFromFloats(0, 0, speed);
  7236. }
  7237. else if (this.keysRight.indexOf(keyCode) !== -1) {
  7238. this._localDirection.copyFromFloats(speed, 0, 0);
  7239. }
  7240. else if (this.keysDown.indexOf(keyCode) !== -1) {
  7241. this._localDirection.copyFromFloats(0, 0, -speed);
  7242. }
  7243. this.getViewMatrix().invertToRef(this._cameraTransformMatrix);
  7244. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  7245. this.cameraDirection.addInPlace(this._transformedDirection);
  7246. }
  7247. };
  7248. FreeCamera.prototype._decideIfNeedsToMove = function () {
  7249. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  7250. };
  7251. FreeCamera.prototype._updatePosition = function () {
  7252. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  7253. this._collideWithWorld(this.cameraDirection);
  7254. if (this.applyGravity) {
  7255. var oldPosition = this.position;
  7256. this._collideWithWorld(this.getScene().gravity);
  7257. this._needMoveForGravity = (BABYLON.Vector3.DistanceSquared(oldPosition, this.position) != 0);
  7258. }
  7259. }
  7260. else {
  7261. this.position.addInPlace(this.cameraDirection);
  7262. }
  7263. };
  7264. FreeCamera.prototype._update = function () {
  7265. this._checkInputs();
  7266. _super.prototype._update.call(this);
  7267. };
  7268. return FreeCamera;
  7269. })(BABYLON.TargetCamera);
  7270. BABYLON.FreeCamera = FreeCamera;
  7271. })(BABYLON || (BABYLON = {}));
  7272. //# sourceMappingURL=babylon.freeCamera.js.map
  7273. var BABYLON;
  7274. (function (BABYLON) {
  7275. // We're mainly based on the logic defined into the FreeCamera code
  7276. var TouchCamera = (function (_super) {
  7277. __extends(TouchCamera, _super);
  7278. function TouchCamera(name, position, scene) {
  7279. _super.call(this, name, position, scene);
  7280. this._offsetX = null;
  7281. this._offsetY = null;
  7282. this._pointerCount = 0;
  7283. this._pointerPressed = [];
  7284. this.angularSensibility = 200000.0;
  7285. this.moveSensibility = 500.0;
  7286. }
  7287. TouchCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  7288. var _this = this;
  7289. var previousPosition;
  7290. if (this._attachedCanvas) {
  7291. return;
  7292. }
  7293. this._attachedCanvas = canvas;
  7294. if (this._onPointerDown === undefined) {
  7295. this._onPointerDown = function (evt) {
  7296. if (!noPreventDefault) {
  7297. evt.preventDefault();
  7298. }
  7299. _this._pointerPressed.push(evt.pointerId);
  7300. if (_this._pointerPressed.length !== 1) {
  7301. return;
  7302. }
  7303. previousPosition = {
  7304. x: evt.clientX,
  7305. y: evt.clientY
  7306. };
  7307. };
  7308. this._onPointerUp = function (evt) {
  7309. if (!noPreventDefault) {
  7310. evt.preventDefault();
  7311. }
  7312. var index = _this._pointerPressed.indexOf(evt.pointerId);
  7313. if (index === -1) {
  7314. return;
  7315. }
  7316. _this._pointerPressed.splice(index, 1);
  7317. if (index != 0) {
  7318. return;
  7319. }
  7320. previousPosition = null;
  7321. _this._offsetX = null;
  7322. _this._offsetY = null;
  7323. };
  7324. this._onPointerMove = function (evt) {
  7325. if (!noPreventDefault) {
  7326. evt.preventDefault();
  7327. }
  7328. if (!previousPosition) {
  7329. return;
  7330. }
  7331. var index = _this._pointerPressed.indexOf(evt.pointerId);
  7332. if (index != 0) {
  7333. return;
  7334. }
  7335. _this._offsetX = evt.clientX - previousPosition.x;
  7336. _this._offsetY = -(evt.clientY - previousPosition.y);
  7337. };
  7338. this._onLostFocus = function () {
  7339. _this._offsetX = null;
  7340. _this._offsetY = null;
  7341. };
  7342. }
  7343. canvas.addEventListener("pointerdown", this._onPointerDown);
  7344. canvas.addEventListener("pointerup", this._onPointerUp);
  7345. canvas.addEventListener("pointerout", this._onPointerUp);
  7346. canvas.addEventListener("pointermove", this._onPointerMove);
  7347. BABYLON.Tools.RegisterTopRootEvents([
  7348. { name: "blur", handler: this._onLostFocus }
  7349. ]);
  7350. };
  7351. TouchCamera.prototype.detachControl = function (canvas) {
  7352. if (this._attachedCanvas != canvas) {
  7353. return;
  7354. }
  7355. canvas.removeEventListener("pointerdown", this._onPointerDown);
  7356. canvas.removeEventListener("pointerup", this._onPointerUp);
  7357. canvas.removeEventListener("pointerout", this._onPointerUp);
  7358. canvas.removeEventListener("pointermove", this._onPointerMove);
  7359. BABYLON.Tools.UnregisterTopRootEvents([
  7360. { name: "blur", handler: this._onLostFocus }
  7361. ]);
  7362. this._attachedCanvas = null;
  7363. };
  7364. TouchCamera.prototype._checkInputs = function () {
  7365. if (!this._offsetX) {
  7366. return;
  7367. }
  7368. this.cameraRotation.y += this._offsetX / this.angularSensibility;
  7369. if (this._pointerPressed.length > 1) {
  7370. this.cameraRotation.x += -this._offsetY / this.angularSensibility;
  7371. }
  7372. else {
  7373. var speed = this._computeLocalCameraSpeed();
  7374. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  7375. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  7376. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  7377. }
  7378. };
  7379. return TouchCamera;
  7380. })(BABYLON.FreeCamera);
  7381. BABYLON.TouchCamera = TouchCamera;
  7382. })(BABYLON || (BABYLON = {}));
  7383. //# sourceMappingURL=babylon.touchCamera.js.map
  7384. var BABYLON;
  7385. (function (BABYLON) {
  7386. // We're mainly based on the logic defined into the FreeCamera code
  7387. var DeviceOrientationCamera = (function (_super) {
  7388. __extends(DeviceOrientationCamera, _super);
  7389. function DeviceOrientationCamera(name, position, scene) {
  7390. var _this = this;
  7391. _super.call(this, name, position, scene);
  7392. this._offsetX = null;
  7393. this._offsetY = null;
  7394. this._orientationGamma = 0;
  7395. this._orientationBeta = 0;
  7396. this._initialOrientationGamma = 0;
  7397. this._initialOrientationBeta = 0;
  7398. this.angularSensibility = 10000.0;
  7399. this.moveSensibility = 50.0;
  7400. window.addEventListener("resize", function () {
  7401. _this._initialOrientationGamma = null;
  7402. }, false);
  7403. }
  7404. DeviceOrientationCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  7405. var _this = this;
  7406. if (this._attachedCanvas) {
  7407. return;
  7408. }
  7409. this._attachedCanvas = canvas;
  7410. if (!this._orientationChanged) {
  7411. this._orientationChanged = function (evt) {
  7412. if (!_this._initialOrientationGamma) {
  7413. _this._initialOrientationGamma = evt.gamma;
  7414. _this._initialOrientationBeta = evt.beta;
  7415. }
  7416. _this._orientationGamma = evt.gamma;
  7417. _this._orientationBeta = evt.beta;
  7418. _this._offsetY = (_this._initialOrientationBeta - _this._orientationBeta);
  7419. _this._offsetX = (_this._initialOrientationGamma - _this._orientationGamma);
  7420. };
  7421. }
  7422. window.addEventListener("deviceorientation", this._orientationChanged);
  7423. };
  7424. DeviceOrientationCamera.prototype.detachControl = function (canvas) {
  7425. if (this._attachedCanvas != canvas) {
  7426. return;
  7427. }
  7428. window.removeEventListener("deviceorientation", this._orientationChanged);
  7429. this._attachedCanvas = null;
  7430. this._orientationGamma = 0;
  7431. this._orientationBeta = 0;
  7432. this._initialOrientationGamma = 0;
  7433. this._initialOrientationBeta = 0;
  7434. };
  7435. DeviceOrientationCamera.prototype._checkInputs = function () {
  7436. if (!this._offsetX) {
  7437. return;
  7438. }
  7439. this.cameraRotation.y -= this._offsetX / this.angularSensibility;
  7440. var speed = this._computeLocalCameraSpeed();
  7441. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  7442. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  7443. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  7444. };
  7445. return DeviceOrientationCamera;
  7446. })(BABYLON.FreeCamera);
  7447. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  7448. })(BABYLON || (BABYLON = {}));
  7449. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  7450. var BABYLON;
  7451. (function (BABYLON) {
  7452. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  7453. var ArcRotateCamera = (function (_super) {
  7454. __extends(ArcRotateCamera, _super);
  7455. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  7456. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  7457. this.alpha = alpha;
  7458. this.beta = beta;
  7459. this.radius = radius;
  7460. this.target = target;
  7461. this.inertialAlphaOffset = 0;
  7462. this.inertialBetaOffset = 0;
  7463. this.inertialRadiusOffset = 0;
  7464. this.lowerAlphaLimit = null;
  7465. this.upperAlphaLimit = null;
  7466. this.lowerBetaLimit = 0.01;
  7467. this.upperBetaLimit = Math.PI;
  7468. this.lowerRadiusLimit = null;
  7469. this.upperRadiusLimit = null;
  7470. this.angularSensibility = 1000.0;
  7471. this.wheelPrecision = 3.0;
  7472. this.keysUp = [38];
  7473. this.keysDown = [40];
  7474. this.keysLeft = [37];
  7475. this.keysRight = [39];
  7476. this.zoomOnFactor = 1;
  7477. this.targetScreenOffset = BABYLON.Vector2.Zero();
  7478. this._keys = [];
  7479. this._viewMatrix = new BABYLON.Matrix();
  7480. this.checkCollisions = false;
  7481. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  7482. this._collider = new BABYLON.Collider();
  7483. this._previousPosition = BABYLON.Vector3.Zero();
  7484. this._collisionVelocity = BABYLON.Vector3.Zero();
  7485. this._newPosition = BABYLON.Vector3.Zero();
  7486. // Pinch
  7487. // value for pinch step scaling
  7488. // set to 20 by default
  7489. this.pinchPrecision = 20;
  7490. this.getViewMatrix();
  7491. }
  7492. ArcRotateCamera.prototype._getTargetPosition = function () {
  7493. return this.target.position || this.target;
  7494. };
  7495. // Cache
  7496. ArcRotateCamera.prototype._initCache = function () {
  7497. _super.prototype._initCache.call(this);
  7498. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7499. this._cache.alpha = undefined;
  7500. this._cache.beta = undefined;
  7501. this._cache.radius = undefined;
  7502. this._cache.targetScreenOffset = undefined;
  7503. };
  7504. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  7505. if (!ignoreParentClass) {
  7506. _super.prototype._updateCache.call(this);
  7507. }
  7508. this._cache.target.copyFrom(this._getTargetPosition());
  7509. this._cache.alpha = this.alpha;
  7510. this._cache.beta = this.beta;
  7511. this._cache.radius = this.radius;
  7512. this._cache.targetScreenOffset = this.targetScreenOffset.clone();
  7513. };
  7514. // Synchronized
  7515. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  7516. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  7517. return false;
  7518. 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);
  7519. };
  7520. // Methods
  7521. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault) {
  7522. var _this = this;
  7523. var previousPosition;
  7524. var pointerId;
  7525. // to know if pinch started
  7526. var pinchStarted = false;
  7527. // two pinch point on X
  7528. // that will use for find if user action is pinch open or pinch close
  7529. var pinchPointX1, pinchPointX2;
  7530. if (this._attachedElement) {
  7531. return;
  7532. }
  7533. this._attachedElement = element;
  7534. var engine = this.getEngine();
  7535. if (this._onPointerDown === undefined) {
  7536. this._onPointerDown = function (evt) {
  7537. if (pointerId) {
  7538. return;
  7539. }
  7540. pointerId = evt.pointerId;
  7541. previousPosition = {
  7542. x: evt.clientX,
  7543. y: evt.clientY
  7544. };
  7545. if (!noPreventDefault) {
  7546. evt.preventDefault();
  7547. }
  7548. };
  7549. this._onPointerUp = function (evt) {
  7550. previousPosition = null;
  7551. pointerId = null;
  7552. if (!noPreventDefault) {
  7553. evt.preventDefault();
  7554. }
  7555. };
  7556. this._onPointerMove = function (evt) {
  7557. if (!previousPosition) {
  7558. return;
  7559. }
  7560. if (pointerId !== evt.pointerId) {
  7561. return;
  7562. }
  7563. // return pinch is started
  7564. if (pinchStarted) {
  7565. return;
  7566. }
  7567. var offsetX = evt.clientX - previousPosition.x;
  7568. var offsetY = evt.clientY - previousPosition.y;
  7569. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  7570. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  7571. previousPosition = {
  7572. x: evt.clientX,
  7573. y: evt.clientY
  7574. };
  7575. if (!noPreventDefault) {
  7576. evt.preventDefault();
  7577. }
  7578. };
  7579. this._onMouseMove = function (evt) {
  7580. if (!engine.isPointerLock) {
  7581. return;
  7582. }
  7583. // return pinch is started
  7584. if (pinchStarted) {
  7585. return;
  7586. }
  7587. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  7588. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  7589. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  7590. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  7591. if (!noPreventDefault) {
  7592. evt.preventDefault();
  7593. }
  7594. };
  7595. this._wheel = function (event) {
  7596. var delta = 0;
  7597. if (event.wheelDelta) {
  7598. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  7599. }
  7600. else if (event.detail) {
  7601. delta = -event.detail / _this.wheelPrecision;
  7602. }
  7603. if (delta)
  7604. _this.inertialRadiusOffset += delta;
  7605. if (event.preventDefault) {
  7606. if (!noPreventDefault) {
  7607. event.preventDefault();
  7608. }
  7609. }
  7610. };
  7611. this._onKeyDown = function (evt) {
  7612. 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) {
  7613. var index = _this._keys.indexOf(evt.keyCode);
  7614. if (index === -1) {
  7615. _this._keys.push(evt.keyCode);
  7616. }
  7617. if (evt.preventDefault) {
  7618. if (!noPreventDefault) {
  7619. evt.preventDefault();
  7620. }
  7621. }
  7622. }
  7623. };
  7624. this._onKeyUp = function (evt) {
  7625. 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) {
  7626. var index = _this._keys.indexOf(evt.keyCode);
  7627. if (index >= 0) {
  7628. _this._keys.splice(index, 1);
  7629. }
  7630. if (evt.preventDefault) {
  7631. if (!noPreventDefault) {
  7632. evt.preventDefault();
  7633. }
  7634. }
  7635. }
  7636. };
  7637. this._onLostFocus = function () {
  7638. _this._keys = [];
  7639. pointerId = null;
  7640. };
  7641. this._onGestureStart = function (e) {
  7642. if (window.MSGesture === undefined) {
  7643. return;
  7644. }
  7645. if (!_this._MSGestureHandler) {
  7646. _this._MSGestureHandler = new MSGesture();
  7647. _this._MSGestureHandler.target = element;
  7648. }
  7649. _this._MSGestureHandler.addPointer(e.pointerId);
  7650. };
  7651. this._onGesture = function (e) {
  7652. _this.radius *= e.scale;
  7653. if (e.preventDefault) {
  7654. if (!noPreventDefault) {
  7655. e.stopPropagation();
  7656. e.preventDefault();
  7657. }
  7658. }
  7659. };
  7660. this._reset = function () {
  7661. _this._keys = [];
  7662. _this.inertialAlphaOffset = 0;
  7663. _this.inertialBetaOffset = 0;
  7664. _this.inertialRadiusOffset = 0;
  7665. previousPosition = null;
  7666. pointerId = null;
  7667. };
  7668. this._touchStart = function (event) {
  7669. if (event.touches.length === 2) {
  7670. //-- start pinch if two fingers on the screen
  7671. pinchStarted = true;
  7672. _this._pinchStart(event);
  7673. }
  7674. };
  7675. this._touchMove = function (event) {
  7676. if (pinchStarted) {
  7677. //-- make scaling
  7678. _this._pinchMove(event);
  7679. }
  7680. };
  7681. this._touchEnd = function (event) {
  7682. if (pinchStarted) {
  7683. //-- end of pinch
  7684. _this._pinchEnd(event);
  7685. }
  7686. };
  7687. this._pinchStart = function (event) {
  7688. // save origin touch point
  7689. pinchPointX1 = event.touches[0].clientX;
  7690. pinchPointX2 = event.touches[1].clientX;
  7691. // block the camera
  7692. // if not it rotate around target during pinch
  7693. pinchStarted = true;
  7694. };
  7695. this._pinchMove = function (event) {
  7696. // variable for new camera's radius
  7697. var delta = 0;
  7698. // variables to know if pinch open or pinch close
  7699. var direction = 1;
  7700. var distanceXOrigine, distanceXNow;
  7701. if (event.touches.length !== 2)
  7702. return;
  7703. // calculate absolute distances of the two fingers
  7704. distanceXOrigine = Math.abs(pinchPointX1 - pinchPointX2);
  7705. distanceXNow = Math.abs(event.touches[0].clientX - event.touches[1].clientX);
  7706. // if distanceXNow < distanceXOrigine -> pinch close so direction = -1
  7707. if (distanceXNow < distanceXOrigine) {
  7708. direction = -1;
  7709. }
  7710. // calculate new radius
  7711. delta = (_this.pinchPrecision / (_this.wheelPrecision * 40)) * direction;
  7712. // set new radius
  7713. _this.inertialRadiusOffset -= delta;
  7714. // save origin touch point
  7715. pinchPointX1 = event.touches[0].clientX;
  7716. pinchPointX2 = event.touches[1].clientX;
  7717. };
  7718. this._pinchEnd = function (event) {
  7719. // cancel pinch and deblock camera rotation
  7720. pinchStarted = false;
  7721. };
  7722. }
  7723. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  7724. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  7725. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  7726. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  7727. element.addEventListener("mousemove", this._onMouseMove, false);
  7728. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  7729. element.addEventListener("MSGestureChange", this._onGesture, false);
  7730. element.addEventListener('mousewheel', this._wheel, false);
  7731. element.addEventListener('DOMMouseScroll', this._wheel, false);
  7732. // pinch
  7733. element.addEventListener('touchstart', this._touchStart, false);
  7734. element.addEventListener('touchmove', this._touchMove, false);
  7735. element.addEventListener('touchend', this._touchEnd, false);
  7736. BABYLON.Tools.RegisterTopRootEvents([
  7737. { name: "keydown", handler: this._onKeyDown },
  7738. { name: "keyup", handler: this._onKeyUp },
  7739. { name: "blur", handler: this._onLostFocus }
  7740. ]);
  7741. };
  7742. ArcRotateCamera.prototype.detachControl = function (element) {
  7743. if (this._attachedElement != element) {
  7744. return;
  7745. }
  7746. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  7747. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  7748. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  7749. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  7750. element.removeEventListener("mousemove", this._onMouseMove);
  7751. element.removeEventListener("MSPointerDown", this._onGestureStart);
  7752. element.removeEventListener("MSGestureChange", this._onGesture);
  7753. element.removeEventListener('mousewheel', this._wheel);
  7754. element.removeEventListener('DOMMouseScroll', this._wheel);
  7755. // pinch
  7756. element.removeEventListener('touchstart', this._touchStart);
  7757. element.removeEventListener('touchmove', this._touchMove);
  7758. element.removeEventListener('touchend', this._touchEnd);
  7759. BABYLON.Tools.UnregisterTopRootEvents([
  7760. { name: "keydown", handler: this._onKeyDown },
  7761. { name: "keyup", handler: this._onKeyUp },
  7762. { name: "blur", handler: this._onLostFocus }
  7763. ]);
  7764. this._MSGestureHandler = null;
  7765. this._attachedElement = null;
  7766. if (this._reset) {
  7767. this._reset();
  7768. }
  7769. };
  7770. ArcRotateCamera.prototype._update = function () {
  7771. for (var index = 0; index < this._keys.length; index++) {
  7772. var keyCode = this._keys[index];
  7773. if (this.keysLeft.indexOf(keyCode) !== -1) {
  7774. this.inertialAlphaOffset -= 0.01;
  7775. }
  7776. else if (this.keysUp.indexOf(keyCode) !== -1) {
  7777. this.inertialBetaOffset -= 0.01;
  7778. }
  7779. else if (this.keysRight.indexOf(keyCode) !== -1) {
  7780. this.inertialAlphaOffset += 0.01;
  7781. }
  7782. else if (this.keysDown.indexOf(keyCode) !== -1) {
  7783. this.inertialBetaOffset += 0.01;
  7784. }
  7785. }
  7786. // Inertia
  7787. if (this.inertialAlphaOffset != 0 || this.inertialBetaOffset != 0 || this.inertialRadiusOffset != 0) {
  7788. this.alpha += this.inertialAlphaOffset;
  7789. this.beta += this.inertialBetaOffset;
  7790. this.radius -= this.inertialRadiusOffset;
  7791. this.inertialAlphaOffset *= this.inertia;
  7792. this.inertialBetaOffset *= this.inertia;
  7793. this.inertialRadiusOffset *= this.inertia;
  7794. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Engine.Epsilon)
  7795. this.inertialAlphaOffset = 0;
  7796. if (Math.abs(this.inertialBetaOffset) < BABYLON.Engine.Epsilon)
  7797. this.inertialBetaOffset = 0;
  7798. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Engine.Epsilon)
  7799. this.inertialRadiusOffset = 0;
  7800. }
  7801. // Limits
  7802. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  7803. this.alpha = this.lowerAlphaLimit;
  7804. }
  7805. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  7806. this.alpha = this.upperAlphaLimit;
  7807. }
  7808. if (this.lowerBetaLimit && this.beta < this.lowerBetaLimit) {
  7809. this.beta = this.lowerBetaLimit;
  7810. }
  7811. if (this.upperBetaLimit && this.beta > this.upperBetaLimit) {
  7812. this.beta = this.upperBetaLimit;
  7813. }
  7814. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  7815. this.radius = this.lowerRadiusLimit;
  7816. }
  7817. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  7818. this.radius = this.upperRadiusLimit;
  7819. }
  7820. };
  7821. ArcRotateCamera.prototype.setPosition = function (position) {
  7822. var radiusv3 = position.subtract(this._getTargetPosition());
  7823. this.radius = radiusv3.length();
  7824. // Alpha
  7825. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  7826. if (radiusv3.z < 0) {
  7827. this.alpha = 2 * Math.PI - this.alpha;
  7828. }
  7829. // Beta
  7830. this.beta = Math.acos(radiusv3.y / this.radius);
  7831. };
  7832. ArcRotateCamera.prototype._getViewMatrix = function () {
  7833. // Compute
  7834. var cosa = Math.cos(this.alpha);
  7835. var sina = Math.sin(this.alpha);
  7836. var cosb = Math.cos(this.beta);
  7837. var sinb = Math.sin(this.beta);
  7838. var target = this._getTargetPosition();
  7839. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this.position);
  7840. if (this.checkCollisions) {
  7841. this._collider.radius = this.collisionRadius;
  7842. this.position.subtractToRef(this._previousPosition, this._collisionVelocity);
  7843. this.getScene()._getNewPosition(this._previousPosition, this._collisionVelocity, this._collider, 3, this._newPosition);
  7844. if (!this._newPosition.equalsWithEpsilon(this.position)) {
  7845. this.position.copyFrom(this._previousPosition);
  7846. this.alpha = this._previousAlpha;
  7847. this.beta = this._previousBeta;
  7848. this.radius = this._previousRadius;
  7849. if (this.onCollide) {
  7850. this.onCollide(this._collider.collidedMesh);
  7851. }
  7852. }
  7853. }
  7854. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._viewMatrix);
  7855. this._previousAlpha = this.alpha;
  7856. this._previousBeta = this.beta;
  7857. this._previousRadius = this.radius;
  7858. this._previousPosition.copyFrom(this.position);
  7859. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  7860. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  7861. return this._viewMatrix;
  7862. };
  7863. ArcRotateCamera.prototype.zoomOn = function (meshes) {
  7864. meshes = meshes || this.getScene().meshes;
  7865. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  7866. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  7867. this.radius = distance * this.zoomOnFactor;
  7868. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance });
  7869. };
  7870. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance) {
  7871. var meshesOrMinMaxVector;
  7872. var distance;
  7873. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  7874. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  7875. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  7876. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  7877. }
  7878. else {
  7879. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  7880. distance = meshesOrMinMaxVectorAndDistance.distance;
  7881. }
  7882. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  7883. this.maxZ = distance * 2;
  7884. };
  7885. return ArcRotateCamera;
  7886. })(BABYLON.Camera);
  7887. BABYLON.ArcRotateCamera = ArcRotateCamera;
  7888. })(BABYLON || (BABYLON = {}));
  7889. //# sourceMappingURL=babylon.arcRotateCamera.js.mapvar BABYLON;
  7890. (function (BABYLON) {
  7891. /**
  7892. * Represents a scene to be rendered by the engine.
  7893. * @see http://doc.babylonjs.com/page.php?p=21911
  7894. */
  7895. var Scene = (function () {
  7896. /**
  7897. * @constructor
  7898. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  7899. */
  7900. function Scene(engine) {
  7901. // Members
  7902. this.autoClear = true;
  7903. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  7904. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  7905. this.forceWireframe = false;
  7906. this.forcePointsCloud = false;
  7907. this.forceShowBoundingBoxes = false;
  7908. this.animationsEnabled = true;
  7909. 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
  7910. // Fog
  7911. /**
  7912. * is fog enabled on this scene.
  7913. * @type {boolean}
  7914. */
  7915. this.fogEnabled = true;
  7916. this.fogMode = Scene.FOGMODE_NONE;
  7917. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  7918. this.fogDensity = 0.1;
  7919. this.fogStart = 0;
  7920. this.fogEnd = 1000.0;
  7921. // Lights
  7922. /**
  7923. * is shadow enabled on this scene.
  7924. * @type {boolean}
  7925. */
  7926. this.shadowsEnabled = true;
  7927. /**
  7928. * is light enabled on this scene.
  7929. * @type {boolean}
  7930. */
  7931. this.lightsEnabled = true;
  7932. /**
  7933. * All of the lights added to this scene.
  7934. * @see BABYLON.Light
  7935. * @type {BABYLON.Light[]}
  7936. */
  7937. this.lights = new Array();
  7938. // Cameras
  7939. /**
  7940. * All of the cameras added to this scene.
  7941. * @see BABYLON.Camera
  7942. * @type {BABYLON.Camera[]}
  7943. */
  7944. this.cameras = new Array();
  7945. this.activeCameras = new Array();
  7946. // Meshes
  7947. /**
  7948. * All of the (abstract) meshes added to this scene.
  7949. * @see BABYLON.AbstractMesh
  7950. * @type {BABYLON.AbstractMesh[]}
  7951. */
  7952. this.meshes = new Array();
  7953. // Geometries
  7954. this._geometries = new Array();
  7955. this.materials = new Array();
  7956. this.multiMaterials = new Array();
  7957. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  7958. // Textures
  7959. this.texturesEnabled = true;
  7960. this.textures = new Array();
  7961. // Particles
  7962. this.particlesEnabled = true;
  7963. this.particleSystems = new Array();
  7964. // Sprites
  7965. this.spritesEnabled = true;
  7966. this.spriteManagers = new Array();
  7967. // Layers
  7968. this.layers = new Array();
  7969. // Skeletons
  7970. this.skeletonsEnabled = true;
  7971. this.skeletons = new Array();
  7972. // Lens flares
  7973. this.lensFlaresEnabled = true;
  7974. this.lensFlareSystems = new Array();
  7975. // Collisions
  7976. this.collisionsEnabled = true;
  7977. this.gravity = new BABYLON.Vector3(0, -9.0, 0);
  7978. // Postprocesses
  7979. this.postProcessesEnabled = true;
  7980. // Customs render targets
  7981. this.renderTargetsEnabled = true;
  7982. this.dumpNextRenderTargets = false;
  7983. this.customRenderTargets = new Array();
  7984. // Imported meshes
  7985. this.importedMeshesFiles = new Array();
  7986. this._actionManagers = new Array();
  7987. this._meshesForIntersections = new BABYLON.SmartArray(256);
  7988. // Procedural textures
  7989. this.proceduralTexturesEnabled = true;
  7990. this._proceduralTextures = new Array();
  7991. this.soundTracks = new Array();
  7992. this._audioEnabled = true;
  7993. this._headphone = false;
  7994. this._totalVertices = 0;
  7995. this._activeVertices = 0;
  7996. this._activeParticles = 0;
  7997. this._lastFrameDuration = 0;
  7998. this._evaluateActiveMeshesDuration = 0;
  7999. this._renderTargetsDuration = 0;
  8000. this._particlesDuration = 0;
  8001. this._renderDuration = 0;
  8002. this._spritesDuration = 0;
  8003. this._animationRatio = 0;
  8004. this._renderId = 0;
  8005. this._executeWhenReadyTimeoutId = -1;
  8006. this._toBeDisposed = new BABYLON.SmartArray(256);
  8007. this._onReadyCallbacks = new Array();
  8008. this._pendingData = []; //ANY
  8009. this._onBeforeRenderCallbacks = new Array();
  8010. this._onAfterRenderCallbacks = new Array();
  8011. this._activeMeshes = new BABYLON.SmartArray(256);
  8012. this._processedMaterials = new BABYLON.SmartArray(256);
  8013. this._renderTargets = new BABYLON.SmartArray(256);
  8014. this._activeParticleSystems = new BABYLON.SmartArray(256);
  8015. this._activeSkeletons = new BABYLON.SmartArray(32);
  8016. this._activeBones = 0;
  8017. this._activeAnimatables = new Array();
  8018. this._transformMatrix = BABYLON.Matrix.Zero();
  8019. this._scaledPosition = BABYLON.Vector3.Zero();
  8020. this._scaledVelocity = BABYLON.Vector3.Zero();
  8021. this._engine = engine;
  8022. engine.scenes.push(this);
  8023. this._renderingManager = new BABYLON.RenderingManager(this);
  8024. this.postProcessManager = new BABYLON.PostProcessManager(this);
  8025. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  8026. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  8027. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  8028. this.attachControl();
  8029. this._debugLayer = new BABYLON.DebugLayer(this);
  8030. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  8031. //simplification queue
  8032. this.simplificationQueue = new BABYLON.SimplificationQueue();
  8033. }
  8034. Object.defineProperty(Scene, "FOGMODE_NONE", {
  8035. get: function () {
  8036. return Scene._FOGMODE_NONE;
  8037. },
  8038. enumerable: true,
  8039. configurable: true
  8040. });
  8041. Object.defineProperty(Scene, "FOGMODE_EXP", {
  8042. get: function () {
  8043. return Scene._FOGMODE_EXP;
  8044. },
  8045. enumerable: true,
  8046. configurable: true
  8047. });
  8048. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  8049. get: function () {
  8050. return Scene._FOGMODE_EXP2;
  8051. },
  8052. enumerable: true,
  8053. configurable: true
  8054. });
  8055. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  8056. get: function () {
  8057. return Scene._FOGMODE_LINEAR;
  8058. },
  8059. enumerable: true,
  8060. configurable: true
  8061. });
  8062. Object.defineProperty(Scene.prototype, "debugLayer", {
  8063. // Properties
  8064. get: function () {
  8065. return this._debugLayer;
  8066. },
  8067. enumerable: true,
  8068. configurable: true
  8069. });
  8070. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  8071. /**
  8072. * The mesh that is currently under the pointer.
  8073. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  8074. */
  8075. get: function () {
  8076. return this._meshUnderPointer;
  8077. },
  8078. enumerable: true,
  8079. configurable: true
  8080. });
  8081. Object.defineProperty(Scene.prototype, "pointerX", {
  8082. /**
  8083. * Current on-screen X position of the pointer
  8084. * @return {number} X position of the pointer
  8085. */
  8086. get: function () {
  8087. return this._pointerX;
  8088. },
  8089. enumerable: true,
  8090. configurable: true
  8091. });
  8092. Object.defineProperty(Scene.prototype, "pointerY", {
  8093. /**
  8094. * Current on-screen Y position of the pointer
  8095. * @return {number} Y position of the pointer
  8096. */
  8097. get: function () {
  8098. return this._pointerY;
  8099. },
  8100. enumerable: true,
  8101. configurable: true
  8102. });
  8103. Scene.prototype.getCachedMaterial = function () {
  8104. return this._cachedMaterial;
  8105. };
  8106. Scene.prototype.getBoundingBoxRenderer = function () {
  8107. return this._boundingBoxRenderer;
  8108. };
  8109. Scene.prototype.getOutlineRenderer = function () {
  8110. return this._outlineRenderer;
  8111. };
  8112. Scene.prototype.getEngine = function () {
  8113. return this._engine;
  8114. };
  8115. Scene.prototype.getTotalVertices = function () {
  8116. return this._totalVertices;
  8117. };
  8118. Scene.prototype.getActiveVertices = function () {
  8119. return this._activeVertices;
  8120. };
  8121. Scene.prototype.getActiveParticles = function () {
  8122. return this._activeParticles;
  8123. };
  8124. Scene.prototype.getActiveBones = function () {
  8125. return this._activeBones;
  8126. };
  8127. // Stats
  8128. Scene.prototype.getLastFrameDuration = function () {
  8129. return this._lastFrameDuration;
  8130. };
  8131. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  8132. return this._evaluateActiveMeshesDuration;
  8133. };
  8134. Scene.prototype.getActiveMeshes = function () {
  8135. return this._activeMeshes;
  8136. };
  8137. Scene.prototype.getRenderTargetsDuration = function () {
  8138. return this._renderTargetsDuration;
  8139. };
  8140. Scene.prototype.getRenderDuration = function () {
  8141. return this._renderDuration;
  8142. };
  8143. Scene.prototype.getParticlesDuration = function () {
  8144. return this._particlesDuration;
  8145. };
  8146. Scene.prototype.getSpritesDuration = function () {
  8147. return this._spritesDuration;
  8148. };
  8149. Scene.prototype.getAnimationRatio = function () {
  8150. return this._animationRatio;
  8151. };
  8152. Scene.prototype.getRenderId = function () {
  8153. return this._renderId;
  8154. };
  8155. Scene.prototype.incrementRenderId = function () {
  8156. this._renderId++;
  8157. };
  8158. Scene.prototype._updatePointerPosition = function (evt) {
  8159. var canvasRect = this._engine.getRenderingCanvasClientRect();
  8160. this._pointerX = evt.clientX - canvasRect.left;
  8161. this._pointerY = evt.clientY - canvasRect.top;
  8162. if (this.cameraToUseForPointers) {
  8163. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  8164. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  8165. }
  8166. };
  8167. // Pointers handling
  8168. Scene.prototype.attachControl = function () {
  8169. var _this = this;
  8170. this._onPointerMove = function (evt) {
  8171. var canvas = _this._engine.getRenderingCanvas();
  8172. _this._updatePointerPosition(evt);
  8173. 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);
  8174. if (pickResult.hit) {
  8175. _this._meshUnderPointer = pickResult.pickedMesh;
  8176. _this.setPointerOverMesh(pickResult.pickedMesh);
  8177. canvas.style.cursor = "pointer";
  8178. }
  8179. else {
  8180. _this.setPointerOverMesh(null);
  8181. canvas.style.cursor = "";
  8182. _this._meshUnderPointer = null;
  8183. }
  8184. };
  8185. this._onPointerDown = function (evt) {
  8186. var predicate = null;
  8187. if (!_this.onPointerDown) {
  8188. predicate = function (mesh) {
  8189. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPickTriggers;
  8190. };
  8191. }
  8192. _this._updatePointerPosition(evt);
  8193. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  8194. if (pickResult.hit) {
  8195. if (pickResult.pickedMesh.actionManager) {
  8196. switch (evt.button) {
  8197. case 0:
  8198. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  8199. break;
  8200. case 1:
  8201. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  8202. break;
  8203. case 2:
  8204. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  8205. break;
  8206. }
  8207. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  8208. }
  8209. }
  8210. if (_this.onPointerDown) {
  8211. _this.onPointerDown(evt, pickResult);
  8212. }
  8213. };
  8214. this._onKeyDown = function (evt) {
  8215. if (_this.actionManager) {
  8216. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  8217. }
  8218. };
  8219. this._onKeyUp = function (evt) {
  8220. if (_this.actionManager) {
  8221. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  8222. }
  8223. };
  8224. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  8225. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  8226. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  8227. BABYLON.Tools.RegisterTopRootEvents([
  8228. { name: "keydown", handler: this._onKeyDown },
  8229. { name: "keyup", handler: this._onKeyUp }
  8230. ]);
  8231. };
  8232. Scene.prototype.detachControl = function () {
  8233. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  8234. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  8235. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  8236. BABYLON.Tools.UnregisterTopRootEvents([
  8237. { name: "keydown", handler: this._onKeyDown },
  8238. { name: "keyup", handler: this._onKeyUp }
  8239. ]);
  8240. };
  8241. // Ready
  8242. Scene.prototype.isReady = function () {
  8243. if (this._pendingData.length > 0) {
  8244. return false;
  8245. }
  8246. for (var index = 0; index < this._geometries.length; index++) {
  8247. var geometry = this._geometries[index];
  8248. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  8249. return false;
  8250. }
  8251. }
  8252. for (index = 0; index < this.meshes.length; index++) {
  8253. var mesh = this.meshes[index];
  8254. if (!mesh.isReady()) {
  8255. return false;
  8256. }
  8257. var mat = mesh.material;
  8258. if (mat) {
  8259. if (!mat.isReady(mesh)) {
  8260. return false;
  8261. }
  8262. }
  8263. }
  8264. return true;
  8265. };
  8266. Scene.prototype.resetCachedMaterial = function () {
  8267. this._cachedMaterial = null;
  8268. };
  8269. Scene.prototype.registerBeforeRender = function (func) {
  8270. this._onBeforeRenderCallbacks.push(func);
  8271. };
  8272. Scene.prototype.unregisterBeforeRender = function (func) {
  8273. var index = this._onBeforeRenderCallbacks.indexOf(func);
  8274. if (index > -1) {
  8275. this._onBeforeRenderCallbacks.splice(index, 1);
  8276. }
  8277. };
  8278. Scene.prototype.registerAfterRender = function (func) {
  8279. this._onAfterRenderCallbacks.push(func);
  8280. };
  8281. Scene.prototype.unregisterAfterRender = function (func) {
  8282. var index = this._onAfterRenderCallbacks.indexOf(func);
  8283. if (index > -1) {
  8284. this._onAfterRenderCallbacks.splice(index, 1);
  8285. }
  8286. };
  8287. Scene.prototype._addPendingData = function (data) {
  8288. this._pendingData.push(data);
  8289. };
  8290. Scene.prototype._removePendingData = function (data) {
  8291. var index = this._pendingData.indexOf(data);
  8292. if (index !== -1) {
  8293. this._pendingData.splice(index, 1);
  8294. }
  8295. };
  8296. Scene.prototype.getWaitingItemsCount = function () {
  8297. return this._pendingData.length;
  8298. };
  8299. /**
  8300. * Registers a function to be executed when the scene is ready.
  8301. * @param {Function} func - the function to be executed.
  8302. */
  8303. Scene.prototype.executeWhenReady = function (func) {
  8304. var _this = this;
  8305. this._onReadyCallbacks.push(func);
  8306. if (this._executeWhenReadyTimeoutId !== -1) {
  8307. return;
  8308. }
  8309. this._executeWhenReadyTimeoutId = setTimeout(function () {
  8310. _this._checkIsReady();
  8311. }, 150);
  8312. };
  8313. Scene.prototype._checkIsReady = function () {
  8314. var _this = this;
  8315. if (this.isReady()) {
  8316. this._onReadyCallbacks.forEach(function (func) {
  8317. func();
  8318. });
  8319. this._onReadyCallbacks = [];
  8320. this._executeWhenReadyTimeoutId = -1;
  8321. return;
  8322. }
  8323. this._executeWhenReadyTimeoutId = setTimeout(function () {
  8324. _this._checkIsReady();
  8325. }, 150);
  8326. };
  8327. // Animations
  8328. /**
  8329. * Will start the animation sequence of a given target
  8330. * @param target - the target
  8331. * @param {number} from - from which frame should animation start
  8332. * @param {number} to - till which frame should animation run.
  8333. * @param {boolean} [loop] - should the animation loop
  8334. * @param {number} [speedRatio] - the speed in which to run the animation
  8335. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  8336. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  8337. * @return {BABYLON.Animatable} the animatable object created for this animation
  8338. * @see BABYLON.Animatable
  8339. * @see http://doc.babylonjs.com/page.php?p=22081
  8340. */
  8341. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  8342. if (speedRatio === undefined) {
  8343. speedRatio = 1.0;
  8344. }
  8345. this.stopAnimation(target);
  8346. if (!animatable) {
  8347. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  8348. }
  8349. // Local animations
  8350. if (target.animations) {
  8351. animatable.appendAnimations(target, target.animations);
  8352. }
  8353. // Children animations
  8354. if (target.getAnimatables) {
  8355. var animatables = target.getAnimatables();
  8356. for (var index = 0; index < animatables.length; index++) {
  8357. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  8358. }
  8359. }
  8360. return animatable;
  8361. };
  8362. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  8363. if (speedRatio === undefined) {
  8364. speedRatio = 1.0;
  8365. }
  8366. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  8367. return animatable;
  8368. };
  8369. Scene.prototype.getAnimatableByTarget = function (target) {
  8370. for (var index = 0; index < this._activeAnimatables.length; index++) {
  8371. if (this._activeAnimatables[index].target === target) {
  8372. return this._activeAnimatables[index];
  8373. }
  8374. }
  8375. return null;
  8376. };
  8377. /**
  8378. * Will stop the animation of the given target
  8379. * @param target - the target
  8380. * @see beginAnimation
  8381. */
  8382. Scene.prototype.stopAnimation = function (target) {
  8383. var animatable = this.getAnimatableByTarget(target);
  8384. if (animatable) {
  8385. animatable.stop();
  8386. }
  8387. };
  8388. Scene.prototype._animate = function () {
  8389. if (!this.animationsEnabled) {
  8390. return;
  8391. }
  8392. if (!this._animationStartDate) {
  8393. this._animationStartDate = BABYLON.Tools.Now;
  8394. }
  8395. // Getting time
  8396. var now = BABYLON.Tools.Now;
  8397. var delay = now - this._animationStartDate;
  8398. for (var index = 0; index < this._activeAnimatables.length; index++) {
  8399. if (!this._activeAnimatables[index]._animate(delay)) {
  8400. this._activeAnimatables.splice(index, 1);
  8401. index--;
  8402. }
  8403. }
  8404. };
  8405. // Matrix
  8406. Scene.prototype.getViewMatrix = function () {
  8407. return this._viewMatrix;
  8408. };
  8409. Scene.prototype.getProjectionMatrix = function () {
  8410. return this._projectionMatrix;
  8411. };
  8412. Scene.prototype.getTransformMatrix = function () {
  8413. return this._transformMatrix;
  8414. };
  8415. Scene.prototype.setTransformMatrix = function (view, projection) {
  8416. this._viewMatrix = view;
  8417. this._projectionMatrix = projection;
  8418. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  8419. };
  8420. // Methods
  8421. /**
  8422. * sets the active camera of the scene using its ID
  8423. * @param {string} id - the camera's ID
  8424. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  8425. * @see activeCamera
  8426. */
  8427. Scene.prototype.setActiveCameraByID = function (id) {
  8428. var camera = this.getCameraByID(id);
  8429. if (camera) {
  8430. this.activeCamera = camera;
  8431. return camera;
  8432. }
  8433. return null;
  8434. };
  8435. /**
  8436. * sets the active camera of the scene using its name
  8437. * @param {string} name - the camera's name
  8438. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  8439. * @see activeCamera
  8440. */
  8441. Scene.prototype.setActiveCameraByName = function (name) {
  8442. var camera = this.getCameraByName(name);
  8443. if (camera) {
  8444. this.activeCamera = camera;
  8445. return camera;
  8446. }
  8447. return null;
  8448. };
  8449. /**
  8450. * get a material using its id
  8451. * @param {string} the material's ID
  8452. * @return {BABYLON.Material|null} the material or null if none found.
  8453. */
  8454. Scene.prototype.getMaterialByID = function (id) {
  8455. for (var index = 0; index < this.materials.length; index++) {
  8456. if (this.materials[index].id === id) {
  8457. return this.materials[index];
  8458. }
  8459. }
  8460. return null;
  8461. };
  8462. /**
  8463. * get a material using its name
  8464. * @param {string} the material's name
  8465. * @return {BABYLON.Material|null} the material or null if none found.
  8466. */
  8467. Scene.prototype.getMaterialByName = function (name) {
  8468. for (var index = 0; index < this.materials.length; index++) {
  8469. if (this.materials[index].name === name) {
  8470. return this.materials[index];
  8471. }
  8472. }
  8473. return null;
  8474. };
  8475. Scene.prototype.getCameraByID = function (id) {
  8476. for (var index = 0; index < this.cameras.length; index++) {
  8477. if (this.cameras[index].id === id) {
  8478. return this.cameras[index];
  8479. }
  8480. }
  8481. return null;
  8482. };
  8483. /**
  8484. * get a camera using its name
  8485. * @param {string} the camera's name
  8486. * @return {BABYLON.Camera|null} the camera or null if none found.
  8487. */
  8488. Scene.prototype.getCameraByName = function (name) {
  8489. for (var index = 0; index < this.cameras.length; index++) {
  8490. if (this.cameras[index].name === name) {
  8491. return this.cameras[index];
  8492. }
  8493. }
  8494. return null;
  8495. };
  8496. /**
  8497. * get a light node using its name
  8498. * @param {string} the light's name
  8499. * @return {BABYLON.Light|null} the light or null if none found.
  8500. */
  8501. Scene.prototype.getLightByName = function (name) {
  8502. for (var index = 0; index < this.lights.length; index++) {
  8503. if (this.lights[index].name === name) {
  8504. return this.lights[index];
  8505. }
  8506. }
  8507. return null;
  8508. };
  8509. /**
  8510. * get a light node using its ID
  8511. * @param {string} the light's id
  8512. * @return {BABYLON.Light|null} the light or null if none found.
  8513. */
  8514. Scene.prototype.getLightByID = function (id) {
  8515. for (var index = 0; index < this.lights.length; index++) {
  8516. if (this.lights[index].id === id) {
  8517. return this.lights[index];
  8518. }
  8519. }
  8520. return null;
  8521. };
  8522. /**
  8523. * get a geometry using its ID
  8524. * @param {string} the geometry's id
  8525. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  8526. */
  8527. Scene.prototype.getGeometryByID = function (id) {
  8528. for (var index = 0; index < this._geometries.length; index++) {
  8529. if (this._geometries[index].id === id) {
  8530. return this._geometries[index];
  8531. }
  8532. }
  8533. return null;
  8534. };
  8535. /**
  8536. * add a new geometry to this scene.
  8537. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  8538. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  8539. * @return {boolean} was the geometry added or not
  8540. */
  8541. Scene.prototype.pushGeometry = function (geometry, force) {
  8542. if (!force && this.getGeometryByID(geometry.id)) {
  8543. return false;
  8544. }
  8545. this._geometries.push(geometry);
  8546. return true;
  8547. };
  8548. Scene.prototype.getGeometries = function () {
  8549. return this._geometries;
  8550. };
  8551. /**
  8552. * Get a the first added mesh found of a given ID
  8553. * @param {string} id - the id to search for
  8554. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  8555. */
  8556. Scene.prototype.getMeshByID = function (id) {
  8557. for (var index = 0; index < this.meshes.length; index++) {
  8558. if (this.meshes[index].id === id) {
  8559. return this.meshes[index];
  8560. }
  8561. }
  8562. return null;
  8563. };
  8564. /**
  8565. * Get a the last added mesh found of a given ID
  8566. * @param {string} id - the id to search for
  8567. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  8568. */
  8569. Scene.prototype.getLastMeshByID = function (id) {
  8570. for (var index = this.meshes.length - 1; index >= 0; index--) {
  8571. if (this.meshes[index].id === id) {
  8572. return this.meshes[index];
  8573. }
  8574. }
  8575. return null;
  8576. };
  8577. /**
  8578. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  8579. * @param {string} id - the id to search for
  8580. * @return {BABYLON.Node|null} the node found or null if not found at all.
  8581. */
  8582. Scene.prototype.getLastEntryByID = function (id) {
  8583. for (var index = this.meshes.length - 1; index >= 0; index--) {
  8584. if (this.meshes[index].id === id) {
  8585. return this.meshes[index];
  8586. }
  8587. }
  8588. for (index = this.cameras.length - 1; index >= 0; index--) {
  8589. if (this.cameras[index].id === id) {
  8590. return this.cameras[index];
  8591. }
  8592. }
  8593. for (index = this.lights.length - 1; index >= 0; index--) {
  8594. if (this.lights[index].id === id) {
  8595. return this.lights[index];
  8596. }
  8597. }
  8598. return null;
  8599. };
  8600. Scene.prototype.getNodeByName = function (name) {
  8601. var mesh = this.getMeshByName(name);
  8602. if (mesh) {
  8603. return mesh;
  8604. }
  8605. var light = this.getLightByName(name);
  8606. if (light) {
  8607. return light;
  8608. }
  8609. return this.getCameraByName(name);
  8610. };
  8611. Scene.prototype.getMeshByName = function (name) {
  8612. for (var index = 0; index < this.meshes.length; index++) {
  8613. if (this.meshes[index].name === name) {
  8614. return this.meshes[index];
  8615. }
  8616. }
  8617. return null;
  8618. };
  8619. Scene.prototype.getSoundByName = function (name) {
  8620. for (var index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  8621. if (this.mainSoundTrack.soundCollection[index].name === name) {
  8622. return this.mainSoundTrack.soundCollection[index];
  8623. }
  8624. }
  8625. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  8626. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  8627. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  8628. return this.soundTracks[sdIndex].soundCollection[index];
  8629. }
  8630. }
  8631. }
  8632. return null;
  8633. };
  8634. Scene.prototype.getLastSkeletonByID = function (id) {
  8635. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  8636. if (this.skeletons[index].id === id) {
  8637. return this.skeletons[index];
  8638. }
  8639. }
  8640. return null;
  8641. };
  8642. Scene.prototype.getSkeletonById = function (id) {
  8643. for (var index = 0; index < this.skeletons.length; index++) {
  8644. if (this.skeletons[index].id === id) {
  8645. return this.skeletons[index];
  8646. }
  8647. }
  8648. return null;
  8649. };
  8650. Scene.prototype.getSkeletonByName = function (name) {
  8651. for (var index = 0; index < this.skeletons.length; index++) {
  8652. if (this.skeletons[index].name === name) {
  8653. return this.skeletons[index];
  8654. }
  8655. }
  8656. return null;
  8657. };
  8658. Scene.prototype.isActiveMesh = function (mesh) {
  8659. return (this._activeMeshes.indexOf(mesh) !== -1);
  8660. };
  8661. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  8662. if (mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  8663. var material = subMesh.getMaterial();
  8664. if (mesh.showSubMeshesBoundingBox) {
  8665. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  8666. }
  8667. if (material) {
  8668. // Render targets
  8669. if (material.getRenderTargetTextures) {
  8670. if (this._processedMaterials.indexOf(material) === -1) {
  8671. this._processedMaterials.push(material);
  8672. this._renderTargets.concat(material.getRenderTargetTextures());
  8673. }
  8674. }
  8675. // Dispatch
  8676. this._activeVertices += subMesh.indexCount;
  8677. this._renderingManager.dispatch(subMesh);
  8678. }
  8679. }
  8680. };
  8681. Scene.prototype._evaluateActiveMeshes = function () {
  8682. this.activeCamera._activeMeshes.reset();
  8683. this._activeMeshes.reset();
  8684. this._renderingManager.reset();
  8685. this._processedMaterials.reset();
  8686. this._activeParticleSystems.reset();
  8687. this._activeSkeletons.reset();
  8688. this._boundingBoxRenderer.reset();
  8689. if (!this._frustumPlanes) {
  8690. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  8691. }
  8692. else {
  8693. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  8694. }
  8695. // Meshes
  8696. var meshes;
  8697. var len;
  8698. if (this._selectionOctree) {
  8699. var selection = this._selectionOctree.select(this._frustumPlanes);
  8700. meshes = selection.data;
  8701. len = selection.length;
  8702. }
  8703. else {
  8704. len = this.meshes.length;
  8705. meshes = this.meshes;
  8706. }
  8707. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  8708. var mesh = meshes[meshIndex];
  8709. if (mesh.isBlocked) {
  8710. continue;
  8711. }
  8712. this._totalVertices += mesh.getTotalVertices();
  8713. if (!mesh.isReady()) {
  8714. continue;
  8715. }
  8716. mesh.computeWorldMatrix();
  8717. // Intersections
  8718. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  8719. this._meshesForIntersections.pushNoDuplicate(mesh);
  8720. }
  8721. // Switch to current LOD
  8722. var meshLOD = mesh.getLOD(this.activeCamera);
  8723. if (!meshLOD) {
  8724. continue;
  8725. }
  8726. mesh._preActivate();
  8727. if (mesh.isEnabled() && mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  8728. this._activeMeshes.push(mesh);
  8729. this.activeCamera._activeMeshes.push(mesh);
  8730. mesh._activate(this._renderId);
  8731. this._activeMesh(meshLOD);
  8732. }
  8733. }
  8734. // Particle systems
  8735. var beforeParticlesDate = BABYLON.Tools.Now;
  8736. if (this.particlesEnabled) {
  8737. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  8738. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  8739. var particleSystem = this.particleSystems[particleIndex];
  8740. if (!particleSystem.isStarted()) {
  8741. continue;
  8742. }
  8743. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  8744. this._activeParticleSystems.push(particleSystem);
  8745. particleSystem.animate();
  8746. }
  8747. }
  8748. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  8749. }
  8750. this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  8751. };
  8752. Scene.prototype._activeMesh = function (mesh) {
  8753. if (mesh.skeleton && this.skeletonsEnabled) {
  8754. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  8755. }
  8756. if (mesh.showBoundingBox || this.forceShowBoundingBoxes) {
  8757. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  8758. }
  8759. if (mesh && mesh.subMeshes) {
  8760. // Submeshes Octrees
  8761. var len;
  8762. var subMeshes;
  8763. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  8764. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  8765. len = intersections.length;
  8766. subMeshes = intersections.data;
  8767. }
  8768. else {
  8769. subMeshes = mesh.subMeshes;
  8770. len = subMeshes.length;
  8771. }
  8772. for (var subIndex = 0; subIndex < len; subIndex++) {
  8773. var subMesh = subMeshes[subIndex];
  8774. this._evaluateSubMesh(subMesh, mesh);
  8775. }
  8776. }
  8777. };
  8778. Scene.prototype.updateTransformMatrix = function (force) {
  8779. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  8780. };
  8781. Scene.prototype._renderForCamera = function (camera) {
  8782. var engine = this._engine;
  8783. this.activeCamera = camera;
  8784. if (!this.activeCamera)
  8785. throw new Error("Active camera not set");
  8786. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  8787. // Viewport
  8788. engine.setViewport(this.activeCamera.viewport);
  8789. // Camera
  8790. this._renderId++;
  8791. this.updateTransformMatrix();
  8792. if (this.beforeCameraRender) {
  8793. this.beforeCameraRender(this.activeCamera);
  8794. }
  8795. // Meshes
  8796. var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
  8797. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  8798. this._evaluateActiveMeshes();
  8799. this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
  8800. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  8801. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  8802. var skeleton = this._activeSkeletons.data[skeletonIndex];
  8803. skeleton.prepare();
  8804. }
  8805. // Render targets
  8806. var beforeRenderTargetDate = BABYLON.Tools.Now;
  8807. if (this.renderTargetsEnabled) {
  8808. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  8809. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  8810. var renderTarget = this._renderTargets.data[renderIndex];
  8811. if (renderTarget._shouldRender()) {
  8812. this._renderId++;
  8813. renderTarget.render(false, this.dumpNextRenderTargets);
  8814. }
  8815. }
  8816. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  8817. this._renderId++;
  8818. }
  8819. if (this._renderTargets.length > 0) {
  8820. engine.restoreDefaultFramebuffer();
  8821. }
  8822. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  8823. // Prepare Frame
  8824. this.postProcessManager._prepareFrame();
  8825. var beforeRenderDate = BABYLON.Tools.Now;
  8826. // Backgrounds
  8827. if (this.layers.length) {
  8828. engine.setDepthBuffer(false);
  8829. var layerIndex;
  8830. var layer;
  8831. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  8832. layer = this.layers[layerIndex];
  8833. if (layer.isBackground) {
  8834. layer.render();
  8835. }
  8836. }
  8837. engine.setDepthBuffer(true);
  8838. }
  8839. // Render
  8840. BABYLON.Tools.StartPerformanceCounter("Main render");
  8841. this._renderingManager.render(null, null, true, true);
  8842. BABYLON.Tools.EndPerformanceCounter("Main render");
  8843. // Bounding boxes
  8844. this._boundingBoxRenderer.render();
  8845. // Lens flares
  8846. if (this.lensFlaresEnabled) {
  8847. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  8848. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  8849. this.lensFlareSystems[lensFlareSystemIndex].render();
  8850. }
  8851. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  8852. }
  8853. // Foregrounds
  8854. if (this.layers.length) {
  8855. engine.setDepthBuffer(false);
  8856. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  8857. layer = this.layers[layerIndex];
  8858. if (!layer.isBackground) {
  8859. layer.render();
  8860. }
  8861. }
  8862. engine.setDepthBuffer(true);
  8863. }
  8864. this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
  8865. // Finalize frame
  8866. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  8867. // Update camera
  8868. this.activeCamera._updateFromScene();
  8869. // Reset some special arrays
  8870. this._renderTargets.reset();
  8871. if (this.afterCameraRender) {
  8872. this.afterCameraRender(this.activeCamera);
  8873. }
  8874. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  8875. };
  8876. Scene.prototype._processSubCameras = function (camera) {
  8877. if (camera.subCameras.length === 0) {
  8878. this._renderForCamera(camera);
  8879. return;
  8880. }
  8881. for (var index = 0; index < camera.subCameras.length; index++) {
  8882. this._renderForCamera(camera.subCameras[index]);
  8883. }
  8884. this.activeCamera = camera;
  8885. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  8886. // Update camera
  8887. this.activeCamera._updateFromScene();
  8888. };
  8889. Scene.prototype._checkIntersections = function () {
  8890. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  8891. var sourceMesh = this._meshesForIntersections.data[index];
  8892. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  8893. var action = sourceMesh.actionManager.actions[actionIndex];
  8894. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  8895. var parameters = action.getTriggerParameter();
  8896. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  8897. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  8898. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  8899. if (areIntersecting && currentIntersectionInProgress === -1) {
  8900. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  8901. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh));
  8902. sourceMesh._intersectionsInProgress.push(otherMesh);
  8903. }
  8904. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  8905. sourceMesh._intersectionsInProgress.push(otherMesh);
  8906. }
  8907. }
  8908. else if (!areIntersecting && currentIntersectionInProgress > -1 && action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  8909. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh));
  8910. var indexOfOther = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  8911. if (indexOfOther > -1) {
  8912. sourceMesh._intersectionsInProgress.splice(indexOfOther, 1);
  8913. }
  8914. }
  8915. }
  8916. }
  8917. }
  8918. };
  8919. Scene.prototype.render = function () {
  8920. var startDate = BABYLON.Tools.Now;
  8921. this._particlesDuration = 0;
  8922. this._spritesDuration = 0;
  8923. this._activeParticles = 0;
  8924. this._renderDuration = 0;
  8925. this._renderTargetsDuration = 0;
  8926. this._evaluateActiveMeshesDuration = 0;
  8927. this._totalVertices = 0;
  8928. this._activeVertices = 0;
  8929. this._activeBones = 0;
  8930. this.getEngine().resetDrawCalls();
  8931. this._meshesForIntersections.reset();
  8932. this.resetCachedMaterial();
  8933. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  8934. // Actions
  8935. if (this.actionManager) {
  8936. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  8937. }
  8938. //Simplification Queue
  8939. if (!this.simplificationQueue.running) {
  8940. this.simplificationQueue.executeNext();
  8941. }
  8942. // Before render
  8943. if (this.beforeRender) {
  8944. this.beforeRender();
  8945. }
  8946. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  8947. this._onBeforeRenderCallbacks[callbackIndex]();
  8948. }
  8949. // Animations
  8950. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  8951. this._animationRatio = deltaTime * (60.0 / 1000.0);
  8952. this._animate();
  8953. // Physics
  8954. if (this._physicsEngine) {
  8955. BABYLON.Tools.StartPerformanceCounter("Physics");
  8956. this._physicsEngine._runOneStep(deltaTime / 1000.0);
  8957. BABYLON.Tools.EndPerformanceCounter("Physics");
  8958. }
  8959. // Customs render targets
  8960. var beforeRenderTargetDate = BABYLON.Tools.Now;
  8961. var engine = this.getEngine();
  8962. var currentActiveCamera = this.activeCamera;
  8963. if (this.renderTargetsEnabled) {
  8964. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  8965. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  8966. var renderTarget = this.customRenderTargets[customIndex];
  8967. if (renderTarget._shouldRender()) {
  8968. this._renderId++;
  8969. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  8970. if (!this.activeCamera)
  8971. throw new Error("Active camera not set");
  8972. // Viewport
  8973. engine.setViewport(this.activeCamera.viewport);
  8974. // Camera
  8975. this.updateTransformMatrix();
  8976. renderTarget.render(false, this.dumpNextRenderTargets);
  8977. }
  8978. }
  8979. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  8980. this._renderId++;
  8981. }
  8982. if (this.customRenderTargets.length > 0) {
  8983. engine.restoreDefaultFramebuffer();
  8984. }
  8985. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  8986. this.activeCamera = currentActiveCamera;
  8987. // Procedural textures
  8988. if (this.proceduralTexturesEnabled) {
  8989. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  8990. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  8991. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  8992. if (proceduralTexture._shouldRender()) {
  8993. proceduralTexture.render();
  8994. }
  8995. }
  8996. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  8997. }
  8998. // Clear
  8999. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  9000. // Shadows
  9001. if (this.shadowsEnabled) {
  9002. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  9003. var light = this.lights[lightIndex];
  9004. var shadowGenerator = light.getShadowGenerator();
  9005. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  9006. this._renderTargets.push(shadowGenerator.getShadowMap());
  9007. }
  9008. }
  9009. }
  9010. // Depth renderer
  9011. if (this._depthRenderer) {
  9012. this._renderTargets.push(this._depthRenderer.getDepthMap());
  9013. }
  9014. // RenderPipeline
  9015. this.postProcessRenderPipelineManager.update();
  9016. // Multi-cameras?
  9017. if (this.activeCameras.length > 0) {
  9018. var currentRenderId = this._renderId;
  9019. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  9020. this._renderId = currentRenderId;
  9021. this._processSubCameras(this.activeCameras[cameraIndex]);
  9022. }
  9023. }
  9024. else {
  9025. if (!this.activeCamera) {
  9026. throw new Error("No camera defined");
  9027. }
  9028. this._processSubCameras(this.activeCamera);
  9029. }
  9030. // Intersection checks
  9031. this._checkIntersections();
  9032. // Update the audio listener attached to the camera
  9033. this._updateAudioParameters();
  9034. // After render
  9035. if (this.afterRender) {
  9036. this.afterRender();
  9037. }
  9038. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  9039. this._onAfterRenderCallbacks[callbackIndex]();
  9040. }
  9041. for (var index = 0; index < this._toBeDisposed.length; index++) {
  9042. this._toBeDisposed.data[index].dispose();
  9043. this._toBeDisposed[index] = null;
  9044. }
  9045. this._toBeDisposed.reset();
  9046. if (this.dumpNextRenderTargets) {
  9047. this.dumpNextRenderTargets = false;
  9048. }
  9049. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  9050. this._lastFrameDuration = BABYLON.Tools.Now - startDate;
  9051. };
  9052. Scene.prototype._updateAudioParameters = function () {
  9053. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 0)) {
  9054. return;
  9055. }
  9056. var listeningCamera;
  9057. var audioEngine = BABYLON.Engine.audioEngine;
  9058. if (this.activeCameras.length > 0) {
  9059. listeningCamera = this.activeCameras[0];
  9060. }
  9061. else {
  9062. listeningCamera = this.activeCamera;
  9063. }
  9064. if (listeningCamera && audioEngine.canUseWebAudio) {
  9065. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  9066. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  9067. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  9068. cameraDirection.normalize();
  9069. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  9070. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  9071. var sound = this.mainSoundTrack.soundCollection[i];
  9072. if (sound.useCustomAttenuation) {
  9073. sound.updateDistanceFromListener();
  9074. }
  9075. }
  9076. for (i = 0; i < this.soundTracks.length; i++) {
  9077. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  9078. sound = this.soundTracks[i].soundCollection[j];
  9079. if (sound.useCustomAttenuation) {
  9080. sound.updateDistanceFromListener();
  9081. }
  9082. }
  9083. }
  9084. }
  9085. };
  9086. Object.defineProperty(Scene.prototype, "audioEnabled", {
  9087. // Audio
  9088. get: function () {
  9089. return this._audioEnabled;
  9090. },
  9091. set: function (value) {
  9092. this._audioEnabled = value;
  9093. if (this._audioEnabled) {
  9094. this._enableAudio();
  9095. }
  9096. else {
  9097. this._disableAudio();
  9098. }
  9099. },
  9100. enumerable: true,
  9101. configurable: true
  9102. });
  9103. Scene.prototype._disableAudio = function () {
  9104. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  9105. this.mainSoundTrack.soundCollection[i].pause();
  9106. }
  9107. for (i = 0; i < this.soundTracks.length; i++) {
  9108. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  9109. this.soundTracks[i].soundCollection[j].pause();
  9110. }
  9111. }
  9112. };
  9113. Scene.prototype._enableAudio = function () {
  9114. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  9115. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  9116. this.mainSoundTrack.soundCollection[i].play();
  9117. }
  9118. }
  9119. for (i = 0; i < this.soundTracks.length; i++) {
  9120. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  9121. if (this.soundTracks[i].soundCollection[j].isPaused) {
  9122. this.soundTracks[i].soundCollection[j].play();
  9123. }
  9124. }
  9125. }
  9126. };
  9127. Object.defineProperty(Scene.prototype, "headphone", {
  9128. get: function () {
  9129. return this._headphone;
  9130. },
  9131. set: function (value) {
  9132. this._headphone = value;
  9133. if (this._headphone) {
  9134. this._switchAudioModeForHeadphones();
  9135. }
  9136. else {
  9137. this._switchAudioModeForNormalSpeakers();
  9138. }
  9139. },
  9140. enumerable: true,
  9141. configurable: true
  9142. });
  9143. Scene.prototype._switchAudioModeForHeadphones = function () {
  9144. this.mainSoundTrack.switchPanningModelToHRTF();
  9145. for (var i = 0; i < this.soundTracks.length; i++) {
  9146. this.soundTracks[i].switchPanningModelToHRTF();
  9147. }
  9148. };
  9149. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  9150. this.mainSoundTrack.switchPanningModelToEqualPower();
  9151. for (var i = 0; i < this.soundTracks.length; i++) {
  9152. this.soundTracks[i].switchPanningModelToEqualPower();
  9153. }
  9154. };
  9155. Scene.prototype.enableDepthRenderer = function () {
  9156. if (this._depthRenderer) {
  9157. return this._depthRenderer;
  9158. }
  9159. this._depthRenderer = new BABYLON.DepthRenderer(this);
  9160. return this._depthRenderer;
  9161. };
  9162. Scene.prototype.disableDepthRenderer = function () {
  9163. if (!this._depthRenderer) {
  9164. return;
  9165. }
  9166. this._depthRenderer.dispose();
  9167. this._depthRenderer = null;
  9168. };
  9169. Scene.prototype.dispose = function () {
  9170. this.beforeRender = null;
  9171. this.afterRender = null;
  9172. this.skeletons = [];
  9173. this._boundingBoxRenderer.dispose();
  9174. if (this._depthRenderer) {
  9175. this._depthRenderer.dispose();
  9176. }
  9177. // Debug layer
  9178. this.debugLayer.hide();
  9179. // Events
  9180. if (this.onDispose) {
  9181. this.onDispose();
  9182. }
  9183. this._onBeforeRenderCallbacks = [];
  9184. this._onAfterRenderCallbacks = [];
  9185. this.detachControl();
  9186. // Release sounds & sounds tracks
  9187. this.disposeSounds();
  9188. // Detach cameras
  9189. var canvas = this._engine.getRenderingCanvas();
  9190. var index;
  9191. for (index = 0; index < this.cameras.length; index++) {
  9192. this.cameras[index].detachControl(canvas);
  9193. }
  9194. while (this.lights.length) {
  9195. this.lights[0].dispose();
  9196. }
  9197. while (this.meshes.length) {
  9198. this.meshes[0].dispose(true);
  9199. }
  9200. while (this.cameras.length) {
  9201. this.cameras[0].dispose();
  9202. }
  9203. while (this.materials.length) {
  9204. this.materials[0].dispose();
  9205. }
  9206. while (this.particleSystems.length) {
  9207. this.particleSystems[0].dispose();
  9208. }
  9209. while (this.spriteManagers.length) {
  9210. this.spriteManagers[0].dispose();
  9211. }
  9212. while (this.layers.length) {
  9213. this.layers[0].dispose();
  9214. }
  9215. while (this.textures.length) {
  9216. this.textures[0].dispose();
  9217. }
  9218. // Post-processes
  9219. this.postProcessManager.dispose();
  9220. // Physics
  9221. if (this._physicsEngine) {
  9222. this.disablePhysicsEngine();
  9223. }
  9224. // Remove from engine
  9225. index = this._engine.scenes.indexOf(this);
  9226. if (index > -1) {
  9227. this._engine.scenes.splice(index, 1);
  9228. }
  9229. this._engine.wipeCaches();
  9230. };
  9231. // Release sounds & sounds tracks
  9232. Scene.prototype.disposeSounds = function () {
  9233. this.mainSoundTrack.dispose();
  9234. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  9235. this.soundTracks[scIndex].dispose();
  9236. }
  9237. };
  9238. // Collisions
  9239. Scene.prototype._getNewPosition = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  9240. if (excludedMesh === void 0) { excludedMesh = null; }
  9241. position.divideToRef(collider.radius, this._scaledPosition);
  9242. velocity.divideToRef(collider.radius, this._scaledVelocity);
  9243. collider.retry = 0;
  9244. collider.initialVelocity = this._scaledVelocity;
  9245. collider.initialPosition = this._scaledPosition;
  9246. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, finalPosition, excludedMesh);
  9247. finalPosition.multiplyInPlace(collider.radius);
  9248. };
  9249. Scene.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  9250. if (excludedMesh === void 0) { excludedMesh = null; }
  9251. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  9252. if (collider.retry >= maximumRetry) {
  9253. finalPosition.copyFrom(position);
  9254. return;
  9255. }
  9256. collider._initialize(position, velocity, closeDistance);
  9257. for (var index = 0; index < this.meshes.length; index++) {
  9258. var mesh = this.meshes[index];
  9259. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  9260. mesh._checkCollision(collider);
  9261. }
  9262. }
  9263. if (!collider.collisionFound) {
  9264. position.addToRef(velocity, finalPosition);
  9265. return;
  9266. }
  9267. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  9268. collider._getResponse(position, velocity);
  9269. }
  9270. if (velocity.length() <= closeDistance) {
  9271. finalPosition.copyFrom(position);
  9272. return;
  9273. }
  9274. collider.retry++;
  9275. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  9276. };
  9277. // Octrees
  9278. Scene.prototype.getWorldExtends = function () {
  9279. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9280. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  9281. for (var index = 0; index < this.meshes.length; index++) {
  9282. var mesh = this.meshes[index];
  9283. mesh.computeWorldMatrix(true);
  9284. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  9285. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  9286. BABYLON.Tools.CheckExtends(minBox, min, max);
  9287. BABYLON.Tools.CheckExtends(maxBox, min, max);
  9288. }
  9289. return {
  9290. min: min,
  9291. max: max
  9292. };
  9293. };
  9294. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  9295. if (maxCapacity === void 0) { maxCapacity = 64; }
  9296. if (maxDepth === void 0) { maxDepth = 2; }
  9297. if (!this._selectionOctree) {
  9298. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  9299. }
  9300. var worldExtends = this.getWorldExtends();
  9301. // Update octree
  9302. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  9303. return this._selectionOctree;
  9304. };
  9305. // Picking
  9306. Scene.prototype.createPickingRay = function (x, y, world, camera) {
  9307. var engine = this._engine;
  9308. if (!camera) {
  9309. if (!this.activeCamera)
  9310. throw new Error("Active camera not set");
  9311. camera = this.activeCamera;
  9312. }
  9313. var cameraViewport = camera.viewport;
  9314. var viewport = cameraViewport.toGlobal(engine);
  9315. // Moving coordinates to local viewport world
  9316. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  9317. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  9318. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  9319. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  9320. };
  9321. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  9322. var pickingInfo = null;
  9323. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  9324. var mesh = this.meshes[meshIndex];
  9325. if (predicate) {
  9326. if (!predicate(mesh)) {
  9327. continue;
  9328. }
  9329. }
  9330. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  9331. continue;
  9332. }
  9333. var world = mesh.getWorldMatrix();
  9334. var ray = rayFunction(world);
  9335. var result = mesh.intersects(ray, fastCheck);
  9336. if (!result || !result.hit)
  9337. continue;
  9338. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  9339. continue;
  9340. pickingInfo = result;
  9341. if (fastCheck) {
  9342. break;
  9343. }
  9344. }
  9345. return pickingInfo || new BABYLON.PickingInfo();
  9346. };
  9347. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  9348. var _this = this;
  9349. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  9350. /// <param name="x">X position on screen</param>
  9351. /// <param name="y">Y position on screen</param>
  9352. /// <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>
  9353. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  9354. /// <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>
  9355. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  9356. };
  9357. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  9358. var _this = this;
  9359. return this._internalPick(function (world) {
  9360. if (!_this._pickWithRayInverseMatrix) {
  9361. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  9362. }
  9363. world.invertToRef(_this._pickWithRayInverseMatrix);
  9364. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  9365. }, predicate, fastCheck);
  9366. };
  9367. Scene.prototype.setPointerOverMesh = function (mesh) {
  9368. if (this._pointerOverMesh === mesh) {
  9369. return;
  9370. }
  9371. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  9372. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  9373. }
  9374. this._pointerOverMesh = mesh;
  9375. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  9376. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  9377. }
  9378. };
  9379. Scene.prototype.getPointerOverMesh = function () {
  9380. return this._pointerOverMesh;
  9381. };
  9382. // Physics
  9383. Scene.prototype.getPhysicsEngine = function () {
  9384. return this._physicsEngine;
  9385. };
  9386. Scene.prototype.enablePhysics = function (gravity, plugin) {
  9387. if (this._physicsEngine) {
  9388. return true;
  9389. }
  9390. this._physicsEngine = new BABYLON.PhysicsEngine(plugin);
  9391. if (!this._physicsEngine.isSupported()) {
  9392. this._physicsEngine = null;
  9393. return false;
  9394. }
  9395. this._physicsEngine._initialize(gravity);
  9396. return true;
  9397. };
  9398. Scene.prototype.disablePhysicsEngine = function () {
  9399. if (!this._physicsEngine) {
  9400. return;
  9401. }
  9402. this._physicsEngine.dispose();
  9403. this._physicsEngine = undefined;
  9404. };
  9405. Scene.prototype.isPhysicsEnabled = function () {
  9406. return this._physicsEngine !== undefined;
  9407. };
  9408. Scene.prototype.setGravity = function (gravity) {
  9409. if (!this._physicsEngine) {
  9410. return;
  9411. }
  9412. this._physicsEngine._setGravity(gravity);
  9413. };
  9414. Scene.prototype.createCompoundImpostor = function (parts, options) {
  9415. if (parts.parts) {
  9416. options = parts;
  9417. parts = parts.parts;
  9418. }
  9419. if (!this._physicsEngine) {
  9420. return null;
  9421. }
  9422. for (var index = 0; index < parts.length; index++) {
  9423. var mesh = parts[index].mesh;
  9424. mesh._physicImpostor = parts[index].impostor;
  9425. mesh._physicsMass = options.mass / parts.length;
  9426. mesh._physicsFriction = options.friction;
  9427. mesh._physicRestitution = options.restitution;
  9428. }
  9429. return this._physicsEngine._registerMeshesAsCompound(parts, options);
  9430. };
  9431. Scene.prototype.deleteCompoundImpostor = function (compound) {
  9432. for (var index = 0; index < compound.parts.length; index++) {
  9433. var mesh = compound.parts[index].mesh;
  9434. mesh._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  9435. this._physicsEngine._unregisterMesh(mesh);
  9436. }
  9437. };
  9438. // Misc.
  9439. Scene.prototype.createDefaultCameraOrLight = function () {
  9440. // Light
  9441. if (this.lights.length === 0) {
  9442. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  9443. }
  9444. // Camera
  9445. if (!this.activeCamera) {
  9446. var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  9447. // Compute position
  9448. var worldExtends = this.getWorldExtends();
  9449. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  9450. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  9451. camera.setTarget(worldCenter);
  9452. this.activeCamera = camera;
  9453. }
  9454. };
  9455. // Tags
  9456. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  9457. if (tagsQuery === undefined) {
  9458. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  9459. return list;
  9460. }
  9461. var listByTags = [];
  9462. forEach = forEach || (function (item) {
  9463. return;
  9464. });
  9465. for (var i in list) {
  9466. var item = list[i];
  9467. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  9468. listByTags.push(item);
  9469. forEach(item);
  9470. }
  9471. }
  9472. return listByTags;
  9473. };
  9474. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  9475. return this._getByTags(this.meshes, tagsQuery, forEach);
  9476. };
  9477. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  9478. return this._getByTags(this.cameras, tagsQuery, forEach);
  9479. };
  9480. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  9481. return this._getByTags(this.lights, tagsQuery, forEach);
  9482. };
  9483. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  9484. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  9485. };
  9486. // Statics
  9487. Scene._FOGMODE_NONE = 0;
  9488. Scene._FOGMODE_EXP = 1;
  9489. Scene._FOGMODE_EXP2 = 2;
  9490. Scene._FOGMODE_LINEAR = 3;
  9491. Scene.MinDeltaTime = 1.0;
  9492. Scene.MaxDeltaTime = 1000.0;
  9493. return Scene;
  9494. })();
  9495. BABYLON.Scene = Scene;
  9496. })(BABYLON || (BABYLON = {}));
  9497. //# sourceMappingURL=babylon.scene.js.mapvar BABYLON;
  9498. (function (BABYLON) {
  9499. var VertexBuffer = (function () {
  9500. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride) {
  9501. if (engine instanceof BABYLON.Mesh) {
  9502. this._engine = engine.getScene().getEngine();
  9503. }
  9504. else {
  9505. this._engine = engine;
  9506. }
  9507. this._updatable = updatable;
  9508. this._data = data;
  9509. if (!postponeInternalCreation) {
  9510. this.create();
  9511. }
  9512. this._kind = kind;
  9513. if (stride) {
  9514. this._strideSize = stride;
  9515. return;
  9516. }
  9517. switch (kind) {
  9518. case VertexBuffer.PositionKind:
  9519. this._strideSize = 3;
  9520. break;
  9521. case VertexBuffer.NormalKind:
  9522. this._strideSize = 3;
  9523. break;
  9524. case VertexBuffer.UVKind:
  9525. this._strideSize = 2;
  9526. break;
  9527. case VertexBuffer.UV2Kind:
  9528. this._strideSize = 2;
  9529. break;
  9530. case VertexBuffer.ColorKind:
  9531. this._strideSize = 4;
  9532. break;
  9533. case VertexBuffer.MatricesIndicesKind:
  9534. this._strideSize = 4;
  9535. break;
  9536. case VertexBuffer.MatricesWeightsKind:
  9537. this._strideSize = 4;
  9538. break;
  9539. }
  9540. }
  9541. // Properties
  9542. VertexBuffer.prototype.isUpdatable = function () {
  9543. return this._updatable;
  9544. };
  9545. VertexBuffer.prototype.getData = function () {
  9546. return this._data;
  9547. };
  9548. VertexBuffer.prototype.getBuffer = function () {
  9549. return this._buffer;
  9550. };
  9551. VertexBuffer.prototype.getStrideSize = function () {
  9552. return this._strideSize;
  9553. };
  9554. // Methods
  9555. VertexBuffer.prototype.create = function (data) {
  9556. if (!data && this._buffer) {
  9557. return; // nothing to do
  9558. }
  9559. data = data || this._data;
  9560. if (!this._buffer) {
  9561. if (this._updatable) {
  9562. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  9563. }
  9564. else {
  9565. this._buffer = this._engine.createVertexBuffer(data);
  9566. }
  9567. }
  9568. if (this._updatable) {
  9569. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  9570. this._data = data;
  9571. }
  9572. };
  9573. VertexBuffer.prototype.update = function (data) {
  9574. this.create(data);
  9575. };
  9576. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  9577. if (!this._buffer) {
  9578. return;
  9579. }
  9580. if (this._updatable) {
  9581. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset);
  9582. this._data = null;
  9583. }
  9584. };
  9585. VertexBuffer.prototype.dispose = function () {
  9586. if (!this._buffer) {
  9587. return;
  9588. }
  9589. if (this._engine._releaseBuffer(this._buffer)) {
  9590. this._buffer = null;
  9591. }
  9592. };
  9593. Object.defineProperty(VertexBuffer, "PositionKind", {
  9594. get: function () {
  9595. return VertexBuffer._PositionKind;
  9596. },
  9597. enumerable: true,
  9598. configurable: true
  9599. });
  9600. Object.defineProperty(VertexBuffer, "NormalKind", {
  9601. get: function () {
  9602. return VertexBuffer._NormalKind;
  9603. },
  9604. enumerable: true,
  9605. configurable: true
  9606. });
  9607. Object.defineProperty(VertexBuffer, "UVKind", {
  9608. get: function () {
  9609. return VertexBuffer._UVKind;
  9610. },
  9611. enumerable: true,
  9612. configurable: true
  9613. });
  9614. Object.defineProperty(VertexBuffer, "UV2Kind", {
  9615. get: function () {
  9616. return VertexBuffer._UV2Kind;
  9617. },
  9618. enumerable: true,
  9619. configurable: true
  9620. });
  9621. Object.defineProperty(VertexBuffer, "ColorKind", {
  9622. get: function () {
  9623. return VertexBuffer._ColorKind;
  9624. },
  9625. enumerable: true,
  9626. configurable: true
  9627. });
  9628. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  9629. get: function () {
  9630. return VertexBuffer._MatricesIndicesKind;
  9631. },
  9632. enumerable: true,
  9633. configurable: true
  9634. });
  9635. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  9636. get: function () {
  9637. return VertexBuffer._MatricesWeightsKind;
  9638. },
  9639. enumerable: true,
  9640. configurable: true
  9641. });
  9642. // Enums
  9643. VertexBuffer._PositionKind = "position";
  9644. VertexBuffer._NormalKind = "normal";
  9645. VertexBuffer._UVKind = "uv";
  9646. VertexBuffer._UV2Kind = "uv2";
  9647. VertexBuffer._ColorKind = "color";
  9648. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  9649. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  9650. return VertexBuffer;
  9651. })();
  9652. BABYLON.VertexBuffer = VertexBuffer;
  9653. })(BABYLON || (BABYLON = {}));
  9654. //# sourceMappingURL=babylon.vertexBuffer.js.map
  9655. var BABYLON;
  9656. (function (BABYLON) {
  9657. var AbstractMesh = (function (_super) {
  9658. __extends(AbstractMesh, _super);
  9659. function AbstractMesh(name, scene) {
  9660. _super.call(this, name, scene);
  9661. // Properties
  9662. this.definedFacingForward = true; // orientation for POV movement & rotation
  9663. this.position = new BABYLON.Vector3(0, 0, 0);
  9664. this.rotation = new BABYLON.Vector3(0, 0, 0);
  9665. this.scaling = new BABYLON.Vector3(1, 1, 1);
  9666. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  9667. this.visibility = 1.0;
  9668. this.alphaIndex = Number.MAX_VALUE;
  9669. this.infiniteDistance = false;
  9670. this.isVisible = true;
  9671. this.isPickable = true;
  9672. this.showBoundingBox = false;
  9673. this.showSubMeshesBoundingBox = false;
  9674. this.onDispose = null;
  9675. this.checkCollisions = false;
  9676. this.isBlocker = false;
  9677. this.renderingGroupId = 0;
  9678. this.receiveShadows = false;
  9679. this.renderOutline = false;
  9680. this.outlineColor = BABYLON.Color3.Red();
  9681. this.outlineWidth = 0.02;
  9682. this.renderOverlay = false;
  9683. this.overlayColor = BABYLON.Color3.Red();
  9684. this.overlayAlpha = 0.5;
  9685. this.hasVertexAlpha = false;
  9686. this.useVertexColors = true;
  9687. this.applyFog = true;
  9688. this.useOctreeForRenderingSelection = true;
  9689. this.useOctreeForPicking = true;
  9690. this.useOctreeForCollisions = true;
  9691. this.layerMask = 0xFFFFFFFF;
  9692. // Physics
  9693. this._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  9694. // Collisions
  9695. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  9696. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  9697. this._collider = new BABYLON.Collider();
  9698. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  9699. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  9700. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  9701. // Cache
  9702. this._localScaling = BABYLON.Matrix.Zero();
  9703. this._localRotation = BABYLON.Matrix.Zero();
  9704. this._localTranslation = BABYLON.Matrix.Zero();
  9705. this._localBillboard = BABYLON.Matrix.Zero();
  9706. this._localPivotScaling = BABYLON.Matrix.Zero();
  9707. this._localPivotScalingRotation = BABYLON.Matrix.Zero();
  9708. this._localWorld = BABYLON.Matrix.Zero();
  9709. this._worldMatrix = BABYLON.Matrix.Zero();
  9710. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  9711. this._absolutePosition = BABYLON.Vector3.Zero();
  9712. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  9713. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  9714. this._isDirty = false;
  9715. this._pivotMatrix = BABYLON.Matrix.Identity();
  9716. this._isDisposed = false;
  9717. this._renderId = 0;
  9718. this._intersectionsInProgress = new Array();
  9719. this._onAfterWorldMatrixUpdate = new Array();
  9720. scene.meshes.push(this);
  9721. }
  9722. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  9723. get: function () {
  9724. return AbstractMesh._BILLBOARDMODE_NONE;
  9725. },
  9726. enumerable: true,
  9727. configurable: true
  9728. });
  9729. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  9730. get: function () {
  9731. return AbstractMesh._BILLBOARDMODE_X;
  9732. },
  9733. enumerable: true,
  9734. configurable: true
  9735. });
  9736. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  9737. get: function () {
  9738. return AbstractMesh._BILLBOARDMODE_Y;
  9739. },
  9740. enumerable: true,
  9741. configurable: true
  9742. });
  9743. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  9744. get: function () {
  9745. return AbstractMesh._BILLBOARDMODE_Z;
  9746. },
  9747. enumerable: true,
  9748. configurable: true
  9749. });
  9750. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  9751. get: function () {
  9752. return AbstractMesh._BILLBOARDMODE_ALL;
  9753. },
  9754. enumerable: true,
  9755. configurable: true
  9756. });
  9757. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  9758. // Methods
  9759. get: function () {
  9760. return false;
  9761. },
  9762. enumerable: true,
  9763. configurable: true
  9764. });
  9765. AbstractMesh.prototype.getLOD = function (camera) {
  9766. return this;
  9767. };
  9768. AbstractMesh.prototype.getTotalVertices = function () {
  9769. return 0;
  9770. };
  9771. AbstractMesh.prototype.getIndices = function () {
  9772. return null;
  9773. };
  9774. AbstractMesh.prototype.getVerticesData = function (kind) {
  9775. return null;
  9776. };
  9777. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  9778. return false;
  9779. };
  9780. AbstractMesh.prototype.getBoundingInfo = function () {
  9781. if (this._masterMesh) {
  9782. return this._masterMesh.getBoundingInfo();
  9783. }
  9784. if (!this._boundingInfo) {
  9785. this._updateBoundingInfo();
  9786. }
  9787. return this._boundingInfo;
  9788. };
  9789. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  9790. get: function () {
  9791. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  9792. },
  9793. enumerable: true,
  9794. configurable: true
  9795. });
  9796. AbstractMesh.prototype._preActivate = function () {
  9797. };
  9798. AbstractMesh.prototype._activate = function (renderId) {
  9799. this._renderId = renderId;
  9800. };
  9801. AbstractMesh.prototype.getWorldMatrix = function () {
  9802. if (this._masterMesh) {
  9803. return this._masterMesh.getWorldMatrix();
  9804. }
  9805. if (this._currentRenderId !== this.getScene().getRenderId()) {
  9806. this.computeWorldMatrix();
  9807. }
  9808. return this._worldMatrix;
  9809. };
  9810. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  9811. get: function () {
  9812. return this._worldMatrix;
  9813. },
  9814. enumerable: true,
  9815. configurable: true
  9816. });
  9817. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  9818. get: function () {
  9819. return this._absolutePosition;
  9820. },
  9821. enumerable: true,
  9822. configurable: true
  9823. });
  9824. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  9825. if (!this.rotationQuaternion) {
  9826. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  9827. this.rotation = BABYLON.Vector3.Zero();
  9828. }
  9829. if (!space || space == 0 /* LOCAL */) {
  9830. var rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  9831. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  9832. }
  9833. else {
  9834. if (this.parent) {
  9835. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  9836. invertParentWorldMatrix.invert();
  9837. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  9838. }
  9839. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  9840. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  9841. }
  9842. };
  9843. AbstractMesh.prototype.translate = function (axis, distance, space) {
  9844. var displacementVector = axis.scale(distance);
  9845. if (!space || space == 0 /* LOCAL */) {
  9846. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  9847. this.setPositionWithLocalVector(tempV3);
  9848. }
  9849. else {
  9850. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  9851. }
  9852. };
  9853. AbstractMesh.prototype.getAbsolutePosition = function () {
  9854. this.computeWorldMatrix();
  9855. return this._absolutePosition;
  9856. };
  9857. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  9858. if (!absolutePosition) {
  9859. return;
  9860. }
  9861. var absolutePositionX;
  9862. var absolutePositionY;
  9863. var absolutePositionZ;
  9864. if (absolutePosition.x === undefined) {
  9865. if (arguments.length < 3) {
  9866. return;
  9867. }
  9868. absolutePositionX = arguments[0];
  9869. absolutePositionY = arguments[1];
  9870. absolutePositionZ = arguments[2];
  9871. }
  9872. else {
  9873. absolutePositionX = absolutePosition.x;
  9874. absolutePositionY = absolutePosition.y;
  9875. absolutePositionZ = absolutePosition.z;
  9876. }
  9877. if (this.parent) {
  9878. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  9879. invertParentWorldMatrix.invert();
  9880. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  9881. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  9882. }
  9883. else {
  9884. this.position.x = absolutePositionX;
  9885. this.position.y = absolutePositionY;
  9886. this.position.z = absolutePositionZ;
  9887. }
  9888. };
  9889. // ================================== Point of View Movement =================================
  9890. /**
  9891. * Perform relative position change from the point of view of behind the front of the mesh.
  9892. * This is performed taking into account the meshes current rotation, so you do not have to care.
  9893. * Supports definition of mesh facing forward or backward.
  9894. * @param {number} amountRight
  9895. * @param {number} amountUp
  9896. * @param {number} amountForward
  9897. */
  9898. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  9899. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  9900. };
  9901. /**
  9902. * Calculate relative position change from the point of view of behind the front of the mesh.
  9903. * This is performed taking into account the meshes current rotation, so you do not have to care.
  9904. * Supports definition of mesh facing forward or backward.
  9905. * @param {number} amountRight
  9906. * @param {number} amountUp
  9907. * @param {number} amountForward
  9908. */
  9909. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  9910. var rotMatrix = new BABYLON.Matrix();
  9911. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  9912. rotQuaternion.toRotationMatrix(rotMatrix);
  9913. var translationDelta = BABYLON.Vector3.Zero();
  9914. var defForwardMult = this.definedFacingForward ? -1 : 1;
  9915. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  9916. return translationDelta;
  9917. };
  9918. // ================================== Point of View Rotation =================================
  9919. /**
  9920. * Perform relative rotation change from the point of view of behind the front of the mesh.
  9921. * Supports definition of mesh facing forward or backward.
  9922. * @param {number} flipBack
  9923. * @param {number} twirlClockwise
  9924. * @param {number} tiltRight
  9925. */
  9926. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  9927. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  9928. };
  9929. /**
  9930. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  9931. * Supports definition of mesh facing forward or backward.
  9932. * @param {number} flipBack
  9933. * @param {number} twirlClockwise
  9934. * @param {number} tiltRight
  9935. */
  9936. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  9937. var defForwardMult = this.definedFacingForward ? 1 : -1;
  9938. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  9939. };
  9940. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  9941. this._pivotMatrix = matrix;
  9942. this._cache.pivotMatrixUpdated = true;
  9943. };
  9944. AbstractMesh.prototype.getPivotMatrix = function () {
  9945. return this._pivotMatrix;
  9946. };
  9947. AbstractMesh.prototype._isSynchronized = function () {
  9948. if (this._isDirty) {
  9949. return false;
  9950. }
  9951. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  9952. return false;
  9953. if (this._cache.pivotMatrixUpdated) {
  9954. return false;
  9955. }
  9956. if (this.infiniteDistance) {
  9957. return false;
  9958. }
  9959. if (!this._cache.position.equals(this.position))
  9960. return false;
  9961. if (this.rotationQuaternion) {
  9962. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  9963. return false;
  9964. }
  9965. else {
  9966. if (!this._cache.rotation.equals(this.rotation))
  9967. return false;
  9968. }
  9969. if (!this._cache.scaling.equals(this.scaling))
  9970. return false;
  9971. return true;
  9972. };
  9973. AbstractMesh.prototype._initCache = function () {
  9974. _super.prototype._initCache.call(this);
  9975. this._cache.localMatrixUpdated = false;
  9976. this._cache.position = BABYLON.Vector3.Zero();
  9977. this._cache.scaling = BABYLON.Vector3.Zero();
  9978. this._cache.rotation = BABYLON.Vector3.Zero();
  9979. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  9980. };
  9981. AbstractMesh.prototype.markAsDirty = function (property) {
  9982. if (property === "rotation") {
  9983. this.rotationQuaternion = null;
  9984. }
  9985. this._currentRenderId = Number.MAX_VALUE;
  9986. this._isDirty = true;
  9987. };
  9988. AbstractMesh.prototype._updateBoundingInfo = function () {
  9989. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  9990. this._boundingInfo._update(this.worldMatrixFromCache);
  9991. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  9992. };
  9993. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  9994. if (!this.subMeshes) {
  9995. return;
  9996. }
  9997. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  9998. var subMesh = this.subMeshes[subIndex];
  9999. subMesh.updateBoundingInfo(matrix);
  10000. }
  10001. };
  10002. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  10003. if (!force && (this._currentRenderId == this.getScene().getRenderId() || this.isSynchronized(true))) {
  10004. return this._worldMatrix;
  10005. }
  10006. this._cache.position.copyFrom(this.position);
  10007. this._cache.scaling.copyFrom(this.scaling);
  10008. this._cache.pivotMatrixUpdated = false;
  10009. this._currentRenderId = this.getScene().getRenderId();
  10010. this._isDirty = false;
  10011. // Scaling
  10012. BABYLON.Matrix.ScalingToRef(this.scaling.x, this.scaling.y, this.scaling.z, this._localScaling);
  10013. // Rotation
  10014. if (this.rotationQuaternion) {
  10015. this.rotationQuaternion.toRotationMatrix(this._localRotation);
  10016. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  10017. }
  10018. else {
  10019. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._localRotation);
  10020. this._cache.rotation.copyFrom(this.rotation);
  10021. }
  10022. // Translation
  10023. if (this.infiniteDistance && !this.parent) {
  10024. var camera = this.getScene().activeCamera;
  10025. var cameraWorldMatrix = camera.getWorldMatrix();
  10026. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  10027. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, this._localTranslation);
  10028. }
  10029. else {
  10030. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._localTranslation);
  10031. }
  10032. // Composing transformations
  10033. this._pivotMatrix.multiplyToRef(this._localScaling, this._localPivotScaling);
  10034. this._localPivotScaling.multiplyToRef(this._localRotation, this._localPivotScalingRotation);
  10035. // Billboarding
  10036. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  10037. var localPosition = this.position.clone();
  10038. var zero = this.getScene().activeCamera.position.clone();
  10039. if (this.parent && this.parent.position) {
  10040. localPosition.addInPlace(this.parent.position);
  10041. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, this._localTranslation);
  10042. }
  10043. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) === AbstractMesh.BILLBOARDMODE_ALL) {
  10044. zero = this.getScene().activeCamera.position;
  10045. }
  10046. else {
  10047. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X)
  10048. zero.x = localPosition.x + BABYLON.Engine.Epsilon;
  10049. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y)
  10050. zero.y = localPosition.y + 0.001;
  10051. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z)
  10052. zero.z = localPosition.z + 0.001;
  10053. }
  10054. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), this._localBillboard);
  10055. this._localBillboard.m[12] = this._localBillboard.m[13] = this._localBillboard.m[14] = 0;
  10056. this._localBillboard.invert();
  10057. this._localPivotScalingRotation.multiplyToRef(this._localBillboard, this._localWorld);
  10058. this._rotateYByPI.multiplyToRef(this._localWorld, this._localPivotScalingRotation);
  10059. }
  10060. // Local world
  10061. this._localPivotScalingRotation.multiplyToRef(this._localTranslation, this._localWorld);
  10062. // Parent
  10063. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  10064. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  10065. }
  10066. else {
  10067. this._worldMatrix.copyFrom(this._localWorld);
  10068. }
  10069. // Bounding info
  10070. this._updateBoundingInfo();
  10071. // Absolute position
  10072. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  10073. for (var callbackIndex = 0; callbackIndex < this._onAfterWorldMatrixUpdate.length; callbackIndex++) {
  10074. this._onAfterWorldMatrixUpdate[callbackIndex](this);
  10075. }
  10076. return this._worldMatrix;
  10077. };
  10078. /**
  10079. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  10080. * @param func: callback function to add
  10081. */
  10082. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  10083. this._onAfterWorldMatrixUpdate.push(func);
  10084. };
  10085. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  10086. var index = this._onAfterWorldMatrixUpdate.indexOf(func);
  10087. if (index > -1) {
  10088. this._onAfterWorldMatrixUpdate.splice(index, 1);
  10089. }
  10090. };
  10091. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  10092. this.computeWorldMatrix();
  10093. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  10094. };
  10095. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  10096. this.computeWorldMatrix();
  10097. var invLocalWorldMatrix = this._localWorld.clone();
  10098. invLocalWorldMatrix.invert();
  10099. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  10100. };
  10101. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  10102. this.computeWorldMatrix();
  10103. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  10104. };
  10105. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  10106. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  10107. /// <param name="targetPoint" type="BABYLON.Vector3">The position (must be in same space as current mesh) to look at</param>
  10108. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  10109. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  10110. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  10111. /// <returns>Mesh oriented towards targetMesh</returns>
  10112. yawCor = yawCor || 0; // default to zero if undefined
  10113. pitchCor = pitchCor || 0;
  10114. rollCor = rollCor || 0;
  10115. var dv = targetPoint.subtract(this.position);
  10116. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  10117. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  10118. var pitch = Math.atan2(dv.y, len);
  10119. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  10120. };
  10121. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  10122. if (!this._boundingInfo.isInFrustum(frustumPlanes)) {
  10123. return false;
  10124. }
  10125. return true;
  10126. };
  10127. AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
  10128. if (!camera) {
  10129. camera = this.getScene().activeCamera;
  10130. }
  10131. var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
  10132. if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
  10133. return false;
  10134. }
  10135. return true;
  10136. };
  10137. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  10138. if (!this._boundingInfo || !mesh._boundingInfo) {
  10139. return false;
  10140. }
  10141. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  10142. };
  10143. AbstractMesh.prototype.intersectsPoint = function (point) {
  10144. if (!this._boundingInfo) {
  10145. return false;
  10146. }
  10147. return this._boundingInfo.intersectsPoint(point);
  10148. };
  10149. // Physics
  10150. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  10151. var physicsEngine = this.getScene().getPhysicsEngine();
  10152. if (!physicsEngine) {
  10153. return;
  10154. }
  10155. impostor = impostor || BABYLON.PhysicsEngine.NoImpostor;
  10156. if (impostor.impostor) {
  10157. // Old API
  10158. options = impostor;
  10159. impostor = impostor.impostor;
  10160. }
  10161. if (impostor === BABYLON.PhysicsEngine.NoImpostor) {
  10162. physicsEngine._unregisterMesh(this);
  10163. return;
  10164. }
  10165. if (!options) {
  10166. options = { mass: 0, friction: 0.2, restitution: 0.2 };
  10167. }
  10168. else {
  10169. if (!options.mass && options.mass !== 0)
  10170. options.mass = 0;
  10171. if (!options.friction && options.friction !== 0)
  10172. options.friction = 0.2;
  10173. if (!options.restitution && options.restitution !== 0)
  10174. options.restitution = 0.2;
  10175. }
  10176. this._physicImpostor = impostor;
  10177. this._physicsMass = options.mass;
  10178. this._physicsFriction = options.friction;
  10179. this._physicRestitution = options.restitution;
  10180. return physicsEngine._registerMesh(this, impostor, options);
  10181. };
  10182. AbstractMesh.prototype.getPhysicsImpostor = function () {
  10183. if (!this._physicImpostor) {
  10184. return BABYLON.PhysicsEngine.NoImpostor;
  10185. }
  10186. return this._physicImpostor;
  10187. };
  10188. AbstractMesh.prototype.getPhysicsMass = function () {
  10189. if (!this._physicsMass) {
  10190. return 0;
  10191. }
  10192. return this._physicsMass;
  10193. };
  10194. AbstractMesh.prototype.getPhysicsFriction = function () {
  10195. if (!this._physicsFriction) {
  10196. return 0;
  10197. }
  10198. return this._physicsFriction;
  10199. };
  10200. AbstractMesh.prototype.getPhysicsRestitution = function () {
  10201. if (!this._physicRestitution) {
  10202. return 0;
  10203. }
  10204. return this._physicRestitution;
  10205. };
  10206. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  10207. if (!camera) {
  10208. camera = this.getScene().activeCamera;
  10209. }
  10210. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  10211. };
  10212. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  10213. if (!camera) {
  10214. camera = this.getScene().activeCamera;
  10215. }
  10216. return this.absolutePosition.subtract(camera.position).length();
  10217. };
  10218. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  10219. if (!this._physicImpostor) {
  10220. return;
  10221. }
  10222. this.getScene().getPhysicsEngine()._applyImpulse(this, force, contactPoint);
  10223. };
  10224. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  10225. if (!this._physicImpostor) {
  10226. return;
  10227. }
  10228. this.getScene().getPhysicsEngine()._createLink(this, otherMesh, pivot1, pivot2, options);
  10229. };
  10230. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  10231. if (!this._physicImpostor) {
  10232. return;
  10233. }
  10234. this.getScene().getPhysicsEngine()._updateBodyPosition(this);
  10235. };
  10236. // Collisions
  10237. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  10238. var globalPosition = this.getAbsolutePosition();
  10239. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  10240. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  10241. this._collider.radius = this.ellipsoid;
  10242. this.getScene()._getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this._newPositionForCollisions, this);
  10243. this._newPositionForCollisions.subtractToRef(this._oldPositionForCollisions, this._diffPositionForCollisions);
  10244. if (this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  10245. this.position.addInPlace(this._diffPositionForCollisions);
  10246. }
  10247. };
  10248. // Submeshes octree
  10249. /**
  10250. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  10251. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  10252. */
  10253. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  10254. if (maxCapacity === void 0) { maxCapacity = 64; }
  10255. if (maxDepth === void 0) { maxDepth = 2; }
  10256. if (!this._submeshesOctree) {
  10257. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  10258. }
  10259. this.computeWorldMatrix(true);
  10260. // Update octree
  10261. var bbox = this.getBoundingInfo().boundingBox;
  10262. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  10263. return this._submeshesOctree;
  10264. };
  10265. // Collisions
  10266. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  10267. this._generatePointsArray();
  10268. // Transformation
  10269. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  10270. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  10271. subMesh._lastColliderWorldVertices = [];
  10272. subMesh._trianglePlanes = [];
  10273. var start = subMesh.verticesStart;
  10274. var end = (subMesh.verticesStart + subMesh.verticesCount);
  10275. for (var i = start; i < end; i++) {
  10276. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  10277. }
  10278. }
  10279. // Collide
  10280. collider._collide(subMesh, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart);
  10281. };
  10282. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  10283. var subMeshes;
  10284. var len;
  10285. // Octrees
  10286. if (this._submeshesOctree && this.useOctreeForCollisions) {
  10287. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  10288. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  10289. len = intersections.length;
  10290. subMeshes = intersections.data;
  10291. }
  10292. else {
  10293. subMeshes = this.subMeshes;
  10294. len = subMeshes.length;
  10295. }
  10296. for (var index = 0; index < len; index++) {
  10297. var subMesh = subMeshes[index];
  10298. // Bounding test
  10299. if (len > 1 && !subMesh._checkCollision(collider))
  10300. continue;
  10301. this._collideForSubMesh(subMesh, transformMatrix, collider);
  10302. }
  10303. };
  10304. AbstractMesh.prototype._checkCollision = function (collider) {
  10305. // Bounding box test
  10306. if (!this._boundingInfo._checkCollision(collider))
  10307. return;
  10308. // Transformation matrix
  10309. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  10310. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  10311. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  10312. };
  10313. // Picking
  10314. AbstractMesh.prototype._generatePointsArray = function () {
  10315. return false;
  10316. };
  10317. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  10318. var pickingInfo = new BABYLON.PickingInfo();
  10319. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  10320. return pickingInfo;
  10321. }
  10322. if (!this._generatePointsArray()) {
  10323. return pickingInfo;
  10324. }
  10325. var intersectInfo = null;
  10326. // Octrees
  10327. var subMeshes;
  10328. var len;
  10329. if (this._submeshesOctree && this.useOctreeForPicking) {
  10330. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  10331. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  10332. len = intersections.length;
  10333. subMeshes = intersections.data;
  10334. }
  10335. else {
  10336. subMeshes = this.subMeshes;
  10337. len = subMeshes.length;
  10338. }
  10339. for (var index = 0; index < len; index++) {
  10340. var subMesh = subMeshes[index];
  10341. // Bounding test
  10342. if (len > 1 && !subMesh.canIntersects(ray))
  10343. continue;
  10344. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  10345. if (currentIntersectInfo) {
  10346. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  10347. intersectInfo = currentIntersectInfo;
  10348. intersectInfo.subMeshId = index;
  10349. if (fastCheck) {
  10350. break;
  10351. }
  10352. }
  10353. }
  10354. }
  10355. if (intersectInfo) {
  10356. // Get picked point
  10357. var world = this.getWorldMatrix();
  10358. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  10359. var direction = ray.direction.clone();
  10360. direction = direction.scale(intersectInfo.distance);
  10361. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  10362. var pickedPoint = worldOrigin.add(worldDirection);
  10363. // Return result
  10364. pickingInfo.hit = true;
  10365. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  10366. pickingInfo.pickedPoint = pickedPoint;
  10367. pickingInfo.pickedMesh = this;
  10368. pickingInfo.bu = intersectInfo.bu;
  10369. pickingInfo.bv = intersectInfo.bv;
  10370. pickingInfo.faceId = intersectInfo.faceId;
  10371. pickingInfo.subMeshId = intersectInfo.subMeshId;
  10372. return pickingInfo;
  10373. }
  10374. return pickingInfo;
  10375. };
  10376. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  10377. return null;
  10378. };
  10379. AbstractMesh.prototype.releaseSubMeshes = function () {
  10380. if (this.subMeshes) {
  10381. while (this.subMeshes.length) {
  10382. this.subMeshes[0].dispose();
  10383. }
  10384. }
  10385. else {
  10386. this.subMeshes = new Array();
  10387. }
  10388. };
  10389. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  10390. // Physics
  10391. if (this.getPhysicsImpostor() != BABYLON.PhysicsEngine.NoImpostor) {
  10392. this.setPhysicsState(BABYLON.PhysicsEngine.NoImpostor);
  10393. }
  10394. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  10395. var other = this._intersectionsInProgress[index];
  10396. var pos = other._intersectionsInProgress.indexOf(this);
  10397. other._intersectionsInProgress.splice(pos, 1);
  10398. }
  10399. this._intersectionsInProgress = [];
  10400. // SubMeshes
  10401. this.releaseSubMeshes();
  10402. // Remove from scene
  10403. var index = this.getScene().meshes.indexOf(this);
  10404. if (index != -1) {
  10405. // Remove from the scene if mesh found
  10406. this.getScene().meshes.splice(index, 1);
  10407. }
  10408. if (!doNotRecurse) {
  10409. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  10410. if (this.getScene().particleSystems[index].emitter == this) {
  10411. this.getScene().particleSystems[index].dispose();
  10412. index--;
  10413. }
  10414. }
  10415. // Children
  10416. var objects = this.getScene().meshes.slice(0);
  10417. for (index = 0; index < objects.length; index++) {
  10418. if (objects[index].parent == this) {
  10419. objects[index].dispose();
  10420. }
  10421. }
  10422. }
  10423. else {
  10424. for (index = 0; index < this.getScene().meshes.length; index++) {
  10425. var obj = this.getScene().meshes[index];
  10426. if (obj.parent === this) {
  10427. obj.parent = null;
  10428. obj.computeWorldMatrix(true);
  10429. }
  10430. }
  10431. }
  10432. this._onAfterWorldMatrixUpdate = [];
  10433. this._isDisposed = true;
  10434. // Callback
  10435. if (this.onDispose) {
  10436. this.onDispose();
  10437. }
  10438. };
  10439. // Statics
  10440. AbstractMesh._BILLBOARDMODE_NONE = 0;
  10441. AbstractMesh._BILLBOARDMODE_X = 1;
  10442. AbstractMesh._BILLBOARDMODE_Y = 2;
  10443. AbstractMesh._BILLBOARDMODE_Z = 4;
  10444. AbstractMesh._BILLBOARDMODE_ALL = 7;
  10445. return AbstractMesh;
  10446. })(BABYLON.Node);
  10447. BABYLON.AbstractMesh = AbstractMesh;
  10448. })(BABYLON || (BABYLON = {}));
  10449. //# sourceMappingURL=babylon.abstractMesh.js.map
  10450. var BABYLON;
  10451. (function (BABYLON) {
  10452. var _InstancesBatch = (function () {
  10453. function _InstancesBatch() {
  10454. this.mustReturn = false;
  10455. this.visibleInstances = new Array();
  10456. this.renderSelf = new Array();
  10457. }
  10458. return _InstancesBatch;
  10459. })();
  10460. BABYLON._InstancesBatch = _InstancesBatch;
  10461. var Mesh = (function (_super) {
  10462. __extends(Mesh, _super);
  10463. /**
  10464. * @constructor
  10465. * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
  10466. * @param {Scene} scene - The scene to add this mesh to.
  10467. * @param {Node} parent - The parent of this mesh, if it has one
  10468. * @param {Mesh} source - An optional Mesh from which geometry is shared, cloned.
  10469. * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
  10470. * When false, achieved by calling a clone(), also passing False.
  10471. * This will make creation of children, recursive.
  10472. */
  10473. function Mesh(name, scene, parent, source, doNotCloneChildren) {
  10474. if (parent === void 0) { parent = null; }
  10475. _super.call(this, name, scene);
  10476. // Members
  10477. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  10478. this.instances = new Array();
  10479. this._LODLevels = new Array();
  10480. this._onBeforeRenderCallbacks = new Array();
  10481. this._onAfterRenderCallbacks = new Array();
  10482. this._visibleInstances = {};
  10483. this._renderIdForInstances = new Array();
  10484. this._batchCache = new _InstancesBatch();
  10485. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  10486. if (source) {
  10487. // Geometry
  10488. if (source._geometry) {
  10489. source._geometry.applyToMesh(this);
  10490. }
  10491. // Deep copy
  10492. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton"], []);
  10493. // Material
  10494. this.material = source.material;
  10495. if (!doNotCloneChildren) {
  10496. for (var index = 0; index < scene.meshes.length; index++) {
  10497. var mesh = scene.meshes[index];
  10498. if (mesh.parent === source) {
  10499. // doNotCloneChildren is always going to be False
  10500. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  10501. }
  10502. }
  10503. }
  10504. for (index = 0; index < scene.particleSystems.length; index++) {
  10505. var system = scene.particleSystems[index];
  10506. if (system.emitter === source) {
  10507. system.clone(system.name, this);
  10508. }
  10509. }
  10510. this.computeWorldMatrix(true);
  10511. }
  10512. // Parent
  10513. if (parent !== null) {
  10514. this.parent = parent;
  10515. }
  10516. }
  10517. Object.defineProperty(Mesh, "FRONTSIDE", {
  10518. get: function () {
  10519. return Mesh._FRONTSIDE;
  10520. },
  10521. enumerable: true,
  10522. configurable: true
  10523. });
  10524. Object.defineProperty(Mesh, "BACKSIDE", {
  10525. get: function () {
  10526. return Mesh._BACKSIDE;
  10527. },
  10528. enumerable: true,
  10529. configurable: true
  10530. });
  10531. Object.defineProperty(Mesh, "DOUBLESIDE", {
  10532. get: function () {
  10533. return Mesh._DOUBLESIDE;
  10534. },
  10535. enumerable: true,
  10536. configurable: true
  10537. });
  10538. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  10539. get: function () {
  10540. return Mesh._DEFAULTSIDE;
  10541. },
  10542. enumerable: true,
  10543. configurable: true
  10544. });
  10545. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  10546. // Methods
  10547. get: function () {
  10548. return this._LODLevels.length > 0;
  10549. },
  10550. enumerable: true,
  10551. configurable: true
  10552. });
  10553. Mesh.prototype._sortLODLevels = function () {
  10554. this._LODLevels.sort(function (a, b) {
  10555. if (a.distance < b.distance) {
  10556. return 1;
  10557. }
  10558. if (a.distance > b.distance) {
  10559. return -1;
  10560. }
  10561. return 0;
  10562. });
  10563. };
  10564. /**
  10565. * Add a mesh as LOD level triggered at the given distance.
  10566. * @param {number} distance - the distance from the center of the object to show this level
  10567. * @param {BABYLON.Mesh} mesh - the mesh to be added as LOD level
  10568. * @return {BABYLON.Mesh} this mesh (for chaining)
  10569. */
  10570. Mesh.prototype.addLODLevel = function (distance, mesh) {
  10571. if (mesh && mesh._masterMesh) {
  10572. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  10573. return this;
  10574. }
  10575. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  10576. this._LODLevels.push(level);
  10577. if (mesh) {
  10578. mesh._masterMesh = this;
  10579. }
  10580. this._sortLODLevels();
  10581. return this;
  10582. };
  10583. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  10584. for (var index = 0; index < this._LODLevels.length; index++) {
  10585. var level = this._LODLevels[index];
  10586. if (level.distance === distance) {
  10587. return level.mesh;
  10588. }
  10589. }
  10590. return null;
  10591. };
  10592. /**
  10593. * Remove a mesh from the LOD array
  10594. * @param {BABYLON.Mesh} mesh - the mesh to be removed.
  10595. * @return {BABYLON.Mesh} this mesh (for chaining)
  10596. */
  10597. Mesh.prototype.removeLODLevel = function (mesh) {
  10598. for (var index = 0; index < this._LODLevels.length; index++) {
  10599. if (this._LODLevels[index].mesh === mesh) {
  10600. this._LODLevels.splice(index, 1);
  10601. if (mesh) {
  10602. mesh._masterMesh = null;
  10603. }
  10604. }
  10605. }
  10606. this._sortLODLevels();
  10607. return this;
  10608. };
  10609. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  10610. if (!this._LODLevels || this._LODLevels.length === 0) {
  10611. return this;
  10612. }
  10613. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.position).length();
  10614. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  10615. return this;
  10616. }
  10617. for (var index = 0; index < this._LODLevels.length; index++) {
  10618. var level = this._LODLevels[index];
  10619. if (level.distance < distanceToCamera) {
  10620. if (level.mesh) {
  10621. level.mesh._preActivate();
  10622. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  10623. }
  10624. return level.mesh;
  10625. }
  10626. }
  10627. return this;
  10628. };
  10629. Object.defineProperty(Mesh.prototype, "geometry", {
  10630. get: function () {
  10631. return this._geometry;
  10632. },
  10633. enumerable: true,
  10634. configurable: true
  10635. });
  10636. Mesh.prototype.getTotalVertices = function () {
  10637. if (!this._geometry) {
  10638. return 0;
  10639. }
  10640. return this._geometry.getTotalVertices();
  10641. };
  10642. Mesh.prototype.getVerticesData = function (kind) {
  10643. if (!this._geometry) {
  10644. return null;
  10645. }
  10646. return this._geometry.getVerticesData(kind);
  10647. };
  10648. Mesh.prototype.getVertexBuffer = function (kind) {
  10649. if (!this._geometry) {
  10650. return undefined;
  10651. }
  10652. return this._geometry.getVertexBuffer(kind);
  10653. };
  10654. Mesh.prototype.isVerticesDataPresent = function (kind) {
  10655. if (!this._geometry) {
  10656. if (this._delayInfo) {
  10657. return this._delayInfo.indexOf(kind) !== -1;
  10658. }
  10659. return false;
  10660. }
  10661. return this._geometry.isVerticesDataPresent(kind);
  10662. };
  10663. Mesh.prototype.getVerticesDataKinds = function () {
  10664. if (!this._geometry) {
  10665. var result = [];
  10666. if (this._delayInfo) {
  10667. for (var kind in this._delayInfo) {
  10668. result.push(kind);
  10669. }
  10670. }
  10671. return result;
  10672. }
  10673. return this._geometry.getVerticesDataKinds();
  10674. };
  10675. Mesh.prototype.getTotalIndices = function () {
  10676. if (!this._geometry) {
  10677. return 0;
  10678. }
  10679. return this._geometry.getTotalIndices();
  10680. };
  10681. Mesh.prototype.getIndices = function () {
  10682. if (!this._geometry) {
  10683. return [];
  10684. }
  10685. return this._geometry.getIndices();
  10686. };
  10687. Object.defineProperty(Mesh.prototype, "isBlocked", {
  10688. get: function () {
  10689. return this._masterMesh !== null && this._masterMesh !== undefined;
  10690. },
  10691. enumerable: true,
  10692. configurable: true
  10693. });
  10694. Mesh.prototype.isReady = function () {
  10695. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  10696. return false;
  10697. }
  10698. return _super.prototype.isReady.call(this);
  10699. };
  10700. Mesh.prototype.isDisposed = function () {
  10701. return this._isDisposed;
  10702. };
  10703. // Methods
  10704. Mesh.prototype._preActivate = function () {
  10705. var sceneRenderId = this.getScene().getRenderId();
  10706. if (this._preActivateId === sceneRenderId) {
  10707. return;
  10708. }
  10709. this._preActivateId = sceneRenderId;
  10710. this._visibleInstances = null;
  10711. };
  10712. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  10713. if (!this._visibleInstances) {
  10714. this._visibleInstances = {};
  10715. this._visibleInstances.defaultRenderId = renderId;
  10716. this._visibleInstances.selfDefaultRenderId = this._renderId;
  10717. }
  10718. if (!this._visibleInstances[renderId]) {
  10719. this._visibleInstances[renderId] = new Array();
  10720. }
  10721. this._visibleInstances[renderId].push(instance);
  10722. };
  10723. Mesh.prototype.refreshBoundingInfo = function () {
  10724. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  10725. if (data) {
  10726. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  10727. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  10728. }
  10729. if (this.subMeshes) {
  10730. for (var index = 0; index < this.subMeshes.length; index++) {
  10731. this.subMeshes[index].refreshBoundingInfo();
  10732. }
  10733. }
  10734. this._updateBoundingInfo();
  10735. };
  10736. Mesh.prototype._createGlobalSubMesh = function () {
  10737. var totalVertices = this.getTotalVertices();
  10738. if (!totalVertices || !this.getIndices()) {
  10739. return null;
  10740. }
  10741. this.releaseSubMeshes();
  10742. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  10743. };
  10744. Mesh.prototype.subdivide = function (count) {
  10745. if (count < 1) {
  10746. return;
  10747. }
  10748. var totalIndices = this.getTotalIndices();
  10749. var subdivisionSize = (totalIndices / count) | 0;
  10750. var offset = 0;
  10751. while (subdivisionSize % 3 !== 0) {
  10752. subdivisionSize++;
  10753. }
  10754. this.releaseSubMeshes();
  10755. for (var index = 0; index < count; index++) {
  10756. if (offset >= totalIndices) {
  10757. break;
  10758. }
  10759. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  10760. offset += subdivisionSize;
  10761. }
  10762. this.synchronizeInstances();
  10763. };
  10764. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  10765. if (kind instanceof Array) {
  10766. var temp = data;
  10767. data = kind;
  10768. kind = temp;
  10769. BABYLON.Tools.Warn("Deprecated usage of setVerticesData detected (since v1.12). Current signature is setVerticesData(kind, data, updatable).");
  10770. }
  10771. if (!this._geometry) {
  10772. var vertexData = new BABYLON.VertexData();
  10773. vertexData.set(data, kind);
  10774. var scene = this.getScene();
  10775. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  10776. }
  10777. else {
  10778. this._geometry.setVerticesData(kind, data, updatable, stride);
  10779. }
  10780. };
  10781. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  10782. if (!this._geometry) {
  10783. return;
  10784. }
  10785. if (!makeItUnique) {
  10786. this._geometry.updateVerticesData(kind, data, updateExtends);
  10787. }
  10788. else {
  10789. this.makeGeometryUnique();
  10790. this.updateVerticesData(kind, data, updateExtends, false);
  10791. }
  10792. };
  10793. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  10794. if (!this._geometry) {
  10795. return;
  10796. }
  10797. if (!makeItUnique) {
  10798. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  10799. }
  10800. else {
  10801. this.makeGeometryUnique();
  10802. this.updateVerticesDataDirectly(kind, data, offset, false);
  10803. }
  10804. };
  10805. Mesh.prototype.makeGeometryUnique = function () {
  10806. if (!this._geometry) {
  10807. return;
  10808. }
  10809. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  10810. geometry.applyToMesh(this);
  10811. };
  10812. Mesh.prototype.setIndices = function (indices, totalVertices) {
  10813. if (!this._geometry) {
  10814. var vertexData = new BABYLON.VertexData();
  10815. vertexData.indices = indices;
  10816. var scene = this.getScene();
  10817. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  10818. }
  10819. else {
  10820. this._geometry.setIndices(indices, totalVertices);
  10821. }
  10822. };
  10823. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  10824. var engine = this.getScene().getEngine();
  10825. // Wireframe
  10826. var indexToBind;
  10827. switch (fillMode) {
  10828. case BABYLON.Material.PointFillMode:
  10829. indexToBind = null;
  10830. break;
  10831. case BABYLON.Material.WireFrameFillMode:
  10832. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  10833. break;
  10834. default:
  10835. case BABYLON.Material.TriangleFillMode:
  10836. indexToBind = this._geometry.getIndexBuffer();
  10837. break;
  10838. }
  10839. // VBOs
  10840. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  10841. };
  10842. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  10843. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  10844. return;
  10845. }
  10846. var engine = this.getScene().getEngine();
  10847. switch (fillMode) {
  10848. case BABYLON.Material.PointFillMode:
  10849. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  10850. break;
  10851. case BABYLON.Material.WireFrameFillMode:
  10852. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  10853. break;
  10854. default:
  10855. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  10856. }
  10857. };
  10858. Mesh.prototype.registerBeforeRender = function (func) {
  10859. this._onBeforeRenderCallbacks.push(func);
  10860. };
  10861. Mesh.prototype.unregisterBeforeRender = function (func) {
  10862. var index = this._onBeforeRenderCallbacks.indexOf(func);
  10863. if (index > -1) {
  10864. this._onBeforeRenderCallbacks.splice(index, 1);
  10865. }
  10866. };
  10867. Mesh.prototype.registerAfterRender = function (func) {
  10868. this._onAfterRenderCallbacks.push(func);
  10869. };
  10870. Mesh.prototype.unregisterAfterRender = function (func) {
  10871. var index = this._onAfterRenderCallbacks.indexOf(func);
  10872. if (index > -1) {
  10873. this._onAfterRenderCallbacks.splice(index, 1);
  10874. }
  10875. };
  10876. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  10877. var scene = this.getScene();
  10878. this._batchCache.mustReturn = false;
  10879. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  10880. this._batchCache.visibleInstances[subMeshId] = null;
  10881. if (this._visibleInstances) {
  10882. var currentRenderId = scene.getRenderId();
  10883. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  10884. var selfRenderId = this._renderId;
  10885. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  10886. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  10887. currentRenderId = Math.max(this._visibleInstances.defaultRenderId, currentRenderId);
  10888. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  10889. }
  10890. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  10891. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  10892. this._batchCache.mustReturn = true;
  10893. return this._batchCache;
  10894. }
  10895. if (currentRenderId !== selfRenderId) {
  10896. this._batchCache.renderSelf[subMeshId] = false;
  10897. }
  10898. }
  10899. this._renderIdForInstances[subMeshId] = currentRenderId;
  10900. }
  10901. return this._batchCache;
  10902. };
  10903. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  10904. var visibleInstances = batch.visibleInstances[subMesh._id];
  10905. var matricesCount = visibleInstances.length + 1;
  10906. var bufferSize = matricesCount * 16 * 4;
  10907. while (this._instancesBufferSize < bufferSize) {
  10908. this._instancesBufferSize *= 2;
  10909. }
  10910. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  10911. if (this._worldMatricesInstancesBuffer) {
  10912. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  10913. }
  10914. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  10915. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  10916. }
  10917. var offset = 0;
  10918. var instancesCount = 0;
  10919. var world = this.getWorldMatrix();
  10920. if (batch.renderSelf[subMesh._id]) {
  10921. world.copyToArray(this._worldMatricesInstancesArray, offset);
  10922. offset += 16;
  10923. instancesCount++;
  10924. }
  10925. if (visibleInstances) {
  10926. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  10927. var instance = visibleInstances[instanceIndex];
  10928. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  10929. offset += 16;
  10930. instancesCount++;
  10931. }
  10932. }
  10933. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  10934. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  10935. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  10936. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  10937. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  10938. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  10939. this._draw(subMesh, fillMode, instancesCount);
  10940. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  10941. };
  10942. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw) {
  10943. var scene = this.getScene();
  10944. var engine = scene.getEngine();
  10945. if (hardwareInstancedRendering) {
  10946. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  10947. }
  10948. else {
  10949. if (batch.renderSelf[subMesh._id]) {
  10950. // Draw
  10951. if (onBeforeDraw) {
  10952. onBeforeDraw(false, this.getWorldMatrix());
  10953. }
  10954. this._draw(subMesh, fillMode);
  10955. }
  10956. if (batch.visibleInstances[subMesh._id]) {
  10957. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  10958. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  10959. // World
  10960. var world = instance.getWorldMatrix();
  10961. if (onBeforeDraw) {
  10962. onBeforeDraw(true, world);
  10963. }
  10964. // Draw
  10965. this._draw(subMesh, fillMode);
  10966. }
  10967. }
  10968. }
  10969. };
  10970. Mesh.prototype.render = function (subMesh) {
  10971. var scene = this.getScene();
  10972. // Managing instances
  10973. var batch = this._getInstancesRenderList(subMesh._id);
  10974. if (batch.mustReturn) {
  10975. return;
  10976. }
  10977. // Checking geometry state
  10978. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  10979. return;
  10980. }
  10981. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  10982. this._onBeforeRenderCallbacks[callbackIndex](this);
  10983. }
  10984. var engine = scene.getEngine();
  10985. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  10986. // Material
  10987. var effectiveMaterial = subMesh.getMaterial();
  10988. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  10989. return;
  10990. }
  10991. // Outline - step 1
  10992. var savedDepthWrite = engine.getDepthWrite();
  10993. if (this.renderOutline) {
  10994. engine.setDepthWrite(false);
  10995. scene.getOutlineRenderer().render(subMesh, batch);
  10996. engine.setDepthWrite(savedDepthWrite);
  10997. }
  10998. effectiveMaterial._preBind();
  10999. var effect = effectiveMaterial.getEffect();
  11000. // Bind
  11001. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  11002. this._bind(subMesh, effect, fillMode);
  11003. var world = this.getWorldMatrix();
  11004. effectiveMaterial.bind(world, this);
  11005. // Draw
  11006. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  11007. if (isInstance) {
  11008. effectiveMaterial.bindOnlyWorldMatrix(world);
  11009. }
  11010. });
  11011. // Unbind
  11012. effectiveMaterial.unbind();
  11013. // Outline - step 2
  11014. if (this.renderOutline && savedDepthWrite) {
  11015. engine.setDepthWrite(true);
  11016. engine.setColorWrite(false);
  11017. scene.getOutlineRenderer().render(subMesh, batch);
  11018. engine.setColorWrite(true);
  11019. }
  11020. // Overlay
  11021. if (this.renderOverlay) {
  11022. var currentMode = engine.getAlphaMode();
  11023. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  11024. scene.getOutlineRenderer().render(subMesh, batch, true);
  11025. engine.setAlphaMode(currentMode);
  11026. }
  11027. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  11028. this._onAfterRenderCallbacks[callbackIndex](this);
  11029. }
  11030. };
  11031. Mesh.prototype.getEmittedParticleSystems = function () {
  11032. var results = new Array();
  11033. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  11034. var particleSystem = this.getScene().particleSystems[index];
  11035. if (particleSystem.emitter === this) {
  11036. results.push(particleSystem);
  11037. }
  11038. }
  11039. return results;
  11040. };
  11041. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  11042. var results = new Array();
  11043. var descendants = this.getDescendants();
  11044. descendants.push(this);
  11045. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  11046. var particleSystem = this.getScene().particleSystems[index];
  11047. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  11048. results.push(particleSystem);
  11049. }
  11050. }
  11051. return results;
  11052. };
  11053. Mesh.prototype.getChildren = function () {
  11054. var results = [];
  11055. for (var index = 0; index < this.getScene().meshes.length; index++) {
  11056. var mesh = this.getScene().meshes[index];
  11057. if (mesh.parent === this) {
  11058. results.push(mesh);
  11059. }
  11060. }
  11061. return results;
  11062. };
  11063. Mesh.prototype._checkDelayState = function () {
  11064. var _this = this;
  11065. var that = this;
  11066. var scene = this.getScene();
  11067. if (this._geometry) {
  11068. this._geometry.load(scene);
  11069. }
  11070. else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  11071. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  11072. scene._addPendingData(that);
  11073. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  11074. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  11075. if (data instanceof ArrayBuffer) {
  11076. _this._delayLoadingFunction(data, _this);
  11077. }
  11078. else {
  11079. _this._delayLoadingFunction(JSON.parse(data), _this);
  11080. }
  11081. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  11082. scene._removePendingData(_this);
  11083. }, function () {
  11084. }, scene.database, getBinaryData);
  11085. }
  11086. };
  11087. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  11088. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  11089. return false;
  11090. }
  11091. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  11092. return false;
  11093. }
  11094. this._checkDelayState();
  11095. return true;
  11096. };
  11097. Mesh.prototype.setMaterialByID = function (id) {
  11098. var materials = this.getScene().materials;
  11099. for (var index = 0; index < materials.length; index++) {
  11100. if (materials[index].id === id) {
  11101. this.material = materials[index];
  11102. return;
  11103. }
  11104. }
  11105. // Multi
  11106. var multiMaterials = this.getScene().multiMaterials;
  11107. for (index = 0; index < multiMaterials.length; index++) {
  11108. if (multiMaterials[index].id === id) {
  11109. this.material = multiMaterials[index];
  11110. return;
  11111. }
  11112. }
  11113. };
  11114. Mesh.prototype.getAnimatables = function () {
  11115. var results = [];
  11116. if (this.material) {
  11117. results.push(this.material);
  11118. }
  11119. if (this.skeleton) {
  11120. results.push(this.skeleton);
  11121. }
  11122. return results;
  11123. };
  11124. // Geometry
  11125. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  11126. // Position
  11127. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  11128. return;
  11129. }
  11130. this._resetPointsArrayCache();
  11131. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11132. var temp = [];
  11133. for (var index = 0; index < data.length; index += 3) {
  11134. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  11135. }
  11136. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  11137. // Normals
  11138. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  11139. return;
  11140. }
  11141. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  11142. for (index = 0; index < data.length; index += 3) {
  11143. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  11144. }
  11145. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  11146. };
  11147. // Cache
  11148. Mesh.prototype._resetPointsArrayCache = function () {
  11149. this._positions = null;
  11150. };
  11151. Mesh.prototype._generatePointsArray = function () {
  11152. if (this._positions)
  11153. return true;
  11154. this._positions = [];
  11155. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11156. if (!data) {
  11157. return false;
  11158. }
  11159. for (var index = 0; index < data.length; index += 3) {
  11160. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  11161. }
  11162. return true;
  11163. };
  11164. // Clone
  11165. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  11166. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  11167. };
  11168. // Dispose
  11169. Mesh.prototype.dispose = function (doNotRecurse) {
  11170. if (this._geometry) {
  11171. this._geometry.releaseForMesh(this, true);
  11172. }
  11173. // Instances
  11174. if (this._worldMatricesInstancesBuffer) {
  11175. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  11176. this._worldMatricesInstancesBuffer = null;
  11177. }
  11178. while (this.instances.length) {
  11179. this.instances[0].dispose();
  11180. }
  11181. _super.prototype.dispose.call(this, doNotRecurse);
  11182. };
  11183. // Geometric tools
  11184. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  11185. var _this = this;
  11186. var scene = this.getScene();
  11187. var onload = function (img) {
  11188. // Getting height map data
  11189. var canvas = document.createElement("canvas");
  11190. var context = canvas.getContext("2d");
  11191. var heightMapWidth = img.width;
  11192. var heightMapHeight = img.height;
  11193. canvas.width = heightMapWidth;
  11194. canvas.height = heightMapHeight;
  11195. context.drawImage(img, 0, 0);
  11196. // Create VertexData from map data
  11197. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  11198. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  11199. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  11200. //execute success callback, if set
  11201. if (onSuccess) {
  11202. onSuccess(_this);
  11203. }
  11204. };
  11205. BABYLON.Tools.LoadImage(url, onload, function () {
  11206. }, scene.database);
  11207. };
  11208. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  11209. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  11210. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  11211. return;
  11212. }
  11213. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11214. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  11215. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  11216. var position = BABYLON.Vector3.Zero();
  11217. var normal = BABYLON.Vector3.Zero();
  11218. var uv = BABYLON.Vector2.Zero();
  11219. for (var index = 0; index < positions.length; index += 3) {
  11220. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  11221. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  11222. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  11223. // Compute height
  11224. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  11225. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  11226. var pos = (u + v * heightMapWidth) * 4;
  11227. var r = buffer[pos] / 255.0;
  11228. var g = buffer[pos + 1] / 255.0;
  11229. var b = buffer[pos + 2] / 255.0;
  11230. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  11231. normal.normalize();
  11232. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  11233. position = position.add(normal);
  11234. position.toArray(positions, index);
  11235. }
  11236. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  11237. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  11238. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  11239. };
  11240. Mesh.prototype.convertToFlatShadedMesh = function () {
  11241. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  11242. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  11243. var kinds = this.getVerticesDataKinds();
  11244. var vbs = [];
  11245. var data = [];
  11246. var newdata = [];
  11247. var updatableNormals = false;
  11248. for (var kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  11249. var kind = kinds[kindIndex];
  11250. var vertexBuffer = this.getVertexBuffer(kind);
  11251. if (kind === BABYLON.VertexBuffer.NormalKind) {
  11252. updatableNormals = vertexBuffer.isUpdatable();
  11253. kinds.splice(kindIndex, 1);
  11254. kindIndex--;
  11255. continue;
  11256. }
  11257. vbs[kind] = vertexBuffer;
  11258. data[kind] = vbs[kind].getData();
  11259. newdata[kind] = [];
  11260. }
  11261. // Save previous submeshes
  11262. var previousSubmeshes = this.subMeshes.slice(0);
  11263. var indices = this.getIndices();
  11264. var totalIndices = this.getTotalIndices();
  11265. for (var index = 0; index < totalIndices; index++) {
  11266. var vertexIndex = indices[index];
  11267. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  11268. kind = kinds[kindIndex];
  11269. var stride = vbs[kind].getStrideSize();
  11270. for (var offset = 0; offset < stride; offset++) {
  11271. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  11272. }
  11273. }
  11274. }
  11275. // Updating faces & normal
  11276. var normals = [];
  11277. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  11278. for (index = 0; index < totalIndices; index += 3) {
  11279. indices[index] = index;
  11280. indices[index + 1] = index + 1;
  11281. indices[index + 2] = index + 2;
  11282. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  11283. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  11284. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  11285. var p1p2 = p1.subtract(p2);
  11286. var p3p2 = p3.subtract(p2);
  11287. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  11288. for (var localIndex = 0; localIndex < 3; localIndex++) {
  11289. normals.push(normal.x);
  11290. normals.push(normal.y);
  11291. normals.push(normal.z);
  11292. }
  11293. }
  11294. this.setIndices(indices);
  11295. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  11296. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  11297. kind = kinds[kindIndex];
  11298. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  11299. }
  11300. // Updating submeshes
  11301. this.releaseSubMeshes();
  11302. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  11303. var previousOne = previousSubmeshes[submeshIndex];
  11304. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  11305. }
  11306. this.synchronizeInstances();
  11307. };
  11308. // Instances
  11309. Mesh.prototype.createInstance = function (name) {
  11310. return new BABYLON.InstancedMesh(name, this);
  11311. };
  11312. Mesh.prototype.synchronizeInstances = function () {
  11313. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  11314. var instance = this.instances[instanceIndex];
  11315. instance._syncSubMeshes();
  11316. }
  11317. };
  11318. /**
  11319. * Simplify the mesh according to the given array of settings.
  11320. * Function will return immediately and will simplify async.
  11321. * @param settings a collection of simplification settings.
  11322. * @param parallelProcessing should all levels calculate parallel or one after the other.
  11323. * @param type the type of simplification to run.
  11324. * successCallback optional success callback to be called after the simplification finished processing all settings.
  11325. */
  11326. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  11327. if (parallelProcessing === void 0) { parallelProcessing = true; }
  11328. if (simplificationType === void 0) { simplificationType = 0 /* QUADRATIC */; }
  11329. this.getScene().simplificationQueue.addTask({
  11330. settings: settings,
  11331. parallelProcessing: parallelProcessing,
  11332. mesh: this,
  11333. simplificationType: simplificationType,
  11334. successCallback: successCallback
  11335. });
  11336. };
  11337. // Statics
  11338. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation) {
  11339. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11340. var ribbon = new Mesh(name, scene);
  11341. var vertexData = BABYLON.VertexData.CreateRibbon(pathArray, closeArray, closePath, offset, sideOrientation);
  11342. vertexData.applyToMesh(ribbon, updatable);
  11343. return ribbon;
  11344. };
  11345. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  11346. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11347. var box = new Mesh(name, scene);
  11348. var vertexData = BABYLON.VertexData.CreateBox(size, sideOrientation);
  11349. vertexData.applyToMesh(box, updatable);
  11350. return box;
  11351. };
  11352. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  11353. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11354. var sphere = new Mesh(name, scene);
  11355. var vertexData = BABYLON.VertexData.CreateSphere(segments, diameter, sideOrientation);
  11356. vertexData.applyToMesh(sphere, updatable);
  11357. return sphere;
  11358. };
  11359. // Cylinder and cone (Code inspired by SharpDX.org)
  11360. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  11361. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11362. // subdivisions is a new parameter, we need to support old signature
  11363. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  11364. if (scene !== undefined) {
  11365. updatable = scene;
  11366. }
  11367. scene = subdivisions;
  11368. subdivisions = 1;
  11369. }
  11370. var cylinder = new Mesh(name, scene);
  11371. var vertexData = BABYLON.VertexData.CreateCylinder(height, diameterTop, diameterBottom, tessellation, subdivisions);
  11372. vertexData.applyToMesh(cylinder, updatable);
  11373. return cylinder;
  11374. };
  11375. // Torus (Code from SharpDX.org)
  11376. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  11377. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11378. var torus = new Mesh(name, scene);
  11379. var vertexData = BABYLON.VertexData.CreateTorus(diameter, thickness, tessellation, sideOrientation);
  11380. vertexData.applyToMesh(torus, updatable);
  11381. return torus;
  11382. };
  11383. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  11384. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11385. var torusKnot = new Mesh(name, scene);
  11386. var vertexData = BABYLON.VertexData.CreateTorusKnot(radius, tube, radialSegments, tubularSegments, p, q, sideOrientation);
  11387. vertexData.applyToMesh(torusKnot, updatable);
  11388. return torusKnot;
  11389. };
  11390. // Lines
  11391. Mesh.CreateLines = function (name, points, scene, updatable) {
  11392. var lines = new BABYLON.LinesMesh(name, scene, updatable);
  11393. var vertexData = BABYLON.VertexData.CreateLines(points);
  11394. vertexData.applyToMesh(lines, updatable);
  11395. return lines;
  11396. };
  11397. // Extrusion
  11398. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, scene, updatable, sideOrientation) {
  11399. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11400. scale = scale || 1;
  11401. rotation = rotation || 0;
  11402. var extruded = Mesh._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, false, scene, updatable, sideOrientation);
  11403. return extruded;
  11404. };
  11405. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, scene, updatable, sideOrientation) {
  11406. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11407. var extrudedCustom = Mesh._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, true, scene, updatable, sideOrientation);
  11408. return extrudedCustom;
  11409. };
  11410. Mesh._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotationFunction, rbCA, rbCP, custom, scene, updtbl, side) {
  11411. var path3D = new BABYLON.Path3D(curve);
  11412. var shapePaths = [];
  11413. var extrudedGeneric = Mesh.CreateRibbon(name, shapePaths, rbCA, rbCP, 0, scene, updtbl, side);
  11414. return extrudedGeneric;
  11415. };
  11416. // Plane & ground
  11417. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  11418. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11419. var plane = new Mesh(name, scene);
  11420. var vertexData = BABYLON.VertexData.CreatePlane(size, sideOrientation);
  11421. vertexData.applyToMesh(plane, updatable);
  11422. return plane;
  11423. };
  11424. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  11425. var ground = new BABYLON.GroundMesh(name, scene);
  11426. ground._setReady(false);
  11427. ground._subdivisions = subdivisions;
  11428. var vertexData = BABYLON.VertexData.CreateGround(width, height, subdivisions);
  11429. vertexData.applyToMesh(ground, updatable);
  11430. ground._setReady(true);
  11431. return ground;
  11432. };
  11433. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  11434. var tiledGround = new Mesh(name, scene);
  11435. var vertexData = BABYLON.VertexData.CreateTiledGround(xmin, zmin, xmax, zmax, subdivisions, precision);
  11436. vertexData.applyToMesh(tiledGround, updatable);
  11437. return tiledGround;
  11438. };
  11439. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  11440. var ground = new BABYLON.GroundMesh(name, scene);
  11441. ground._subdivisions = subdivisions;
  11442. ground._setReady(false);
  11443. var onload = function (img) {
  11444. // Getting height map data
  11445. var canvas = document.createElement("canvas");
  11446. var context = canvas.getContext("2d");
  11447. var heightMapWidth = img.width;
  11448. var heightMapHeight = img.height;
  11449. canvas.width = heightMapWidth;
  11450. canvas.height = heightMapHeight;
  11451. context.drawImage(img, 0, 0);
  11452. // Create VertexData from map data
  11453. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  11454. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  11455. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap(width, height, subdivisions, minHeight, maxHeight, buffer, heightMapWidth, heightMapHeight);
  11456. vertexData.applyToMesh(ground, updatable);
  11457. ground._setReady(true);
  11458. //execute ready callback, if set
  11459. if (onReady) {
  11460. onReady(ground);
  11461. }
  11462. };
  11463. BABYLON.Tools.LoadImage(url, onload, function () {
  11464. }, scene.database);
  11465. return ground;
  11466. };
  11467. Mesh.CreateTube = function (name, path, radius, tesselation, radiusFunction, scene, updatable, sideOrientation) {
  11468. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11469. var path3D = new BABYLON.Path3D(path);
  11470. var tangents = path3D.getTangents();
  11471. var normals = path3D.getNormals();
  11472. var distances = path3D.getDistances();
  11473. var pi2 = Math.PI * 2;
  11474. var step = pi2 / tesselation;
  11475. var returnRadius = function (i, distance) { return radius; };
  11476. var radiusFunctionFinal = radiusFunction || returnRadius;
  11477. var circlePaths = new Array();
  11478. var circlePath;
  11479. var rad;
  11480. var normal;
  11481. var rotated;
  11482. var rotationMatrix;
  11483. for (var i = 0; i < path.length; i++) {
  11484. rad = radiusFunctionFinal(i, distances[i]); // current radius
  11485. circlePath = Array(); // current circle array
  11486. normal = normals[i]; // current normal
  11487. for (var ang = 0; ang < pi2; ang += step) {
  11488. rotationMatrix = BABYLON.Matrix.RotationAxis(tangents[i], ang);
  11489. rotated = BABYLON.Vector3.TransformCoordinates(normal, rotationMatrix).scaleInPlace(rad).add(path[i]);
  11490. circlePath.push(rotated);
  11491. }
  11492. circlePaths.push(circlePath);
  11493. }
  11494. var tube = Mesh.CreateRibbon(name, circlePaths, false, true, 0, scene, updatable, sideOrientation);
  11495. return tube;
  11496. };
  11497. // Tools
  11498. Mesh.MinMax = function (meshes) {
  11499. var minVector = null;
  11500. var maxVector = null;
  11501. for (var i in meshes) {
  11502. var mesh = meshes[i];
  11503. var boundingBox = mesh.getBoundingInfo().boundingBox;
  11504. if (!minVector) {
  11505. minVector = boundingBox.minimumWorld;
  11506. maxVector = boundingBox.maximumWorld;
  11507. continue;
  11508. }
  11509. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  11510. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  11511. }
  11512. return {
  11513. min: minVector,
  11514. max: maxVector
  11515. };
  11516. };
  11517. Mesh.Center = function (meshesOrMinMaxVector) {
  11518. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  11519. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  11520. };
  11521. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices) {
  11522. if (disposeSource === void 0) { disposeSource = true; }
  11523. var source = meshes[0];
  11524. var material = source.material;
  11525. var scene = source.getScene();
  11526. if (!allow32BitsIndices) {
  11527. var totalVertices = 0;
  11528. for (var index = 0; index < meshes.length; index++) {
  11529. totalVertices += meshes[index].getTotalVertices();
  11530. if (totalVertices > 65536) {
  11531. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  11532. return null;
  11533. }
  11534. }
  11535. }
  11536. // Merge
  11537. var vertexData = BABYLON.VertexData.ExtractFromMesh(source);
  11538. vertexData.transform(source.getWorldMatrix());
  11539. for (index = 1; index < meshes.length; index++) {
  11540. var otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index]);
  11541. otherVertexData.transform(meshes[index].getWorldMatrix());
  11542. vertexData.merge(otherVertexData);
  11543. }
  11544. var newMesh = new Mesh(source.name + "_merged", scene);
  11545. vertexData.applyToMesh(newMesh);
  11546. // Setting properties
  11547. newMesh.material = material;
  11548. newMesh.checkCollisions = source.checkCollisions;
  11549. // Cleaning
  11550. if (disposeSource) {
  11551. for (index = 0; index < meshes.length; index++) {
  11552. meshes[index].dispose();
  11553. }
  11554. }
  11555. return newMesh;
  11556. };
  11557. // Consts
  11558. Mesh._FRONTSIDE = 0;
  11559. Mesh._BACKSIDE = 1;
  11560. Mesh._DOUBLESIDE = 2;
  11561. Mesh._DEFAULTSIDE = 0;
  11562. return Mesh;
  11563. })(BABYLON.AbstractMesh);
  11564. BABYLON.Mesh = Mesh;
  11565. })(BABYLON || (BABYLON = {}));
  11566. //# sourceMappingURL=babylon.mesh.js.map
  11567. var BABYLON;
  11568. (function (BABYLON) {
  11569. var GroundMesh = (function (_super) {
  11570. __extends(GroundMesh, _super);
  11571. function GroundMesh(name, scene) {
  11572. _super.call(this, name, scene);
  11573. this.generateOctree = false;
  11574. this._worldInverse = new BABYLON.Matrix();
  11575. }
  11576. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  11577. get: function () {
  11578. return this._subdivisions;
  11579. },
  11580. enumerable: true,
  11581. configurable: true
  11582. });
  11583. GroundMesh.prototype.optimize = function (chunksCount) {
  11584. this.subdivide(this._subdivisions);
  11585. this.createOrUpdateSubmeshesOctree(32);
  11586. };
  11587. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  11588. var ray = new BABYLON.Ray(new BABYLON.Vector3(x, this.getBoundingInfo().boundingBox.maximumWorld.y + 1, z), new BABYLON.Vector3(0, -1, 0));
  11589. this.getWorldMatrix().invertToRef(this._worldInverse);
  11590. ray = BABYLON.Ray.Transform(ray, this._worldInverse);
  11591. var pickInfo = this.intersects(ray);
  11592. if (pickInfo.hit) {
  11593. return pickInfo.pickedPoint.y;
  11594. }
  11595. return 0;
  11596. };
  11597. return GroundMesh;
  11598. })(BABYLON.Mesh);
  11599. BABYLON.GroundMesh = GroundMesh;
  11600. })(BABYLON || (BABYLON = {}));
  11601. //# sourceMappingURL=babylon.groundMesh.js.map
  11602. var BABYLON;
  11603. (function (BABYLON) {
  11604. /**
  11605. * Creates an instance based on a source mesh.
  11606. */
  11607. var InstancedMesh = (function (_super) {
  11608. __extends(InstancedMesh, _super);
  11609. function InstancedMesh(name, source) {
  11610. _super.call(this, name, source.getScene());
  11611. source.instances.push(this);
  11612. this._sourceMesh = source;
  11613. this.position.copyFrom(source.position);
  11614. this.rotation.copyFrom(source.rotation);
  11615. this.scaling.copyFrom(source.scaling);
  11616. if (source.rotationQuaternion) {
  11617. this.rotationQuaternion = source.rotationQuaternion.clone();
  11618. }
  11619. this.infiniteDistance = source.infiniteDistance;
  11620. this.setPivotMatrix(source.getPivotMatrix());
  11621. this.refreshBoundingInfo();
  11622. this._syncSubMeshes();
  11623. }
  11624. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  11625. // Methods
  11626. get: function () {
  11627. return this._sourceMesh.receiveShadows;
  11628. },
  11629. enumerable: true,
  11630. configurable: true
  11631. });
  11632. Object.defineProperty(InstancedMesh.prototype, "material", {
  11633. get: function () {
  11634. return this._sourceMesh.material;
  11635. },
  11636. enumerable: true,
  11637. configurable: true
  11638. });
  11639. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  11640. get: function () {
  11641. return this._sourceMesh.visibility;
  11642. },
  11643. enumerable: true,
  11644. configurable: true
  11645. });
  11646. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  11647. get: function () {
  11648. return this._sourceMesh.skeleton;
  11649. },
  11650. enumerable: true,
  11651. configurable: true
  11652. });
  11653. InstancedMesh.prototype.getTotalVertices = function () {
  11654. return this._sourceMesh.getTotalVertices();
  11655. };
  11656. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  11657. get: function () {
  11658. return this._sourceMesh;
  11659. },
  11660. enumerable: true,
  11661. configurable: true
  11662. });
  11663. InstancedMesh.prototype.getVerticesData = function (kind) {
  11664. return this._sourceMesh.getVerticesData(kind);
  11665. };
  11666. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  11667. return this._sourceMesh.isVerticesDataPresent(kind);
  11668. };
  11669. InstancedMesh.prototype.getIndices = function () {
  11670. return this._sourceMesh.getIndices();
  11671. };
  11672. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  11673. get: function () {
  11674. return this._sourceMesh._positions;
  11675. },
  11676. enumerable: true,
  11677. configurable: true
  11678. });
  11679. InstancedMesh.prototype.refreshBoundingInfo = function () {
  11680. var data = this._sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11681. if (data) {
  11682. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._sourceMesh.getTotalVertices());
  11683. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  11684. }
  11685. this._updateBoundingInfo();
  11686. };
  11687. InstancedMesh.prototype._preActivate = function () {
  11688. if (this._currentLOD) {
  11689. this._currentLOD._preActivate();
  11690. }
  11691. };
  11692. InstancedMesh.prototype._activate = function (renderId) {
  11693. if (this._currentLOD) {
  11694. this._currentLOD._registerInstanceForRenderId(this, renderId);
  11695. }
  11696. };
  11697. InstancedMesh.prototype.getLOD = function (camera) {
  11698. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  11699. if (this._currentLOD === this.sourceMesh) {
  11700. return this;
  11701. }
  11702. return this._currentLOD;
  11703. };
  11704. InstancedMesh.prototype._syncSubMeshes = function () {
  11705. this.releaseSubMeshes();
  11706. if (this._sourceMesh.subMeshes) {
  11707. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  11708. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  11709. }
  11710. }
  11711. };
  11712. InstancedMesh.prototype._generatePointsArray = function () {
  11713. return this._sourceMesh._generatePointsArray();
  11714. };
  11715. // Clone
  11716. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  11717. var result = this._sourceMesh.createInstance(name);
  11718. // Deep copy
  11719. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  11720. // Bounding info
  11721. this.refreshBoundingInfo();
  11722. // Parent
  11723. if (newParent) {
  11724. result.parent = newParent;
  11725. }
  11726. if (!doNotCloneChildren) {
  11727. for (var index = 0; index < this.getScene().meshes.length; index++) {
  11728. var mesh = this.getScene().meshes[index];
  11729. if (mesh.parent === this) {
  11730. mesh.clone(mesh.name, result);
  11731. }
  11732. }
  11733. }
  11734. result.computeWorldMatrix(true);
  11735. return result;
  11736. };
  11737. // Dispoe
  11738. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  11739. // Remove from mesh
  11740. var index = this._sourceMesh.instances.indexOf(this);
  11741. this._sourceMesh.instances.splice(index, 1);
  11742. _super.prototype.dispose.call(this, doNotRecurse);
  11743. };
  11744. return InstancedMesh;
  11745. })(BABYLON.AbstractMesh);
  11746. BABYLON.InstancedMesh = InstancedMesh;
  11747. })(BABYLON || (BABYLON = {}));
  11748. //# sourceMappingURL=babylon.instancedMesh.js.mapvar BABYLON;
  11749. (function (BABYLON) {
  11750. var SubMesh = (function () {
  11751. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  11752. if (createBoundingBox === void 0) { createBoundingBox = true; }
  11753. this.materialIndex = materialIndex;
  11754. this.verticesStart = verticesStart;
  11755. this.verticesCount = verticesCount;
  11756. this.indexStart = indexStart;
  11757. this.indexCount = indexCount;
  11758. this._renderId = 0;
  11759. this._mesh = mesh;
  11760. this._renderingMesh = renderingMesh || mesh;
  11761. mesh.subMeshes.push(this);
  11762. this._id = mesh.subMeshes.length - 1;
  11763. if (createBoundingBox) {
  11764. this.refreshBoundingInfo();
  11765. }
  11766. }
  11767. SubMesh.prototype.getBoundingInfo = function () {
  11768. return this._boundingInfo;
  11769. };
  11770. SubMesh.prototype.getMesh = function () {
  11771. return this._mesh;
  11772. };
  11773. SubMesh.prototype.getRenderingMesh = function () {
  11774. return this._renderingMesh;
  11775. };
  11776. SubMesh.prototype.getMaterial = function () {
  11777. var rootMaterial = this._renderingMesh.material;
  11778. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  11779. var multiMaterial = rootMaterial;
  11780. return multiMaterial.getSubMaterial(this.materialIndex);
  11781. }
  11782. if (!rootMaterial) {
  11783. return this._mesh.getScene().defaultMaterial;
  11784. }
  11785. return rootMaterial;
  11786. };
  11787. // Methods
  11788. SubMesh.prototype.refreshBoundingInfo = function () {
  11789. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11790. if (!data) {
  11791. this._boundingInfo = this._mesh._boundingInfo;
  11792. return;
  11793. }
  11794. var indices = this._renderingMesh.getIndices();
  11795. var extend;
  11796. if (this.indexStart === 0 && this.indexCount === indices.length) {
  11797. extend = BABYLON.Tools.ExtractMinAndMax(data, this.verticesStart, this.verticesCount);
  11798. }
  11799. else {
  11800. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
  11801. }
  11802. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  11803. };
  11804. SubMesh.prototype._checkCollision = function (collider) {
  11805. return this._boundingInfo._checkCollision(collider);
  11806. };
  11807. SubMesh.prototype.updateBoundingInfo = function (world) {
  11808. if (!this._boundingInfo) {
  11809. this.refreshBoundingInfo();
  11810. }
  11811. this._boundingInfo._update(world);
  11812. };
  11813. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  11814. return this._boundingInfo.isInFrustum(frustumPlanes);
  11815. };
  11816. SubMesh.prototype.render = function () {
  11817. this._renderingMesh.render(this);
  11818. };
  11819. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  11820. if (!this._linesIndexBuffer) {
  11821. var linesIndices = [];
  11822. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  11823. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  11824. }
  11825. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  11826. this.linesIndexCount = linesIndices.length;
  11827. }
  11828. return this._linesIndexBuffer;
  11829. };
  11830. SubMesh.prototype.canIntersects = function (ray) {
  11831. return ray.intersectsBox(this._boundingInfo.boundingBox);
  11832. };
  11833. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  11834. var intersectInfo = null;
  11835. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  11836. var p0 = positions[indices[index]];
  11837. var p1 = positions[indices[index + 1]];
  11838. var p2 = positions[indices[index + 2]];
  11839. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  11840. if (currentIntersectInfo) {
  11841. if (currentIntersectInfo.distance < 0) {
  11842. continue;
  11843. }
  11844. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  11845. intersectInfo = currentIntersectInfo;
  11846. intersectInfo.faceId = index / 3;
  11847. if (fastCheck) {
  11848. break;
  11849. }
  11850. }
  11851. }
  11852. }
  11853. return intersectInfo;
  11854. };
  11855. // Clone
  11856. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  11857. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  11858. result._boundingInfo = new BABYLON.BoundingInfo(this._boundingInfo.minimum, this._boundingInfo.maximum);
  11859. return result;
  11860. };
  11861. // Dispose
  11862. SubMesh.prototype.dispose = function () {
  11863. if (this._linesIndexBuffer) {
  11864. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  11865. this._linesIndexBuffer = null;
  11866. }
  11867. // Remove from mesh
  11868. var index = this._mesh.subMeshes.indexOf(this);
  11869. this._mesh.subMeshes.splice(index, 1);
  11870. };
  11871. // Statics
  11872. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  11873. var minVertexIndex = Number.MAX_VALUE;
  11874. var maxVertexIndex = -Number.MAX_VALUE;
  11875. renderingMesh = renderingMesh || mesh;
  11876. var indices = renderingMesh.getIndices();
  11877. for (var index = startIndex; index < startIndex + indexCount; index++) {
  11878. var vertexIndex = indices[index];
  11879. if (vertexIndex < minVertexIndex)
  11880. minVertexIndex = vertexIndex;
  11881. if (vertexIndex > maxVertexIndex)
  11882. maxVertexIndex = vertexIndex;
  11883. }
  11884. return new BABYLON.SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  11885. };
  11886. return SubMesh;
  11887. })();
  11888. BABYLON.SubMesh = SubMesh;
  11889. })(BABYLON || (BABYLON = {}));
  11890. //# sourceMappingURL=babylon.subMesh.js.mapvar BABYLON;
  11891. (function (BABYLON) {
  11892. var BaseTexture = (function () {
  11893. function BaseTexture(scene) {
  11894. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  11895. this.hasAlpha = false;
  11896. this.getAlphaFromRGB = false;
  11897. this.level = 1;
  11898. this.isCube = false;
  11899. this.isRenderTarget = false;
  11900. this.animations = new Array();
  11901. this.coordinatesIndex = 0;
  11902. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  11903. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  11904. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  11905. this.anisotropicFilteringLevel = 4;
  11906. this._scene = scene;
  11907. this._scene.textures.push(this);
  11908. }
  11909. BaseTexture.prototype.getScene = function () {
  11910. return this._scene;
  11911. };
  11912. BaseTexture.prototype.getTextureMatrix = function () {
  11913. return null;
  11914. };
  11915. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  11916. return null;
  11917. };
  11918. BaseTexture.prototype.getInternalTexture = function () {
  11919. return this._texture;
  11920. };
  11921. BaseTexture.prototype.isReady = function () {
  11922. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  11923. return true;
  11924. }
  11925. if (this._texture) {
  11926. return this._texture.isReady;
  11927. }
  11928. return false;
  11929. };
  11930. BaseTexture.prototype.getSize = function () {
  11931. if (this._texture._width) {
  11932. return { width: this._texture._width, height: this._texture._height };
  11933. }
  11934. if (this._texture._size) {
  11935. return { width: this._texture._size, height: this._texture._size };
  11936. }
  11937. return { width: 0, height: 0 };
  11938. };
  11939. BaseTexture.prototype.getBaseSize = function () {
  11940. if (!this.isReady())
  11941. return { width: 0, height: 0 };
  11942. if (this._texture._size) {
  11943. return { width: this._texture._size, height: this._texture._size };
  11944. }
  11945. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  11946. };
  11947. BaseTexture.prototype.scale = function (ratio) {
  11948. };
  11949. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  11950. get: function () {
  11951. return false;
  11952. },
  11953. enumerable: true,
  11954. configurable: true
  11955. });
  11956. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  11957. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  11958. for (var index = 0; index < texturesCache.length; index++) {
  11959. var texturesCacheEntry = texturesCache[index];
  11960. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  11961. texturesCache.splice(index, 1);
  11962. return;
  11963. }
  11964. }
  11965. };
  11966. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  11967. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  11968. for (var index = 0; index < texturesCache.length; index++) {
  11969. var texturesCacheEntry = texturesCache[index];
  11970. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  11971. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  11972. texturesCacheEntry.references++;
  11973. return texturesCacheEntry;
  11974. }
  11975. }
  11976. }
  11977. return null;
  11978. };
  11979. BaseTexture.prototype.delayLoad = function () {
  11980. };
  11981. BaseTexture.prototype.releaseInternalTexture = function () {
  11982. if (!this._texture) {
  11983. return;
  11984. }
  11985. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  11986. this._texture.references--;
  11987. // Final reference ?
  11988. if (this._texture.references === 0) {
  11989. var index = texturesCache.indexOf(this._texture);
  11990. texturesCache.splice(index, 1);
  11991. this._scene.getEngine()._releaseTexture(this._texture);
  11992. delete this._texture;
  11993. }
  11994. };
  11995. BaseTexture.prototype.clone = function () {
  11996. return null;
  11997. };
  11998. BaseTexture.prototype.dispose = function () {
  11999. // Remove from scene
  12000. var index = this._scene.textures.indexOf(this);
  12001. if (index >= 0) {
  12002. this._scene.textures.splice(index, 1);
  12003. }
  12004. if (this._texture === undefined) {
  12005. return;
  12006. }
  12007. this.releaseInternalTexture();
  12008. // Callback
  12009. if (this.onDispose) {
  12010. this.onDispose();
  12011. }
  12012. };
  12013. return BaseTexture;
  12014. })();
  12015. BABYLON.BaseTexture = BaseTexture;
  12016. })(BABYLON || (BABYLON = {}));
  12017. //# sourceMappingURL=babylon.baseTexture.js.mapvar BABYLON;
  12018. (function (BABYLON) {
  12019. var RenderingGroup = (function () {
  12020. function RenderingGroup(index, scene) {
  12021. this.index = index;
  12022. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  12023. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  12024. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  12025. this._scene = scene;
  12026. }
  12027. RenderingGroup.prototype.render = function (customRenderFunction) {
  12028. if (customRenderFunction) {
  12029. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  12030. return true;
  12031. }
  12032. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  12033. return false;
  12034. }
  12035. var engine = this._scene.getEngine();
  12036. // Opaque
  12037. var subIndex;
  12038. var submesh;
  12039. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  12040. submesh = this._opaqueSubMeshes.data[subIndex];
  12041. submesh.render();
  12042. }
  12043. // Alpha test
  12044. engine.setAlphaTesting(true);
  12045. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  12046. submesh = this._alphaTestSubMeshes.data[subIndex];
  12047. submesh.render();
  12048. }
  12049. engine.setAlphaTesting(false);
  12050. // Transparent
  12051. if (this._transparentSubMeshes.length) {
  12052. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  12053. submesh = this._transparentSubMeshes.data[subIndex];
  12054. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  12055. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.position).length();
  12056. }
  12057. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  12058. sortedArray.sort(function (a, b) {
  12059. // Alpha index first
  12060. if (a._alphaIndex > b._alphaIndex) {
  12061. return 1;
  12062. }
  12063. if (a._alphaIndex < b._alphaIndex) {
  12064. return -1;
  12065. }
  12066. // Then distance to camera
  12067. if (a._distanceToCamera < b._distanceToCamera) {
  12068. return 1;
  12069. }
  12070. if (a._distanceToCamera > b._distanceToCamera) {
  12071. return -1;
  12072. }
  12073. return 0;
  12074. });
  12075. // Rendering
  12076. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  12077. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  12078. submesh = sortedArray[subIndex];
  12079. submesh.render();
  12080. }
  12081. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  12082. }
  12083. return true;
  12084. };
  12085. RenderingGroup.prototype.prepare = function () {
  12086. this._opaqueSubMeshes.reset();
  12087. this._transparentSubMeshes.reset();
  12088. this._alphaTestSubMeshes.reset();
  12089. };
  12090. RenderingGroup.prototype.dispatch = function (subMesh) {
  12091. var material = subMesh.getMaterial();
  12092. var mesh = subMesh.getMesh();
  12093. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  12094. this._transparentSubMeshes.push(subMesh);
  12095. }
  12096. else if (material.needAlphaTesting()) {
  12097. this._alphaTestSubMeshes.push(subMesh);
  12098. }
  12099. else {
  12100. this._opaqueSubMeshes.push(subMesh); // Opaque
  12101. }
  12102. };
  12103. return RenderingGroup;
  12104. })();
  12105. BABYLON.RenderingGroup = RenderingGroup;
  12106. })(BABYLON || (BABYLON = {}));
  12107. //# sourceMappingURL=babylon.renderingGroup.js.mapvar BABYLON;
  12108. (function (BABYLON) {
  12109. var RenderingManager = (function () {
  12110. function RenderingManager(scene) {
  12111. this._renderingGroups = new Array();
  12112. this._scene = scene;
  12113. }
  12114. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  12115. if (this._scene._activeParticleSystems.length === 0) {
  12116. return;
  12117. }
  12118. // Particles
  12119. var beforeParticlesDate = BABYLON.Tools.Now;
  12120. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  12121. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  12122. if (particleSystem.renderingGroupId !== index) {
  12123. continue;
  12124. }
  12125. this._clearDepthBuffer();
  12126. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  12127. this._scene._activeParticles += particleSystem.render();
  12128. }
  12129. }
  12130. this._scene._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  12131. };
  12132. RenderingManager.prototype._renderSprites = function (index) {
  12133. if (!this._scene.spritesEnabled || this._scene.spriteManagers.length === 0) {
  12134. return;
  12135. }
  12136. // Sprites
  12137. var beforeSpritessDate = BABYLON.Tools.Now;
  12138. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  12139. var spriteManager = this._scene.spriteManagers[id];
  12140. if (spriteManager.renderingGroupId === index) {
  12141. this._clearDepthBuffer();
  12142. spriteManager.render();
  12143. }
  12144. }
  12145. this._scene._spritesDuration += BABYLON.Tools.Now - beforeSpritessDate;
  12146. };
  12147. RenderingManager.prototype._clearDepthBuffer = function () {
  12148. if (this._depthBufferAlreadyCleaned) {
  12149. return;
  12150. }
  12151. this._scene.getEngine().clear(0, false, true);
  12152. this._depthBufferAlreadyCleaned = true;
  12153. };
  12154. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  12155. for (var index = 0; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  12156. this._depthBufferAlreadyCleaned = false;
  12157. var renderingGroup = this._renderingGroups[index];
  12158. var needToStepBack = false;
  12159. if (renderingGroup) {
  12160. this._clearDepthBuffer();
  12161. if (!renderingGroup.render(customRenderFunction)) {
  12162. this._renderingGroups.splice(index, 1);
  12163. needToStepBack = true;
  12164. }
  12165. }
  12166. if (renderSprites) {
  12167. this._renderSprites(index);
  12168. }
  12169. if (renderParticles) {
  12170. this._renderParticles(index, activeMeshes);
  12171. }
  12172. if (needToStepBack) {
  12173. index--;
  12174. }
  12175. }
  12176. };
  12177. RenderingManager.prototype.reset = function () {
  12178. for (var index in this._renderingGroups) {
  12179. var renderingGroup = this._renderingGroups[index];
  12180. renderingGroup.prepare();
  12181. }
  12182. };
  12183. RenderingManager.prototype.dispatch = function (subMesh) {
  12184. var mesh = subMesh.getMesh();
  12185. var renderingGroupId = mesh.renderingGroupId || 0;
  12186. if (!this._renderingGroups[renderingGroupId]) {
  12187. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  12188. }
  12189. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  12190. };
  12191. RenderingManager.MAX_RENDERINGGROUPS = 4;
  12192. return RenderingManager;
  12193. })();
  12194. BABYLON.RenderingManager = RenderingManager;
  12195. })(BABYLON || (BABYLON = {}));
  12196. //# sourceMappingURL=babylon.renderingManager.js.map
  12197. var BABYLON;
  12198. (function (BABYLON) {
  12199. var Texture = (function (_super) {
  12200. __extends(Texture, _super);
  12201. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  12202. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  12203. if (onLoad === void 0) { onLoad = null; }
  12204. if (onError === void 0) { onError = null; }
  12205. if (buffer === void 0) { buffer = null; }
  12206. if (deleteBuffer === void 0) { deleteBuffer = false; }
  12207. _super.call(this, scene);
  12208. this.uOffset = 0;
  12209. this.vOffset = 0;
  12210. this.uScale = 1.0;
  12211. this.vScale = 1.0;
  12212. this.uAng = 0;
  12213. this.vAng = 0;
  12214. this.wAng = 0;
  12215. this.name = url;
  12216. this.url = url;
  12217. this._noMipmap = noMipmap;
  12218. this._invertY = invertY;
  12219. this._samplingMode = samplingMode;
  12220. this._buffer = buffer;
  12221. this._deleteBuffer = deleteBuffer;
  12222. if (!url) {
  12223. return;
  12224. }
  12225. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  12226. if (!this._texture) {
  12227. if (!scene.useDelayedTextureLoading) {
  12228. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  12229. if (deleteBuffer) {
  12230. delete this._buffer;
  12231. }
  12232. }
  12233. else {
  12234. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  12235. }
  12236. }
  12237. }
  12238. Texture.prototype.delayLoad = function () {
  12239. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  12240. return;
  12241. }
  12242. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  12243. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  12244. if (!this._texture) {
  12245. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, null, null, this._buffer);
  12246. if (this._deleteBuffer) {
  12247. delete this._buffer;
  12248. }
  12249. }
  12250. };
  12251. Texture.prototype.updateSamplingMode = function (samplingMode) {
  12252. if (!this._texture) {
  12253. return;
  12254. }
  12255. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  12256. };
  12257. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  12258. x -= this.uOffset + 0.5;
  12259. y -= this.vOffset + 0.5;
  12260. z -= 0.5;
  12261. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  12262. t.x *= this.uScale;
  12263. t.y *= this.vScale;
  12264. t.x += 0.5;
  12265. t.y += 0.5;
  12266. t.z += 0.5;
  12267. };
  12268. Texture.prototype.getTextureMatrix = function () {
  12269. 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) {
  12270. return this._cachedTextureMatrix;
  12271. }
  12272. this._cachedUOffset = this.uOffset;
  12273. this._cachedVOffset = this.vOffset;
  12274. this._cachedUScale = this.uScale;
  12275. this._cachedVScale = this.vScale;
  12276. this._cachedUAng = this.uAng;
  12277. this._cachedVAng = this.vAng;
  12278. this._cachedWAng = this.wAng;
  12279. if (!this._cachedTextureMatrix) {
  12280. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  12281. this._rowGenerationMatrix = new BABYLON.Matrix();
  12282. this._t0 = BABYLON.Vector3.Zero();
  12283. this._t1 = BABYLON.Vector3.Zero();
  12284. this._t2 = BABYLON.Vector3.Zero();
  12285. }
  12286. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  12287. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  12288. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  12289. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  12290. this._t1.subtractInPlace(this._t0);
  12291. this._t2.subtractInPlace(this._t0);
  12292. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  12293. this._cachedTextureMatrix.m[0] = this._t1.x;
  12294. this._cachedTextureMatrix.m[1] = this._t1.y;
  12295. this._cachedTextureMatrix.m[2] = this._t1.z;
  12296. this._cachedTextureMatrix.m[4] = this._t2.x;
  12297. this._cachedTextureMatrix.m[5] = this._t2.y;
  12298. this._cachedTextureMatrix.m[6] = this._t2.z;
  12299. this._cachedTextureMatrix.m[8] = this._t0.x;
  12300. this._cachedTextureMatrix.m[9] = this._t0.y;
  12301. this._cachedTextureMatrix.m[10] = this._t0.z;
  12302. return this._cachedTextureMatrix;
  12303. };
  12304. Texture.prototype.getReflectionTextureMatrix = function () {
  12305. if (this.uOffset === this._cachedUOffset && this.vOffset === this._cachedVOffset && this.uScale === this._cachedUScale && this.vScale === this._cachedVScale && this.coordinatesMode === this._cachedCoordinatesMode) {
  12306. return this._cachedTextureMatrix;
  12307. }
  12308. if (!this._cachedTextureMatrix) {
  12309. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  12310. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  12311. }
  12312. this._cachedCoordinatesMode = this.coordinatesMode;
  12313. switch (this.coordinatesMode) {
  12314. case Texture.SPHERICAL_MODE:
  12315. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  12316. this._cachedTextureMatrix[0] = -0.5 * this.uScale;
  12317. this._cachedTextureMatrix[5] = -0.5 * this.vScale;
  12318. this._cachedTextureMatrix[12] = 0.5 + this.uOffset;
  12319. this._cachedTextureMatrix[13] = 0.5 + this.vOffset;
  12320. break;
  12321. case Texture.PLANAR_MODE:
  12322. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  12323. this._cachedTextureMatrix[0] = this.uScale;
  12324. this._cachedTextureMatrix[5] = this.vScale;
  12325. this._cachedTextureMatrix[12] = this.uOffset;
  12326. this._cachedTextureMatrix[13] = this.vOffset;
  12327. break;
  12328. case Texture.PROJECTION_MODE:
  12329. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  12330. this._projectionModeMatrix.m[0] = 0.5;
  12331. this._projectionModeMatrix.m[5] = -0.5;
  12332. this._projectionModeMatrix.m[10] = 0.0;
  12333. this._projectionModeMatrix.m[12] = 0.5;
  12334. this._projectionModeMatrix.m[13] = 0.5;
  12335. this._projectionModeMatrix.m[14] = 1.0;
  12336. this._projectionModeMatrix.m[15] = 1.0;
  12337. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  12338. break;
  12339. default:
  12340. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  12341. break;
  12342. }
  12343. return this._cachedTextureMatrix;
  12344. };
  12345. Texture.prototype.clone = function () {
  12346. var newTexture = new Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY, this._samplingMode);
  12347. // Base texture
  12348. newTexture.hasAlpha = this.hasAlpha;
  12349. newTexture.level = this.level;
  12350. newTexture.wrapU = this.wrapU;
  12351. newTexture.wrapV = this.wrapV;
  12352. newTexture.coordinatesIndex = this.coordinatesIndex;
  12353. newTexture.coordinatesMode = this.coordinatesMode;
  12354. // Texture
  12355. newTexture.uOffset = this.uOffset;
  12356. newTexture.vOffset = this.vOffset;
  12357. newTexture.uScale = this.uScale;
  12358. newTexture.vScale = this.vScale;
  12359. newTexture.uAng = this.uAng;
  12360. newTexture.vAng = this.vAng;
  12361. newTexture.wAng = this.wAng;
  12362. return newTexture;
  12363. };
  12364. // Statics
  12365. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  12366. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  12367. if (onLoad === void 0) { onLoad = null; }
  12368. if (onError === void 0) { onError = null; }
  12369. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  12370. };
  12371. // Constants
  12372. Texture.NEAREST_SAMPLINGMODE = 1;
  12373. Texture.BILINEAR_SAMPLINGMODE = 2;
  12374. Texture.TRILINEAR_SAMPLINGMODE = 3;
  12375. Texture.EXPLICIT_MODE = 0;
  12376. Texture.SPHERICAL_MODE = 1;
  12377. Texture.PLANAR_MODE = 2;
  12378. Texture.CUBIC_MODE = 3;
  12379. Texture.PROJECTION_MODE = 4;
  12380. Texture.SKYBOX_MODE = 5;
  12381. Texture.CLAMP_ADDRESSMODE = 0;
  12382. Texture.WRAP_ADDRESSMODE = 1;
  12383. Texture.MIRROR_ADDRESSMODE = 2;
  12384. return Texture;
  12385. })(BABYLON.BaseTexture);
  12386. BABYLON.Texture = Texture;
  12387. })(BABYLON || (BABYLON = {}));
  12388. //# sourceMappingURL=babylon.texture.js.map
  12389. var BABYLON;
  12390. (function (BABYLON) {
  12391. var CubeTexture = (function (_super) {
  12392. __extends(CubeTexture, _super);
  12393. function CubeTexture(rootUrl, scene, extensions, noMipmap) {
  12394. _super.call(this, scene);
  12395. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  12396. this.name = rootUrl;
  12397. this.url = rootUrl;
  12398. this._noMipmap = noMipmap;
  12399. this.hasAlpha = false;
  12400. this._texture = this._getFromCache(rootUrl, noMipmap);
  12401. if (!extensions) {
  12402. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  12403. }
  12404. this._extensions = extensions;
  12405. if (!this._texture) {
  12406. if (!scene.useDelayedTextureLoading) {
  12407. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, extensions, noMipmap);
  12408. }
  12409. else {
  12410. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  12411. }
  12412. }
  12413. this.isCube = true;
  12414. this._textureMatrix = BABYLON.Matrix.Identity();
  12415. }
  12416. CubeTexture.prototype.clone = function () {
  12417. var newTexture = new CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap);
  12418. // Base texture
  12419. newTexture.level = this.level;
  12420. newTexture.wrapU = this.wrapU;
  12421. newTexture.wrapV = this.wrapV;
  12422. newTexture.coordinatesIndex = this.coordinatesIndex;
  12423. newTexture.coordinatesMode = this.coordinatesMode;
  12424. return newTexture;
  12425. };
  12426. // Methods
  12427. CubeTexture.prototype.delayLoad = function () {
  12428. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  12429. return;
  12430. }
  12431. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  12432. this._texture = this._getFromCache(this.url, this._noMipmap);
  12433. if (!this._texture) {
  12434. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  12435. }
  12436. };
  12437. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  12438. return this._textureMatrix;
  12439. };
  12440. return CubeTexture;
  12441. })(BABYLON.BaseTexture);
  12442. BABYLON.CubeTexture = CubeTexture;
  12443. })(BABYLON || (BABYLON = {}));
  12444. //# sourceMappingURL=babylon.cubeTexture.js.map
  12445. var BABYLON;
  12446. (function (BABYLON) {
  12447. var RenderTargetTexture = (function (_super) {
  12448. __extends(RenderTargetTexture, _super);
  12449. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type) {
  12450. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  12451. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  12452. _super.call(this, null, scene, !generateMipMaps);
  12453. this.renderList = new Array();
  12454. this.renderParticles = true;
  12455. this.renderSprites = false;
  12456. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  12457. this._currentRefreshId = -1;
  12458. this._refreshRate = 1;
  12459. this.name = name;
  12460. this.isRenderTarget = true;
  12461. this._size = size;
  12462. this._generateMipMaps = generateMipMaps;
  12463. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  12464. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, type: type });
  12465. // Rendering groups
  12466. this._renderingManager = new BABYLON.RenderingManager(scene);
  12467. }
  12468. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  12469. this._currentRefreshId = -1;
  12470. };
  12471. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  12472. get: function () {
  12473. return this._refreshRate;
  12474. },
  12475. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  12476. set: function (value) {
  12477. this._refreshRate = value;
  12478. this.resetRefreshCounter();
  12479. },
  12480. enumerable: true,
  12481. configurable: true
  12482. });
  12483. RenderTargetTexture.prototype._shouldRender = function () {
  12484. if (this._currentRefreshId === -1) {
  12485. this._currentRefreshId = 1;
  12486. return true;
  12487. }
  12488. if (this.refreshRate === this._currentRefreshId) {
  12489. this._currentRefreshId = 1;
  12490. return true;
  12491. }
  12492. this._currentRefreshId++;
  12493. return false;
  12494. };
  12495. RenderTargetTexture.prototype.isReady = function () {
  12496. if (!this.getScene().renderTargetsEnabled) {
  12497. return false;
  12498. }
  12499. return _super.prototype.isReady.call(this);
  12500. };
  12501. RenderTargetTexture.prototype.getRenderSize = function () {
  12502. return this._size;
  12503. };
  12504. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  12505. get: function () {
  12506. return true;
  12507. },
  12508. enumerable: true,
  12509. configurable: true
  12510. });
  12511. RenderTargetTexture.prototype.scale = function (ratio) {
  12512. var newSize = this._size * ratio;
  12513. this.resize(newSize, this._generateMipMaps);
  12514. };
  12515. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  12516. this.releaseInternalTexture();
  12517. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  12518. };
  12519. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  12520. var scene = this.getScene();
  12521. var engine = scene.getEngine();
  12522. if (this._waitingRenderList) {
  12523. this.renderList = [];
  12524. for (var index = 0; index < this._waitingRenderList.length; index++) {
  12525. var id = this._waitingRenderList[index];
  12526. this.renderList.push(scene.getMeshByID(id));
  12527. }
  12528. delete this._waitingRenderList;
  12529. }
  12530. if (this.renderList && this.renderList.length === 0) {
  12531. return;
  12532. }
  12533. // Bind
  12534. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  12535. engine.bindFramebuffer(this._texture);
  12536. }
  12537. this._renderingManager.reset();
  12538. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  12539. for (var meshIndex = 0; meshIndex < currentRenderList.length; meshIndex++) {
  12540. var mesh = currentRenderList[meshIndex];
  12541. if (mesh) {
  12542. if (!mesh.isReady()) {
  12543. // Reset _currentRefreshId
  12544. this.resetRefreshCounter();
  12545. continue;
  12546. }
  12547. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  12548. mesh._activate(scene.getRenderId());
  12549. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  12550. var subMesh = mesh.subMeshes[subIndex];
  12551. scene._activeVertices += subMesh.indexCount;
  12552. this._renderingManager.dispatch(subMesh);
  12553. }
  12554. }
  12555. }
  12556. }
  12557. if (this.onBeforeRender) {
  12558. this.onBeforeRender();
  12559. }
  12560. // Clear
  12561. if (this.onClear) {
  12562. this.onClear(engine);
  12563. }
  12564. else {
  12565. engine.clear(scene.clearColor, true, true);
  12566. }
  12567. if (!this._doNotChangeAspectRatio) {
  12568. scene.updateTransformMatrix(true);
  12569. }
  12570. // Render
  12571. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  12572. if (useCameraPostProcess) {
  12573. scene.postProcessManager._finalizeFrame(false, this._texture);
  12574. }
  12575. if (!this._doNotChangeAspectRatio) {
  12576. scene.updateTransformMatrix(true);
  12577. }
  12578. if (this.onAfterRender) {
  12579. this.onAfterRender();
  12580. }
  12581. // Dump ?
  12582. if (dumpForDebug) {
  12583. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  12584. }
  12585. // Unbind
  12586. engine.unBindFramebuffer(this._texture);
  12587. if (this.onAfterUnbind) {
  12588. this.onAfterUnbind();
  12589. }
  12590. };
  12591. RenderTargetTexture.prototype.clone = function () {
  12592. var textureSize = this.getSize();
  12593. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  12594. // Base texture
  12595. newTexture.hasAlpha = this.hasAlpha;
  12596. newTexture.level = this.level;
  12597. // RenderTarget Texture
  12598. newTexture.coordinatesMode = this.coordinatesMode;
  12599. newTexture.renderList = this.renderList.slice(0);
  12600. return newTexture;
  12601. };
  12602. return RenderTargetTexture;
  12603. })(BABYLON.Texture);
  12604. BABYLON.RenderTargetTexture = RenderTargetTexture;
  12605. })(BABYLON || (BABYLON = {}));
  12606. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  12607. var BABYLON;
  12608. (function (BABYLON) {
  12609. var ProceduralTexture = (function (_super) {
  12610. __extends(ProceduralTexture, _super);
  12611. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps) {
  12612. if (generateMipMaps === void 0) { generateMipMaps = true; }
  12613. _super.call(this, null, scene, !generateMipMaps);
  12614. this._currentRefreshId = -1;
  12615. this._refreshRate = 1;
  12616. this._vertexDeclaration = [2];
  12617. this._vertexStrideSize = 2 * 4;
  12618. this._uniforms = new Array();
  12619. this._samplers = new Array();
  12620. this._textures = new Array();
  12621. this._floats = new Array();
  12622. this._floatsArrays = {};
  12623. this._colors3 = new Array();
  12624. this._colors4 = new Array();
  12625. this._vectors2 = new Array();
  12626. this._vectors3 = new Array();
  12627. this._matrices = new Array();
  12628. this._fallbackTextureUsed = false;
  12629. scene._proceduralTextures.push(this);
  12630. this.name = name;
  12631. this.isRenderTarget = true;
  12632. this._size = size;
  12633. this._generateMipMaps = generateMipMaps;
  12634. this.setFragment(fragment);
  12635. this._fallbackTexture = fallbackTexture;
  12636. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  12637. // VBO
  12638. var vertices = [];
  12639. vertices.push(1, 1);
  12640. vertices.push(-1, 1);
  12641. vertices.push(-1, -1);
  12642. vertices.push(1, -1);
  12643. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  12644. // Indices
  12645. var indices = [];
  12646. indices.push(0);
  12647. indices.push(1);
  12648. indices.push(2);
  12649. indices.push(0);
  12650. indices.push(2);
  12651. indices.push(3);
  12652. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  12653. }
  12654. ProceduralTexture.prototype.reset = function () {
  12655. if (this._effect === undefined) {
  12656. return;
  12657. }
  12658. var engine = this.getScene().getEngine();
  12659. engine._releaseEffect(this._effect);
  12660. };
  12661. ProceduralTexture.prototype.isReady = function () {
  12662. var _this = this;
  12663. var engine = this.getScene().getEngine();
  12664. var shaders;
  12665. if (!this._fragment) {
  12666. return false;
  12667. }
  12668. if (this._fallbackTextureUsed) {
  12669. return true;
  12670. }
  12671. if (this._fragment.fragmentElement !== undefined) {
  12672. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  12673. }
  12674. else {
  12675. shaders = { vertex: "procedural", fragment: this._fragment };
  12676. }
  12677. this._effect = engine.createEffect(shaders, ["position"], this._uniforms, this._samplers, "", null, null, function () {
  12678. _this.releaseInternalTexture();
  12679. if (_this._fallbackTexture) {
  12680. _this._texture = _this._fallbackTexture._texture;
  12681. _this._texture.references++;
  12682. }
  12683. _this._fallbackTextureUsed = true;
  12684. });
  12685. return this._effect.isReady();
  12686. };
  12687. ProceduralTexture.prototype.resetRefreshCounter = function () {
  12688. this._currentRefreshId = -1;
  12689. };
  12690. ProceduralTexture.prototype.setFragment = function (fragment) {
  12691. this._fragment = fragment;
  12692. };
  12693. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  12694. get: function () {
  12695. return this._refreshRate;
  12696. },
  12697. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  12698. set: function (value) {
  12699. this._refreshRate = value;
  12700. this.resetRefreshCounter();
  12701. },
  12702. enumerable: true,
  12703. configurable: true
  12704. });
  12705. ProceduralTexture.prototype._shouldRender = function () {
  12706. if (!this.isReady() || !this._texture) {
  12707. return false;
  12708. }
  12709. if (this._fallbackTextureUsed) {
  12710. return false;
  12711. }
  12712. if (this._currentRefreshId === -1) {
  12713. this._currentRefreshId = 1;
  12714. return true;
  12715. }
  12716. if (this.refreshRate === this._currentRefreshId) {
  12717. this._currentRefreshId = 1;
  12718. return true;
  12719. }
  12720. this._currentRefreshId++;
  12721. return false;
  12722. };
  12723. ProceduralTexture.prototype.getRenderSize = function () {
  12724. return this._size;
  12725. };
  12726. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  12727. if (this._fallbackTextureUsed) {
  12728. return;
  12729. }
  12730. this.releaseInternalTexture();
  12731. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  12732. };
  12733. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  12734. if (this._uniforms.indexOf(uniformName) === -1) {
  12735. this._uniforms.push(uniformName);
  12736. }
  12737. };
  12738. ProceduralTexture.prototype.setTexture = function (name, texture) {
  12739. if (this._samplers.indexOf(name) === -1) {
  12740. this._samplers.push(name);
  12741. }
  12742. this._textures[name] = texture;
  12743. return this;
  12744. };
  12745. ProceduralTexture.prototype.setFloat = function (name, value) {
  12746. this._checkUniform(name);
  12747. this._floats[name] = value;
  12748. return this;
  12749. };
  12750. ProceduralTexture.prototype.setFloats = function (name, value) {
  12751. this._checkUniform(name);
  12752. this._floatsArrays[name] = value;
  12753. return this;
  12754. };
  12755. ProceduralTexture.prototype.setColor3 = function (name, value) {
  12756. this._checkUniform(name);
  12757. this._colors3[name] = value;
  12758. return this;
  12759. };
  12760. ProceduralTexture.prototype.setColor4 = function (name, value) {
  12761. this._checkUniform(name);
  12762. this._colors4[name] = value;
  12763. return this;
  12764. };
  12765. ProceduralTexture.prototype.setVector2 = function (name, value) {
  12766. this._checkUniform(name);
  12767. this._vectors2[name] = value;
  12768. return this;
  12769. };
  12770. ProceduralTexture.prototype.setVector3 = function (name, value) {
  12771. this._checkUniform(name);
  12772. this._vectors3[name] = value;
  12773. return this;
  12774. };
  12775. ProceduralTexture.prototype.setMatrix = function (name, value) {
  12776. this._checkUniform(name);
  12777. this._matrices[name] = value;
  12778. return this;
  12779. };
  12780. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  12781. var scene = this.getScene();
  12782. var engine = scene.getEngine();
  12783. engine.bindFramebuffer(this._texture);
  12784. // Clear
  12785. engine.clear(scene.clearColor, true, true);
  12786. // Render
  12787. engine.enableEffect(this._effect);
  12788. engine.setState(false);
  12789. for (var name in this._textures) {
  12790. this._effect.setTexture(name, this._textures[name]);
  12791. }
  12792. for (name in this._floats) {
  12793. this._effect.setFloat(name, this._floats[name]);
  12794. }
  12795. for (name in this._floatsArrays) {
  12796. this._effect.setArray(name, this._floatsArrays[name]);
  12797. }
  12798. for (name in this._colors3) {
  12799. this._effect.setColor3(name, this._colors3[name]);
  12800. }
  12801. for (name in this._colors4) {
  12802. var color = this._colors4[name];
  12803. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  12804. }
  12805. for (name in this._vectors2) {
  12806. this._effect.setVector2(name, this._vectors2[name]);
  12807. }
  12808. for (name in this._vectors3) {
  12809. this._effect.setVector3(name, this._vectors3[name]);
  12810. }
  12811. for (name in this._matrices) {
  12812. this._effect.setMatrix(name, this._matrices[name]);
  12813. }
  12814. // VBOs
  12815. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  12816. // Draw order
  12817. engine.draw(true, 0, 6);
  12818. // Unbind
  12819. engine.unBindFramebuffer(this._texture);
  12820. };
  12821. ProceduralTexture.prototype.clone = function () {
  12822. var textureSize = this.getSize();
  12823. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  12824. // Base texture
  12825. newTexture.hasAlpha = this.hasAlpha;
  12826. newTexture.level = this.level;
  12827. // RenderTarget Texture
  12828. newTexture.coordinatesMode = this.coordinatesMode;
  12829. return newTexture;
  12830. };
  12831. ProceduralTexture.prototype.dispose = function () {
  12832. var index = this.getScene()._proceduralTextures.indexOf(this);
  12833. if (index >= 0) {
  12834. this.getScene()._proceduralTextures.splice(index, 1);
  12835. }
  12836. _super.prototype.dispose.call(this);
  12837. };
  12838. return ProceduralTexture;
  12839. })(BABYLON.Texture);
  12840. BABYLON.ProceduralTexture = ProceduralTexture;
  12841. })(BABYLON || (BABYLON = {}));
  12842. //# sourceMappingURL=babylon.proceduralTexture.js.map
  12843. var BABYLON;
  12844. (function (BABYLON) {
  12845. var WoodProceduralTexture = (function (_super) {
  12846. __extends(WoodProceduralTexture, _super);
  12847. function WoodProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  12848. _super.call(this, name, size, "wood", scene, fallbackTexture, generateMipMaps);
  12849. this._ampScale = 100.0;
  12850. this._woodColor = new BABYLON.Color3(0.32, 0.17, 0.09);
  12851. this.updateShaderUniforms();
  12852. this.refreshRate = 0;
  12853. }
  12854. WoodProceduralTexture.prototype.updateShaderUniforms = function () {
  12855. this.setFloat("ampScale", this._ampScale);
  12856. this.setColor3("woodColor", this._woodColor);
  12857. };
  12858. Object.defineProperty(WoodProceduralTexture.prototype, "ampScale", {
  12859. get: function () {
  12860. return this._ampScale;
  12861. },
  12862. set: function (value) {
  12863. this._ampScale = value;
  12864. this.updateShaderUniforms();
  12865. },
  12866. enumerable: true,
  12867. configurable: true
  12868. });
  12869. Object.defineProperty(WoodProceduralTexture.prototype, "woodColor", {
  12870. get: function () {
  12871. return this._woodColor;
  12872. },
  12873. set: function (value) {
  12874. this._woodColor = value;
  12875. this.updateShaderUniforms();
  12876. },
  12877. enumerable: true,
  12878. configurable: true
  12879. });
  12880. return WoodProceduralTexture;
  12881. })(BABYLON.ProceduralTexture);
  12882. BABYLON.WoodProceduralTexture = WoodProceduralTexture;
  12883. var FireProceduralTexture = (function (_super) {
  12884. __extends(FireProceduralTexture, _super);
  12885. function FireProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  12886. _super.call(this, name, size, "fire", scene, fallbackTexture, generateMipMaps);
  12887. this._time = 0.0;
  12888. this._speed = new BABYLON.Vector2(0.5, 0.3);
  12889. this._shift = 1.6;
  12890. this._autoGenerateTime = true;
  12891. this._alphaThreshold = 0.5;
  12892. this._fireColors = FireProceduralTexture.RedFireColors;
  12893. this.updateShaderUniforms();
  12894. this.refreshRate = 1;
  12895. }
  12896. FireProceduralTexture.prototype.updateShaderUniforms = function () {
  12897. this.setFloat("time", this._time);
  12898. this.setVector2("speed", this._speed);
  12899. this.setFloat("shift", this._shift);
  12900. this.setColor3("c1", this._fireColors[0]);
  12901. this.setColor3("c2", this._fireColors[1]);
  12902. this.setColor3("c3", this._fireColors[2]);
  12903. this.setColor3("c4", this._fireColors[3]);
  12904. this.setColor3("c5", this._fireColors[4]);
  12905. this.setColor3("c6", this._fireColors[5]);
  12906. this.setFloat("alphaThreshold", this._alphaThreshold);
  12907. };
  12908. FireProceduralTexture.prototype.render = function (useCameraPostProcess) {
  12909. if (this._autoGenerateTime) {
  12910. this._time += this.getScene().getAnimationRatio() * 0.03;
  12911. this.updateShaderUniforms();
  12912. }
  12913. _super.prototype.render.call(this, useCameraPostProcess);
  12914. };
  12915. Object.defineProperty(FireProceduralTexture, "PurpleFireColors", {
  12916. get: function () {
  12917. return [
  12918. new BABYLON.Color3(0.5, 0.0, 1.0),
  12919. new BABYLON.Color3(0.9, 0.0, 1.0),
  12920. new BABYLON.Color3(0.2, 0.0, 1.0),
  12921. new BABYLON.Color3(1.0, 0.9, 1.0),
  12922. new BABYLON.Color3(0.1, 0.1, 1.0),
  12923. new BABYLON.Color3(0.9, 0.9, 1.0)
  12924. ];
  12925. },
  12926. enumerable: true,
  12927. configurable: true
  12928. });
  12929. Object.defineProperty(FireProceduralTexture, "GreenFireColors", {
  12930. get: function () {
  12931. return [
  12932. new BABYLON.Color3(0.5, 1.0, 0.0),
  12933. new BABYLON.Color3(0.5, 1.0, 0.0),
  12934. new BABYLON.Color3(0.3, 0.4, 0.0),
  12935. new BABYLON.Color3(0.5, 1.0, 0.0),
  12936. new BABYLON.Color3(0.2, 0.0, 0.0),
  12937. new BABYLON.Color3(0.5, 1.0, 0.0)
  12938. ];
  12939. },
  12940. enumerable: true,
  12941. configurable: true
  12942. });
  12943. Object.defineProperty(FireProceduralTexture, "RedFireColors", {
  12944. get: function () {
  12945. return [
  12946. new BABYLON.Color3(0.5, 0.0, 0.1),
  12947. new BABYLON.Color3(0.9, 0.0, 0.0),
  12948. new BABYLON.Color3(0.2, 0.0, 0.0),
  12949. new BABYLON.Color3(1.0, 0.9, 0.0),
  12950. new BABYLON.Color3(0.1, 0.1, 0.1),
  12951. new BABYLON.Color3(0.9, 0.9, 0.9)
  12952. ];
  12953. },
  12954. enumerable: true,
  12955. configurable: true
  12956. });
  12957. Object.defineProperty(FireProceduralTexture, "BlueFireColors", {
  12958. get: function () {
  12959. return [
  12960. new BABYLON.Color3(0.1, 0.0, 0.5),
  12961. new BABYLON.Color3(0.0, 0.0, 0.5),
  12962. new BABYLON.Color3(0.1, 0.0, 0.2),
  12963. new BABYLON.Color3(0.0, 0.0, 1.0),
  12964. new BABYLON.Color3(0.1, 0.2, 0.3),
  12965. new BABYLON.Color3(0.0, 0.2, 0.9)
  12966. ];
  12967. },
  12968. enumerable: true,
  12969. configurable: true
  12970. });
  12971. Object.defineProperty(FireProceduralTexture.prototype, "fireColors", {
  12972. get: function () {
  12973. return this._fireColors;
  12974. },
  12975. set: function (value) {
  12976. this._fireColors = value;
  12977. this.updateShaderUniforms();
  12978. },
  12979. enumerable: true,
  12980. configurable: true
  12981. });
  12982. Object.defineProperty(FireProceduralTexture.prototype, "time", {
  12983. get: function () {
  12984. return this._time;
  12985. },
  12986. set: function (value) {
  12987. this._time = value;
  12988. this.updateShaderUniforms();
  12989. },
  12990. enumerable: true,
  12991. configurable: true
  12992. });
  12993. Object.defineProperty(FireProceduralTexture.prototype, "speed", {
  12994. get: function () {
  12995. return this._speed;
  12996. },
  12997. set: function (value) {
  12998. this._speed = value;
  12999. this.updateShaderUniforms();
  13000. },
  13001. enumerable: true,
  13002. configurable: true
  13003. });
  13004. Object.defineProperty(FireProceduralTexture.prototype, "shift", {
  13005. get: function () {
  13006. return this._shift;
  13007. },
  13008. set: function (value) {
  13009. this._shift = value;
  13010. this.updateShaderUniforms();
  13011. },
  13012. enumerable: true,
  13013. configurable: true
  13014. });
  13015. Object.defineProperty(FireProceduralTexture.prototype, "alphaThreshold", {
  13016. get: function () {
  13017. return this._alphaThreshold;
  13018. },
  13019. set: function (value) {
  13020. this._alphaThreshold = value;
  13021. this.updateShaderUniforms();
  13022. },
  13023. enumerable: true,
  13024. configurable: true
  13025. });
  13026. return FireProceduralTexture;
  13027. })(BABYLON.ProceduralTexture);
  13028. BABYLON.FireProceduralTexture = FireProceduralTexture;
  13029. var CloudProceduralTexture = (function (_super) {
  13030. __extends(CloudProceduralTexture, _super);
  13031. function CloudProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  13032. _super.call(this, name, size, "cloud", scene, fallbackTexture, generateMipMaps);
  13033. this._skyColor = new BABYLON.Color3(0.15, 0.68, 1.0);
  13034. this._cloudColor = new BABYLON.Color3(1, 1, 1);
  13035. this.updateShaderUniforms();
  13036. this.refreshRate = 0;
  13037. }
  13038. CloudProceduralTexture.prototype.updateShaderUniforms = function () {
  13039. this.setColor3("skyColor", this._skyColor);
  13040. this.setColor3("cloudColor", this._cloudColor);
  13041. };
  13042. Object.defineProperty(CloudProceduralTexture.prototype, "skyColor", {
  13043. get: function () {
  13044. return this._skyColor;
  13045. },
  13046. set: function (value) {
  13047. this._skyColor = value;
  13048. this.updateShaderUniforms();
  13049. },
  13050. enumerable: true,
  13051. configurable: true
  13052. });
  13053. Object.defineProperty(CloudProceduralTexture.prototype, "cloudColor", {
  13054. get: function () {
  13055. return this._cloudColor;
  13056. },
  13057. set: function (value) {
  13058. this._cloudColor = value;
  13059. this.updateShaderUniforms();
  13060. },
  13061. enumerable: true,
  13062. configurable: true
  13063. });
  13064. return CloudProceduralTexture;
  13065. })(BABYLON.ProceduralTexture);
  13066. BABYLON.CloudProceduralTexture = CloudProceduralTexture;
  13067. var GrassProceduralTexture = (function (_super) {
  13068. __extends(GrassProceduralTexture, _super);
  13069. function GrassProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  13070. _super.call(this, name, size, "grass", scene, fallbackTexture, generateMipMaps);
  13071. this._herb1 = new BABYLON.Color3(0.29, 0.38, 0.02);
  13072. this._herb2 = new BABYLON.Color3(0.36, 0.49, 0.09);
  13073. this._herb3 = new BABYLON.Color3(0.51, 0.6, 0.28);
  13074. this._groundColor = new BABYLON.Color3(1, 1, 1);
  13075. this._grassColors = [
  13076. new BABYLON.Color3(0.29, 0.38, 0.02),
  13077. new BABYLON.Color3(0.36, 0.49, 0.09),
  13078. new BABYLON.Color3(0.51, 0.6, 0.28)
  13079. ];
  13080. this.updateShaderUniforms();
  13081. this.refreshRate = 0;
  13082. }
  13083. GrassProceduralTexture.prototype.updateShaderUniforms = function () {
  13084. this.setColor3("herb1Color", this._grassColors[0]);
  13085. this.setColor3("herb2Color", this._grassColors[1]);
  13086. this.setColor3("herb3Color", this._grassColors[2]);
  13087. this.setColor3("groundColor", this._groundColor);
  13088. };
  13089. Object.defineProperty(GrassProceduralTexture.prototype, "grassColors", {
  13090. get: function () {
  13091. return this._grassColors;
  13092. },
  13093. set: function (value) {
  13094. this._grassColors = value;
  13095. this.updateShaderUniforms();
  13096. },
  13097. enumerable: true,
  13098. configurable: true
  13099. });
  13100. Object.defineProperty(GrassProceduralTexture.prototype, "groundColor", {
  13101. get: function () {
  13102. return this._groundColor;
  13103. },
  13104. set: function (value) {
  13105. this.groundColor = value;
  13106. this.updateShaderUniforms();
  13107. },
  13108. enumerable: true,
  13109. configurable: true
  13110. });
  13111. return GrassProceduralTexture;
  13112. })(BABYLON.ProceduralTexture);
  13113. BABYLON.GrassProceduralTexture = GrassProceduralTexture;
  13114. var RoadProceduralTexture = (function (_super) {
  13115. __extends(RoadProceduralTexture, _super);
  13116. function RoadProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  13117. _super.call(this, name, size, "road", scene, fallbackTexture, generateMipMaps);
  13118. this._roadColor = new BABYLON.Color3(0.53, 0.53, 0.53);
  13119. this.updateShaderUniforms();
  13120. this.refreshRate = 0;
  13121. }
  13122. RoadProceduralTexture.prototype.updateShaderUniforms = function () {
  13123. this.setColor3("roadColor", this._roadColor);
  13124. };
  13125. Object.defineProperty(RoadProceduralTexture.prototype, "roadColor", {
  13126. get: function () {
  13127. return this._roadColor;
  13128. },
  13129. set: function (value) {
  13130. this._roadColor = value;
  13131. this.updateShaderUniforms();
  13132. },
  13133. enumerable: true,
  13134. configurable: true
  13135. });
  13136. return RoadProceduralTexture;
  13137. })(BABYLON.ProceduralTexture);
  13138. BABYLON.RoadProceduralTexture = RoadProceduralTexture;
  13139. var BrickProceduralTexture = (function (_super) {
  13140. __extends(BrickProceduralTexture, _super);
  13141. function BrickProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  13142. _super.call(this, name, size, "brick", scene, fallbackTexture, generateMipMaps);
  13143. this._numberOfBricksHeight = 15;
  13144. this._numberOfBricksWidth = 5;
  13145. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  13146. this._brickColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  13147. this.updateShaderUniforms();
  13148. this.refreshRate = 0;
  13149. }
  13150. BrickProceduralTexture.prototype.updateShaderUniforms = function () {
  13151. this.setFloat("numberOfBricksHeight", this._numberOfBricksHeight);
  13152. this.setFloat("numberOfBricksWidth", this._numberOfBricksWidth);
  13153. this.setColor3("brickColor", this._brickColor);
  13154. this.setColor3("jointColor", this._jointColor);
  13155. };
  13156. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksHeight", {
  13157. get: function () {
  13158. return this._numberOfBricksHeight;
  13159. },
  13160. enumerable: true,
  13161. configurable: true
  13162. });
  13163. Object.defineProperty(BrickProceduralTexture.prototype, "cloudColor", {
  13164. set: function (value) {
  13165. this._numberOfBricksHeight = value;
  13166. this.updateShaderUniforms();
  13167. },
  13168. enumerable: true,
  13169. configurable: true
  13170. });
  13171. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksWidth", {
  13172. get: function () {
  13173. return this._numberOfBricksWidth;
  13174. },
  13175. set: function (value) {
  13176. this._numberOfBricksHeight = value;
  13177. this.updateShaderUniforms();
  13178. },
  13179. enumerable: true,
  13180. configurable: true
  13181. });
  13182. Object.defineProperty(BrickProceduralTexture.prototype, "jointColor", {
  13183. get: function () {
  13184. return this._jointColor;
  13185. },
  13186. set: function (value) {
  13187. this._jointColor = value;
  13188. this.updateShaderUniforms();
  13189. },
  13190. enumerable: true,
  13191. configurable: true
  13192. });
  13193. Object.defineProperty(BrickProceduralTexture.prototype, "brickColor", {
  13194. get: function () {
  13195. return this._brickColor;
  13196. },
  13197. set: function (value) {
  13198. this._brickColor = value;
  13199. this.updateShaderUniforms();
  13200. },
  13201. enumerable: true,
  13202. configurable: true
  13203. });
  13204. return BrickProceduralTexture;
  13205. })(BABYLON.ProceduralTexture);
  13206. BABYLON.BrickProceduralTexture = BrickProceduralTexture;
  13207. var MarbleProceduralTexture = (function (_super) {
  13208. __extends(MarbleProceduralTexture, _super);
  13209. function MarbleProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  13210. _super.call(this, name, size, "marble", scene, fallbackTexture, generateMipMaps);
  13211. this._numberOfTilesHeight = 3;
  13212. this._numberOfTilesWidth = 3;
  13213. this._amplitude = 9.0;
  13214. this._marbleColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  13215. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  13216. this.updateShaderUniforms();
  13217. this.refreshRate = 0;
  13218. }
  13219. MarbleProceduralTexture.prototype.updateShaderUniforms = function () {
  13220. this.setFloat("numberOfTilesHeight", this._numberOfTilesHeight);
  13221. this.setFloat("numberOfTilesWidth", this._numberOfTilesWidth);
  13222. this.setFloat("amplitude", this._amplitude);
  13223. this.setColor3("marbleColor", this._marbleColor);
  13224. this.setColor3("jointColor", this._jointColor);
  13225. };
  13226. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesHeight", {
  13227. get: function () {
  13228. return this._numberOfTilesHeight;
  13229. },
  13230. set: function (value) {
  13231. this._numberOfTilesHeight = value;
  13232. this.updateShaderUniforms();
  13233. },
  13234. enumerable: true,
  13235. configurable: true
  13236. });
  13237. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesWidth", {
  13238. get: function () {
  13239. return this._numberOfTilesWidth;
  13240. },
  13241. set: function (value) {
  13242. this._numberOfTilesWidth = value;
  13243. this.updateShaderUniforms();
  13244. },
  13245. enumerable: true,
  13246. configurable: true
  13247. });
  13248. Object.defineProperty(MarbleProceduralTexture.prototype, "jointColor", {
  13249. get: function () {
  13250. return this._jointColor;
  13251. },
  13252. set: function (value) {
  13253. this._jointColor = value;
  13254. this.updateShaderUniforms();
  13255. },
  13256. enumerable: true,
  13257. configurable: true
  13258. });
  13259. Object.defineProperty(MarbleProceduralTexture.prototype, "marbleColor", {
  13260. get: function () {
  13261. return this._marbleColor;
  13262. },
  13263. set: function (value) {
  13264. this._marbleColor = value;
  13265. this.updateShaderUniforms();
  13266. },
  13267. enumerable: true,
  13268. configurable: true
  13269. });
  13270. return MarbleProceduralTexture;
  13271. })(BABYLON.ProceduralTexture);
  13272. BABYLON.MarbleProceduralTexture = MarbleProceduralTexture;
  13273. })(BABYLON || (BABYLON = {}));
  13274. //# sourceMappingURL=babylon.standardProceduralTexture.js.map
  13275. var BABYLON;
  13276. (function (BABYLON) {
  13277. var CustomProceduralTexture = (function (_super) {
  13278. __extends(CustomProceduralTexture, _super);
  13279. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  13280. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  13281. this._animate = true;
  13282. this._time = 0;
  13283. this._texturePath = texturePath;
  13284. //Try to load json
  13285. this.loadJson(texturePath);
  13286. this.refreshRate = 1;
  13287. }
  13288. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  13289. var _this = this;
  13290. var that = this;
  13291. function noConfigFile() {
  13292. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  13293. try {
  13294. that.setFragment(that._texturePath);
  13295. }
  13296. catch (ex) {
  13297. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  13298. }
  13299. }
  13300. var configFileUrl = jsonUrl + "/config.json";
  13301. var xhr = new XMLHttpRequest();
  13302. xhr.open("GET", configFileUrl, true);
  13303. xhr.addEventListener("load", function () {
  13304. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  13305. try {
  13306. _this._config = JSON.parse(xhr.response);
  13307. _this.updateShaderUniforms();
  13308. _this.updateTextures();
  13309. _this.setFragment(_this._texturePath + "/custom");
  13310. _this._animate = _this._config.animate;
  13311. _this.refreshRate = _this._config.refreshrate;
  13312. }
  13313. catch (ex) {
  13314. noConfigFile();
  13315. }
  13316. }
  13317. else {
  13318. noConfigFile();
  13319. }
  13320. }, false);
  13321. xhr.addEventListener("error", function () {
  13322. noConfigFile();
  13323. }, false);
  13324. try {
  13325. xhr.send();
  13326. }
  13327. catch (ex) {
  13328. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  13329. }
  13330. };
  13331. CustomProceduralTexture.prototype.isReady = function () {
  13332. if (!_super.prototype.isReady.call(this)) {
  13333. return false;
  13334. }
  13335. for (var name in this._textures) {
  13336. var texture = this._textures[name];
  13337. if (!texture.isReady()) {
  13338. return false;
  13339. }
  13340. }
  13341. return true;
  13342. };
  13343. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  13344. if (this._animate) {
  13345. this._time += this.getScene().getAnimationRatio() * 0.03;
  13346. this.updateShaderUniforms();
  13347. }
  13348. _super.prototype.render.call(this, useCameraPostProcess);
  13349. };
  13350. CustomProceduralTexture.prototype.updateTextures = function () {
  13351. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  13352. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  13353. }
  13354. };
  13355. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  13356. if (this._config) {
  13357. for (var j = 0; j < this._config.uniforms.length; j++) {
  13358. var uniform = this._config.uniforms[j];
  13359. switch (uniform.type) {
  13360. case "float":
  13361. this.setFloat(uniform.name, uniform.value);
  13362. break;
  13363. case "color3":
  13364. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  13365. break;
  13366. case "color4":
  13367. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  13368. break;
  13369. case "vector2":
  13370. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  13371. break;
  13372. case "vector3":
  13373. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  13374. break;
  13375. }
  13376. }
  13377. }
  13378. this.setFloat("time", this._time);
  13379. };
  13380. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  13381. get: function () {
  13382. return this._animate;
  13383. },
  13384. set: function (value) {
  13385. this._animate = value;
  13386. },
  13387. enumerable: true,
  13388. configurable: true
  13389. });
  13390. return CustomProceduralTexture;
  13391. })(BABYLON.ProceduralTexture);
  13392. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  13393. })(BABYLON || (BABYLON = {}));
  13394. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  13395. var BABYLON;
  13396. (function (BABYLON) {
  13397. var MirrorTexture = (function (_super) {
  13398. __extends(MirrorTexture, _super);
  13399. function MirrorTexture(name, size, scene, generateMipMaps) {
  13400. var _this = this;
  13401. _super.call(this, name, size, scene, generateMipMaps, true);
  13402. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  13403. this._transformMatrix = BABYLON.Matrix.Zero();
  13404. this._mirrorMatrix = BABYLON.Matrix.Zero();
  13405. this.onBeforeRender = function () {
  13406. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  13407. _this._savedViewMatrix = scene.getViewMatrix();
  13408. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  13409. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  13410. scene.clipPlane = _this.mirrorPlane;
  13411. scene.getEngine().cullBackFaces = false;
  13412. };
  13413. this.onAfterRender = function () {
  13414. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  13415. scene.getEngine().cullBackFaces = true;
  13416. delete scene.clipPlane;
  13417. };
  13418. }
  13419. MirrorTexture.prototype.clone = function () {
  13420. var textureSize = this.getSize();
  13421. var newTexture = new BABYLON.MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  13422. // Base texture
  13423. newTexture.hasAlpha = this.hasAlpha;
  13424. newTexture.level = this.level;
  13425. // Mirror Texture
  13426. newTexture.mirrorPlane = this.mirrorPlane.clone();
  13427. newTexture.renderList = this.renderList.slice(0);
  13428. return newTexture;
  13429. };
  13430. return MirrorTexture;
  13431. })(BABYLON.RenderTargetTexture);
  13432. BABYLON.MirrorTexture = MirrorTexture;
  13433. })(BABYLON || (BABYLON = {}));
  13434. //# sourceMappingURL=babylon.mirrorTexture.js.map
  13435. var BABYLON;
  13436. (function (BABYLON) {
  13437. var DynamicTexture = (function (_super) {
  13438. __extends(DynamicTexture, _super);
  13439. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  13440. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  13441. _super.call(this, null, scene, !generateMipMaps);
  13442. this.name = name;
  13443. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  13444. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  13445. this._generateMipMaps = generateMipMaps;
  13446. if (options.getContext) {
  13447. this._canvas = options;
  13448. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  13449. }
  13450. else {
  13451. this._canvas = document.createElement("canvas");
  13452. if (options.width) {
  13453. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  13454. }
  13455. else {
  13456. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  13457. }
  13458. }
  13459. var textureSize = this.getSize();
  13460. this._canvas.width = textureSize.width;
  13461. this._canvas.height = textureSize.height;
  13462. this._context = this._canvas.getContext("2d");
  13463. }
  13464. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  13465. get: function () {
  13466. return true;
  13467. },
  13468. enumerable: true,
  13469. configurable: true
  13470. });
  13471. DynamicTexture.prototype.scale = function (ratio) {
  13472. var textureSize = this.getSize();
  13473. textureSize.width *= ratio;
  13474. textureSize.height *= ratio;
  13475. this._canvas.width = textureSize.width;
  13476. this._canvas.height = textureSize.height;
  13477. this.releaseInternalTexture();
  13478. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  13479. };
  13480. DynamicTexture.prototype.getContext = function () {
  13481. return this._context;
  13482. };
  13483. DynamicTexture.prototype.clear = function () {
  13484. var size = this.getSize();
  13485. this._context.fillRect(0, 0, size.width, size.height);
  13486. };
  13487. DynamicTexture.prototype.update = function (invertY) {
  13488. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  13489. };
  13490. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  13491. if (update === void 0) { update = true; }
  13492. var size = this.getSize();
  13493. if (clearColor) {
  13494. this._context.fillStyle = clearColor;
  13495. this._context.fillRect(0, 0, size.width, size.height);
  13496. }
  13497. this._context.font = font;
  13498. if (x === null) {
  13499. var textSize = this._context.measureText(text);
  13500. x = (size.width - textSize.width) / 2;
  13501. }
  13502. this._context.fillStyle = color;
  13503. this._context.fillText(text, x, y);
  13504. if (update) {
  13505. this.update(invertY);
  13506. }
  13507. };
  13508. DynamicTexture.prototype.clone = function () {
  13509. var textureSize = this.getSize();
  13510. var newTexture = new DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  13511. // Base texture
  13512. newTexture.hasAlpha = this.hasAlpha;
  13513. newTexture.level = this.level;
  13514. // Dynamic Texture
  13515. newTexture.wrapU = this.wrapU;
  13516. newTexture.wrapV = this.wrapV;
  13517. return newTexture;
  13518. };
  13519. return DynamicTexture;
  13520. })(BABYLON.Texture);
  13521. BABYLON.DynamicTexture = DynamicTexture;
  13522. })(BABYLON || (BABYLON = {}));
  13523. //# sourceMappingURL=babylon.dynamicTexture.js.map
  13524. var BABYLON;
  13525. (function (BABYLON) {
  13526. var VideoTexture = (function (_super) {
  13527. __extends(VideoTexture, _super);
  13528. function VideoTexture(name, urls, size, scene, generateMipMaps, invertY, samplingMode) {
  13529. var _this = this;
  13530. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  13531. _super.call(this, null, scene, !generateMipMaps, invertY);
  13532. this._autoLaunch = true;
  13533. this.name = name;
  13534. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  13535. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  13536. var requiredWidth = size.width || size;
  13537. var requiredHeight = size.height || size;
  13538. this._texture = scene.getEngine().createDynamicTexture(requiredWidth, requiredHeight, generateMipMaps, samplingMode);
  13539. var textureSize = this.getSize();
  13540. this.video = document.createElement("video");
  13541. this.video.width = textureSize.width;
  13542. this.video.height = textureSize.height;
  13543. this.video.autoplay = false;
  13544. this.video.loop = true;
  13545. this.video.addEventListener("canplaythrough", function () {
  13546. if (_this._texture) {
  13547. _this._texture.isReady = true;
  13548. }
  13549. });
  13550. urls.forEach(function (url) {
  13551. //Backwards-compatibility for typescript 1. from 1.3 it should say "SOURCE". see here - https://github.com/Microsoft/TypeScript/issues/1850
  13552. var source = document.createElement("source");
  13553. source.src = url;
  13554. _this.video.appendChild(source);
  13555. });
  13556. this._lastUpdate = BABYLON.Tools.Now;
  13557. }
  13558. VideoTexture.prototype.update = function () {
  13559. if (this._autoLaunch) {
  13560. this._autoLaunch = false;
  13561. this.video.play();
  13562. }
  13563. var now = BABYLON.Tools.Now;
  13564. if (now - this._lastUpdate < 15) {
  13565. return false;
  13566. }
  13567. this._lastUpdate = now;
  13568. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  13569. return true;
  13570. };
  13571. return VideoTexture;
  13572. })(BABYLON.Texture);
  13573. BABYLON.VideoTexture = VideoTexture;
  13574. })(BABYLON || (BABYLON = {}));
  13575. //# sourceMappingURL=babylon.videoTexture.js.mapvar BABYLON;
  13576. (function (BABYLON) {
  13577. var EffectFallbacks = (function () {
  13578. function EffectFallbacks() {
  13579. this._defines = {};
  13580. this._currentRank = 32;
  13581. this._maxRank = -1;
  13582. }
  13583. EffectFallbacks.prototype.addFallback = function (rank, define) {
  13584. if (!this._defines[rank]) {
  13585. if (rank < this._currentRank) {
  13586. this._currentRank = rank;
  13587. }
  13588. if (rank > this._maxRank) {
  13589. this._maxRank = rank;
  13590. }
  13591. this._defines[rank] = new Array();
  13592. }
  13593. this._defines[rank].push(define);
  13594. };
  13595. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  13596. get: function () {
  13597. return this._currentRank <= this._maxRank;
  13598. },
  13599. enumerable: true,
  13600. configurable: true
  13601. });
  13602. EffectFallbacks.prototype.reduce = function (currentDefines) {
  13603. var currentFallbacks = this._defines[this._currentRank];
  13604. for (var index = 0; index < currentFallbacks.length; index++) {
  13605. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  13606. }
  13607. this._currentRank++;
  13608. return currentDefines;
  13609. };
  13610. return EffectFallbacks;
  13611. })();
  13612. BABYLON.EffectFallbacks = EffectFallbacks;
  13613. var Effect = (function () {
  13614. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  13615. var _this = this;
  13616. this._isReady = false;
  13617. this._compilationError = "";
  13618. this._valueCache = [];
  13619. this._engine = engine;
  13620. this.name = baseName;
  13621. this.defines = defines;
  13622. this._uniformsNames = uniformsNames.concat(samplers);
  13623. this._samplers = samplers;
  13624. this._attributesNames = attributesNames;
  13625. this.onError = onError;
  13626. this.onCompiled = onCompiled;
  13627. var vertexSource;
  13628. var fragmentSource;
  13629. if (baseName.vertexElement) {
  13630. vertexSource = document.getElementById(baseName.vertexElement);
  13631. if (!vertexSource) {
  13632. vertexSource = baseName.vertexElement;
  13633. }
  13634. }
  13635. else {
  13636. vertexSource = baseName.vertex || baseName;
  13637. }
  13638. if (baseName.fragmentElement) {
  13639. fragmentSource = document.getElementById(baseName.fragmentElement);
  13640. if (!fragmentSource) {
  13641. fragmentSource = baseName.fragmentElement;
  13642. }
  13643. }
  13644. else {
  13645. fragmentSource = baseName.fragment || baseName;
  13646. }
  13647. this._loadVertexShader(vertexSource, function (vertexCode) {
  13648. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  13649. _this._prepareEffect(vertexCode, fragmentCode, attributesNames, defines, fallbacks);
  13650. });
  13651. });
  13652. }
  13653. // Properties
  13654. Effect.prototype.isReady = function () {
  13655. return this._isReady;
  13656. };
  13657. Effect.prototype.getProgram = function () {
  13658. return this._program;
  13659. };
  13660. Effect.prototype.getAttributesNames = function () {
  13661. return this._attributesNames;
  13662. };
  13663. Effect.prototype.getAttributeLocation = function (index) {
  13664. return this._attributes[index];
  13665. };
  13666. Effect.prototype.getAttributeLocationByName = function (name) {
  13667. var index = this._attributesNames.indexOf(name);
  13668. return this._attributes[index];
  13669. };
  13670. Effect.prototype.getAttributesCount = function () {
  13671. return this._attributes.length;
  13672. };
  13673. Effect.prototype.getUniformIndex = function (uniformName) {
  13674. return this._uniformsNames.indexOf(uniformName);
  13675. };
  13676. Effect.prototype.getUniform = function (uniformName) {
  13677. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  13678. };
  13679. Effect.prototype.getSamplers = function () {
  13680. return this._samplers;
  13681. };
  13682. Effect.prototype.getCompilationError = function () {
  13683. return this._compilationError;
  13684. };
  13685. // Methods
  13686. Effect.prototype._loadVertexShader = function (vertex, callback) {
  13687. // DOM element ?
  13688. if (vertex instanceof HTMLElement) {
  13689. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  13690. callback(vertexCode);
  13691. return;
  13692. }
  13693. // Is in local store ?
  13694. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  13695. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  13696. return;
  13697. }
  13698. var vertexShaderUrl;
  13699. if (vertex[0] === ".") {
  13700. vertexShaderUrl = vertex;
  13701. }
  13702. else {
  13703. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  13704. }
  13705. // Vertex shader
  13706. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  13707. };
  13708. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  13709. // DOM element ?
  13710. if (fragment instanceof HTMLElement) {
  13711. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  13712. callback(fragmentCode);
  13713. return;
  13714. }
  13715. // Is in local store ?
  13716. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  13717. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  13718. return;
  13719. }
  13720. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  13721. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  13722. return;
  13723. }
  13724. var fragmentShaderUrl;
  13725. if (fragment[0] === ".") {
  13726. fragmentShaderUrl = fragment;
  13727. }
  13728. else {
  13729. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  13730. }
  13731. // Fragment shader
  13732. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  13733. };
  13734. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  13735. try {
  13736. var engine = this._engine;
  13737. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  13738. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  13739. this._attributes = engine.getAttributes(this._program, attributesNames);
  13740. for (var index = 0; index < this._samplers.length; index++) {
  13741. var sampler = this.getUniform(this._samplers[index]);
  13742. if (sampler == null) {
  13743. this._samplers.splice(index, 1);
  13744. index--;
  13745. }
  13746. }
  13747. engine.bindSamplers(this);
  13748. this._isReady = true;
  13749. if (this.onCompiled) {
  13750. this.onCompiled(this);
  13751. }
  13752. }
  13753. catch (e) {
  13754. // Is it a problem with precision?
  13755. if (e.message.indexOf("highp") !== -1) {
  13756. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  13757. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  13758. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  13759. return;
  13760. }
  13761. // Let's go through fallbacks then
  13762. if (fallbacks && fallbacks.isMoreFallbacks) {
  13763. defines = fallbacks.reduce(defines);
  13764. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  13765. }
  13766. else {
  13767. BABYLON.Tools.Error("Unable to compile effect: " + this.name);
  13768. BABYLON.Tools.Error("Defines: " + defines);
  13769. BABYLON.Tools.Error("Error: " + e.message);
  13770. this._compilationError = e.message;
  13771. if (this.onError) {
  13772. this.onError(this, this._compilationError);
  13773. }
  13774. }
  13775. }
  13776. };
  13777. Effect.prototype._bindTexture = function (channel, texture) {
  13778. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  13779. };
  13780. Effect.prototype.setTexture = function (channel, texture) {
  13781. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  13782. };
  13783. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  13784. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  13785. };
  13786. //public _cacheMatrix(uniformName, matrix) {
  13787. // if (!this._valueCache[uniformName]) {
  13788. // this._valueCache[uniformName] = new BABYLON.Matrix();
  13789. // }
  13790. // for (var index = 0; index < 16; index++) {
  13791. // this._valueCache[uniformName].m[index] = matrix.m[index];
  13792. // }
  13793. //};
  13794. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  13795. if (!this._valueCache[uniformName]) {
  13796. this._valueCache[uniformName] = [x, y];
  13797. return;
  13798. }
  13799. this._valueCache[uniformName][0] = x;
  13800. this._valueCache[uniformName][1] = y;
  13801. };
  13802. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  13803. if (!this._valueCache[uniformName]) {
  13804. this._valueCache[uniformName] = [x, y, z];
  13805. return;
  13806. }
  13807. this._valueCache[uniformName][0] = x;
  13808. this._valueCache[uniformName][1] = y;
  13809. this._valueCache[uniformName][2] = z;
  13810. };
  13811. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  13812. if (!this._valueCache[uniformName]) {
  13813. this._valueCache[uniformName] = [x, y, z, w];
  13814. return;
  13815. }
  13816. this._valueCache[uniformName][0] = x;
  13817. this._valueCache[uniformName][1] = y;
  13818. this._valueCache[uniformName][2] = z;
  13819. this._valueCache[uniformName][3] = w;
  13820. };
  13821. Effect.prototype.setArray = function (uniformName, array) {
  13822. this._engine.setArray(this.getUniform(uniformName), array);
  13823. return this;
  13824. };
  13825. Effect.prototype.setArray2 = function (uniformName, array) {
  13826. this._engine.setArray2(this.getUniform(uniformName), array);
  13827. return this;
  13828. };
  13829. Effect.prototype.setArray3 = function (uniformName, array) {
  13830. this._engine.setArray3(this.getUniform(uniformName), array);
  13831. return this;
  13832. };
  13833. Effect.prototype.setArray4 = function (uniformName, array) {
  13834. this._engine.setArray4(this.getUniform(uniformName), array);
  13835. return this;
  13836. };
  13837. Effect.prototype.setMatrices = function (uniformName, matrices) {
  13838. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  13839. return this;
  13840. };
  13841. Effect.prototype.setMatrix = function (uniformName, matrix) {
  13842. //if (this._valueCache[uniformName] && this._valueCache[uniformName].equals(matrix))
  13843. // return;
  13844. //this._cacheMatrix(uniformName, matrix);
  13845. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  13846. return this;
  13847. };
  13848. Effect.prototype.setFloat = function (uniformName, value) {
  13849. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  13850. return this;
  13851. this._valueCache[uniformName] = value;
  13852. this._engine.setFloat(this.getUniform(uniformName), value);
  13853. return this;
  13854. };
  13855. Effect.prototype.setBool = function (uniformName, bool) {
  13856. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  13857. return this;
  13858. this._valueCache[uniformName] = bool;
  13859. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  13860. return this;
  13861. };
  13862. Effect.prototype.setVector2 = function (uniformName, vector2) {
  13863. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector2.x && this._valueCache[uniformName][1] === vector2.y)
  13864. return this;
  13865. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  13866. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  13867. return this;
  13868. };
  13869. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  13870. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y)
  13871. return this;
  13872. this._cacheFloat2(uniformName, x, y);
  13873. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  13874. return this;
  13875. };
  13876. Effect.prototype.setVector3 = function (uniformName, vector3) {
  13877. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector3.x && this._valueCache[uniformName][1] === vector3.y && this._valueCache[uniformName][2] === vector3.z)
  13878. return this;
  13879. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  13880. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  13881. return this;
  13882. };
  13883. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  13884. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z)
  13885. return this;
  13886. this._cacheFloat3(uniformName, x, y, z);
  13887. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  13888. return this;
  13889. };
  13890. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  13891. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z && this._valueCache[uniformName][3] === w)
  13892. return this;
  13893. this._cacheFloat4(uniformName, x, y, z, w);
  13894. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  13895. return this;
  13896. };
  13897. Effect.prototype.setColor3 = function (uniformName, color3) {
  13898. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b)
  13899. return this;
  13900. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  13901. this._engine.setColor3(this.getUniform(uniformName), color3);
  13902. return this;
  13903. };
  13904. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  13905. 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)
  13906. return this;
  13907. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  13908. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  13909. return this;
  13910. };
  13911. // Statics
  13912. 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}",
  13913. 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}",
  13914. 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}",
  13915. 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}",
  13916. 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}",
  13917. 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}",
  13918. colorPixelShader:"precision highp float;\n\nuniform vec4 color;\n\nvoid main(void) {\n gl_FragColor = color;\n}",
  13919. 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}",
  13920. 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}",
  13921. 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}",
  13922. 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 if (unpack(texture2D(shadowSampler, uv + poissonDisk[0] / mapSize)) + bias < depth.z) visibility -= 0.25;\n if (unpack(texture2D(shadowSampler, uv + poissonDisk[1] / mapSize)) + bias < depth.z) visibility -= 0.25;\n if (unpack(texture2D(shadowSampler, uv + poissonDisk[2] / mapSize)) + bias < depth.z) visibility -= 0.25;\n if (unpack(texture2D(shadowSampler, uv + poissonDisk[3] / mapSize)) + bias < depth.z) visibility -= 0.25;\n\n return visibility;\n}\n\n// Thanks to http://devmaster.net/\nfloat ChebychevInequality(vec2 moments, float t)\n{\n if (t <= moments.x)\n {\n return 0.0;\n }\n\n float variance = moments.y - (moments.x * moments.x);\n variance = max(variance, 0.002);\n\n float d = t - moments.x;\n\n return clamp(variance / (variance + d * d) - 0.05, 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}",
  13923. 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}",
  13924. 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}",
  13925. 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}",
  13926. 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}",
  13927. 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}",
  13928. 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}",
  13929. 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}",
  13930. 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}",
  13931. 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}",
  13932. 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}",
  13933. 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}",
  13934. 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}",
  13935. 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}",
  13936. 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}",
  13937. 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}",
  13938. 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}",
  13939. 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}",
  13940. 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}",
  13941. 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}",
  13942. 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}",
  13943. 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}",
  13944. 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}",
  13945. 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}",
  13946. 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}",
  13947. 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}",
  13948. 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}",
  13949. 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}",
  13950. 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}",
  13951. 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}",
  13952. 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}",
  13953. spritesVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Attributes\nattribute vec3 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\n// Uniforms\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\n// Output\nvarying vec2 vUV;\nvarying vec4 vColor;\n\n#ifdef FOG\nvarying float fFogDistance;\n#endif\n\nvoid main(void) { \n vec3 viewPos = (view * vec4(position, 1.0)).xyz; \n vec3 cornerPos;\n \n float angle = options.x;\n float size = options.y;\n vec2 offset = options.zw;\n vec2 uvScale = textureInfos.xy;\n\n cornerPos = vec3(offset.x - 0.5, offset.y - 0.5, 0.) * size;\n\n // Rotate\n vec3 rotatedCorner;\n rotatedCorner.x = cornerPos.x * cos(angle) - cornerPos.y * sin(angle);\n rotatedCorner.y = cornerPos.x * sin(angle) + cornerPos.y * cos(angle);\n rotatedCorner.z = 0.;\n\n // Position\n viewPos += rotatedCorner;\n gl_Position = projection * vec4(viewPos, 1.0); \n\n // Color\n vColor = color;\n \n // Texture\n vec2 uvOffset = vec2(abs(offset.x - cellInfo.x), 1.0 - abs(offset.y - cellInfo.y));\n\n vUV = (uvOffset + cellInfo.zw) * uvScale;\n\n // Fog\n#ifdef FOG\n fFogDistance = viewPos.z;\n#endif\n}",
  13954. ssaoPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n#define SAMPLES 16\n\nuniform sampler2D textureSampler;\nuniform sampler2D randomSampler;\n\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[16];\n\nvarying vec2 vUV;\n\nconst vec2 offset1 = vec2(0.0, 0.01);\nconst vec2 offset2 = vec2(0.01, 0.0);\n\nvec3 normalFromDepth(const float depth, const vec2 coords) {\n float depth1 = texture2D(textureSampler, coords + offset1).r;\n float depth2 = texture2D(textureSampler, coords + offset2).r;\n\n vec3 p1 = vec3(offset1, depth1 - depth);\n vec3 p2 = vec3(offset2, depth2 - depth);\n\n vec3 normal = cross(p1, p2);\n normal.z = -normal.z;\n\n return normalize(normal);\n}\n\nvoid main(void)\n{\n const float totalStrength = 1.0;\n const float base = 0.2;\n const float area = 0.0075;\n const float fallOff = 0.000001;\n const float radius = 0.0005;\n\n vec3 random = texture2D(randomSampler, vUV * randTextureTiles).rgb;\n float depth = texture2D(textureSampler, vUV).r;\n vec3 position = vec3(vUV, depth);\n vec3 normal = normalFromDepth(depth, vUV);\n float radiusDepth = radius / depth;\n float occlusion = 0.0;\n\n vec3 ray;\n vec3 hemiRay;\n float occlusionDepth;\n float difference;\n\n for (int i = 0; i < SAMPLES; i++)\n {\n ray = radiusDepth * reflect(sampleSphere[i], random);\n hemiRay = position + dot(ray, normal) * ray;\n\n occlusionDepth = texture2D(textureSampler, clamp(hemiRay.xy, 0.0, 1.0)).r;\n difference = depth - occlusionDepth;\n\n occlusion += step(fallOff, difference) * (1.0 - smoothstep(fallOff, area, difference));\n }\n\n float ao = 1.0 - totalStrength * occlusion * samplesFactor;\n\n float result = clamp(ao + base, 0.0, 1.0);\n gl_FragColor.r = result;\n gl_FragColor.g = result;\n gl_FragColor.b = result;\n gl_FragColor.a = 1.0;\n}",
  13955. 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}",
  13956. 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}",
  13957. 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}",
  13958. 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}",
  13959. };
  13960. return Effect;
  13961. })();
  13962. BABYLON.Effect = Effect;
  13963. })(BABYLON || (BABYLON = {}));
  13964. //# sourceMappingURL=babylon.effect.js.mapvar BABYLON;
  13965. (function (BABYLON) {
  13966. var Material = (function () {
  13967. function Material(name, scene, doNotAdd) {
  13968. this.name = name;
  13969. this.checkReadyOnEveryCall = true;
  13970. this.checkReadyOnlyOnce = false;
  13971. this.state = "";
  13972. this.alpha = 1.0;
  13973. this.backFaceCulling = true;
  13974. this._wasPreviouslyReady = false;
  13975. this._fillMode = Material.TriangleFillMode;
  13976. this.pointSize = 1.0;
  13977. this.id = name;
  13978. this._scene = scene;
  13979. if (!doNotAdd) {
  13980. scene.materials.push(this);
  13981. }
  13982. }
  13983. Object.defineProperty(Material, "TriangleFillMode", {
  13984. get: function () {
  13985. return Material._TriangleFillMode;
  13986. },
  13987. enumerable: true,
  13988. configurable: true
  13989. });
  13990. Object.defineProperty(Material, "WireFrameFillMode", {
  13991. get: function () {
  13992. return Material._WireFrameFillMode;
  13993. },
  13994. enumerable: true,
  13995. configurable: true
  13996. });
  13997. Object.defineProperty(Material, "PointFillMode", {
  13998. get: function () {
  13999. return Material._PointFillMode;
  14000. },
  14001. enumerable: true,
  14002. configurable: true
  14003. });
  14004. Object.defineProperty(Material.prototype, "wireframe", {
  14005. get: function () {
  14006. return this._fillMode === Material.WireFrameFillMode;
  14007. },
  14008. set: function (value) {
  14009. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  14010. },
  14011. enumerable: true,
  14012. configurable: true
  14013. });
  14014. Object.defineProperty(Material.prototype, "pointsCloud", {
  14015. get: function () {
  14016. return this._fillMode === Material.PointFillMode;
  14017. },
  14018. set: function (value) {
  14019. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  14020. },
  14021. enumerable: true,
  14022. configurable: true
  14023. });
  14024. Object.defineProperty(Material.prototype, "fillMode", {
  14025. get: function () {
  14026. return this._fillMode;
  14027. },
  14028. set: function (value) {
  14029. this._fillMode = value;
  14030. },
  14031. enumerable: true,
  14032. configurable: true
  14033. });
  14034. Material.prototype.isReady = function (mesh, useInstances) {
  14035. return true;
  14036. };
  14037. Material.prototype.getEffect = function () {
  14038. return this._effect;
  14039. };
  14040. Material.prototype.getScene = function () {
  14041. return this._scene;
  14042. };
  14043. Material.prototype.needAlphaBlending = function () {
  14044. return (this.alpha < 1.0);
  14045. };
  14046. Material.prototype.needAlphaTesting = function () {
  14047. return false;
  14048. };
  14049. Material.prototype.getAlphaTestTexture = function () {
  14050. return null;
  14051. };
  14052. Material.prototype.trackCreation = function (onCompiled, onError) {
  14053. };
  14054. Material.prototype._preBind = function () {
  14055. var engine = this._scene.getEngine();
  14056. engine.enableEffect(this._effect);
  14057. engine.setState(this.backFaceCulling);
  14058. };
  14059. Material.prototype.bind = function (world, mesh) {
  14060. this._scene._cachedMaterial = this;
  14061. if (this.onBind) {
  14062. this.onBind(this);
  14063. }
  14064. };
  14065. Material.prototype.bindOnlyWorldMatrix = function (world) {
  14066. };
  14067. Material.prototype.unbind = function () {
  14068. };
  14069. Material.prototype.dispose = function (forceDisposeEffect) {
  14070. // Remove from scene
  14071. var index = this._scene.materials.indexOf(this);
  14072. this._scene.materials.splice(index, 1);
  14073. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  14074. if (forceDisposeEffect && this._effect) {
  14075. this._scene.getEngine()._releaseEffect(this._effect);
  14076. this._effect = null;
  14077. }
  14078. // Callback
  14079. if (this.onDispose) {
  14080. this.onDispose();
  14081. }
  14082. };
  14083. Material._TriangleFillMode = 0;
  14084. Material._WireFrameFillMode = 1;
  14085. Material._PointFillMode = 2;
  14086. return Material;
  14087. })();
  14088. BABYLON.Material = Material;
  14089. })(BABYLON || (BABYLON = {}));
  14090. //# sourceMappingURL=babylon.material.js.map
  14091. var BABYLON;
  14092. (function (BABYLON) {
  14093. var maxSimultaneousLights = 4;
  14094. var FresnelParameters = (function () {
  14095. function FresnelParameters() {
  14096. this.isEnabled = true;
  14097. this.leftColor = BABYLON.Color3.White();
  14098. this.rightColor = BABYLON.Color3.Black();
  14099. this.bias = 0;
  14100. this.power = 1;
  14101. }
  14102. return FresnelParameters;
  14103. })();
  14104. BABYLON.FresnelParameters = FresnelParameters;
  14105. var StandardMaterial = (function (_super) {
  14106. __extends(StandardMaterial, _super);
  14107. function StandardMaterial(name, scene) {
  14108. var _this = this;
  14109. _super.call(this, name, scene);
  14110. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  14111. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  14112. this.specularColor = new BABYLON.Color3(1, 1, 1);
  14113. this.specularPower = 64;
  14114. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  14115. this.useAlphaFromDiffuseTexture = false;
  14116. this.useSpecularOverAlpha = true;
  14117. this.fogEnabled = true;
  14118. this._cachedDefines = null;
  14119. this._renderTargets = new BABYLON.SmartArray(16);
  14120. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  14121. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  14122. this._scaledDiffuse = new BABYLON.Color3();
  14123. this._scaledSpecular = new BABYLON.Color3();
  14124. this.getRenderTargetTextures = function () {
  14125. _this._renderTargets.reset();
  14126. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  14127. _this._renderTargets.push(_this.reflectionTexture);
  14128. }
  14129. return _this._renderTargets;
  14130. };
  14131. }
  14132. StandardMaterial.prototype.needAlphaBlending = function () {
  14133. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  14134. };
  14135. StandardMaterial.prototype.needAlphaTesting = function () {
  14136. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && !this.diffuseTexture.getAlphaFromRGB;
  14137. };
  14138. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  14139. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  14140. };
  14141. StandardMaterial.prototype.getAlphaTestTexture = function () {
  14142. return this.diffuseTexture;
  14143. };
  14144. // Methods
  14145. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  14146. if (this.checkReadyOnlyOnce) {
  14147. if (this._wasPreviouslyReady) {
  14148. return true;
  14149. }
  14150. }
  14151. var scene = this.getScene();
  14152. if (!this.checkReadyOnEveryCall) {
  14153. if (this._renderId === scene.getRenderId()) {
  14154. return true;
  14155. }
  14156. }
  14157. var engine = scene.getEngine();
  14158. var defines = [];
  14159. var fallbacks = new BABYLON.EffectFallbacks();
  14160. var needNormals = false;
  14161. var needUVs = false;
  14162. // Textures
  14163. if (scene.texturesEnabled) {
  14164. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  14165. if (!this.diffuseTexture.isReady()) {
  14166. return false;
  14167. }
  14168. else {
  14169. needUVs = true;
  14170. defines.push("#define DIFFUSE");
  14171. }
  14172. }
  14173. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  14174. if (!this.ambientTexture.isReady()) {
  14175. return false;
  14176. }
  14177. else {
  14178. needUVs = true;
  14179. defines.push("#define AMBIENT");
  14180. }
  14181. }
  14182. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  14183. if (!this.opacityTexture.isReady()) {
  14184. return false;
  14185. }
  14186. else {
  14187. needUVs = true;
  14188. defines.push("#define OPACITY");
  14189. if (this.opacityTexture.getAlphaFromRGB) {
  14190. defines.push("#define OPACITYRGB");
  14191. }
  14192. }
  14193. }
  14194. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  14195. if (!this.reflectionTexture.isReady()) {
  14196. return false;
  14197. }
  14198. else {
  14199. needNormals = true;
  14200. needUVs = true;
  14201. defines.push("#define REFLECTION");
  14202. fallbacks.addFallback(0, "REFLECTION");
  14203. }
  14204. }
  14205. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  14206. if (!this.emissiveTexture.isReady()) {
  14207. return false;
  14208. }
  14209. else {
  14210. needUVs = true;
  14211. defines.push("#define EMISSIVE");
  14212. }
  14213. }
  14214. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  14215. if (!this.specularTexture.isReady()) {
  14216. return false;
  14217. }
  14218. else {
  14219. needUVs = true;
  14220. defines.push("#define SPECULAR");
  14221. fallbacks.addFallback(0, "SPECULAR");
  14222. }
  14223. }
  14224. }
  14225. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  14226. if (!this.bumpTexture.isReady()) {
  14227. return false;
  14228. }
  14229. else {
  14230. needUVs = true;
  14231. defines.push("#define BUMP");
  14232. fallbacks.addFallback(0, "BUMP");
  14233. }
  14234. }
  14235. // Effect
  14236. if (this.useSpecularOverAlpha) {
  14237. defines.push("#define SPECULAROVERALPHA");
  14238. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  14239. }
  14240. if (scene.clipPlane) {
  14241. defines.push("#define CLIPPLANE");
  14242. }
  14243. if (engine.getAlphaTesting()) {
  14244. defines.push("#define ALPHATEST");
  14245. }
  14246. if (this._shouldUseAlphaFromDiffuseTexture()) {
  14247. defines.push("#define ALPHAFROMDIFFUSE");
  14248. }
  14249. // Point size
  14250. if (this.pointsCloud || scene.forcePointsCloud) {
  14251. defines.push("#define POINTSIZE");
  14252. }
  14253. // Fog
  14254. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  14255. defines.push("#define FOG");
  14256. fallbacks.addFallback(1, "FOG");
  14257. }
  14258. var shadowsActivated = false;
  14259. var lightIndex = 0;
  14260. if (scene.lightsEnabled) {
  14261. for (var index = 0; index < scene.lights.length; index++) {
  14262. var light = scene.lights[index];
  14263. if (!light.isEnabled()) {
  14264. continue;
  14265. }
  14266. // Excluded check
  14267. if (light._excludedMeshesIds.length > 0) {
  14268. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  14269. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  14270. if (excludedMesh) {
  14271. light.excludedMeshes.push(excludedMesh);
  14272. }
  14273. }
  14274. light._excludedMeshesIds = [];
  14275. }
  14276. // Included check
  14277. if (light._includedOnlyMeshesIds.length > 0) {
  14278. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  14279. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  14280. if (includedOnlyMesh) {
  14281. light.includedOnlyMeshes.push(includedOnlyMesh);
  14282. }
  14283. }
  14284. light._includedOnlyMeshesIds = [];
  14285. }
  14286. if (!light.canAffectMesh(mesh)) {
  14287. continue;
  14288. }
  14289. needNormals = true;
  14290. defines.push("#define LIGHT" + lightIndex);
  14291. if (lightIndex > 0) {
  14292. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  14293. }
  14294. var type;
  14295. if (light instanceof BABYLON.SpotLight) {
  14296. type = "#define SPOTLIGHT" + lightIndex;
  14297. }
  14298. else if (light instanceof BABYLON.HemisphericLight) {
  14299. type = "#define HEMILIGHT" + lightIndex;
  14300. }
  14301. else {
  14302. type = "#define POINTDIRLIGHT" + lightIndex;
  14303. }
  14304. defines.push(type);
  14305. if (lightIndex > 0) {
  14306. fallbacks.addFallback(lightIndex, type.replace("#define ", ""));
  14307. }
  14308. // Shadows
  14309. if (scene.shadowsEnabled) {
  14310. var shadowGenerator = light.getShadowGenerator();
  14311. if (mesh && mesh.receiveShadows && shadowGenerator) {
  14312. defines.push("#define SHADOW" + lightIndex);
  14313. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  14314. if (!shadowsActivated) {
  14315. defines.push("#define SHADOWS");
  14316. shadowsActivated = true;
  14317. }
  14318. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  14319. defines.push("#define SHADOWVSM" + lightIndex);
  14320. if (lightIndex > 0) {
  14321. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  14322. }
  14323. }
  14324. if (shadowGenerator.usePoissonSampling) {
  14325. defines.push("#define SHADOWPCF" + lightIndex);
  14326. if (lightIndex > 0) {
  14327. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  14328. }
  14329. }
  14330. }
  14331. }
  14332. lightIndex++;
  14333. if (lightIndex === maxSimultaneousLights)
  14334. break;
  14335. }
  14336. }
  14337. if (StandardMaterial.FresnelEnabled) {
  14338. // Fresnel
  14339. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled || this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled || this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  14340. var fresnelRank = 1;
  14341. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  14342. defines.push("#define DIFFUSEFRESNEL");
  14343. fallbacks.addFallback(fresnelRank, "DIFFUSEFRESNEL");
  14344. fresnelRank++;
  14345. }
  14346. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  14347. defines.push("#define OPACITYFRESNEL");
  14348. fallbacks.addFallback(fresnelRank, "OPACITYFRESNEL");
  14349. fresnelRank++;
  14350. }
  14351. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  14352. defines.push("#define REFLECTIONFRESNEL");
  14353. fallbacks.addFallback(fresnelRank, "REFLECTIONFRESNEL");
  14354. fresnelRank++;
  14355. }
  14356. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  14357. defines.push("#define EMISSIVEFRESNEL");
  14358. fallbacks.addFallback(fresnelRank, "EMISSIVEFRESNEL");
  14359. fresnelRank++;
  14360. }
  14361. needNormals = true;
  14362. defines.push("#define FRESNEL");
  14363. fallbacks.addFallback(fresnelRank - 1, "FRESNEL");
  14364. }
  14365. }
  14366. // Attribs
  14367. var attribs = [BABYLON.VertexBuffer.PositionKind];
  14368. if (mesh) {
  14369. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  14370. attribs.push(BABYLON.VertexBuffer.NormalKind);
  14371. defines.push("#define NORMAL");
  14372. }
  14373. if (needUVs) {
  14374. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  14375. attribs.push(BABYLON.VertexBuffer.UVKind);
  14376. defines.push("#define UV1");
  14377. }
  14378. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  14379. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  14380. defines.push("#define UV2");
  14381. }
  14382. }
  14383. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  14384. attribs.push(BABYLON.VertexBuffer.ColorKind);
  14385. defines.push("#define VERTEXCOLOR");
  14386. if (mesh.hasVertexAlpha) {
  14387. defines.push("#define VERTEXALPHA");
  14388. }
  14389. }
  14390. if (mesh.useBones) {
  14391. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  14392. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  14393. defines.push("#define BONES");
  14394. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  14395. defines.push("#define BONES4");
  14396. fallbacks.addFallback(0, "BONES4");
  14397. }
  14398. // Instances
  14399. if (useInstances) {
  14400. defines.push("#define INSTANCES");
  14401. attribs.push("world0");
  14402. attribs.push("world1");
  14403. attribs.push("world2");
  14404. attribs.push("world3");
  14405. }
  14406. }
  14407. // Get correct effect
  14408. var join = defines.join("\n");
  14409. if (this._cachedDefines !== join) {
  14410. this._cachedDefines = join;
  14411. scene.resetCachedMaterial();
  14412. // Legacy browser patch
  14413. var shaderName = "default";
  14414. if (!scene.getEngine().getCaps().standardDerivatives) {
  14415. shaderName = "legacydefault";
  14416. }
  14417. 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);
  14418. }
  14419. if (!this._effect.isReady()) {
  14420. return false;
  14421. }
  14422. this._renderId = scene.getRenderId();
  14423. this._wasPreviouslyReady = true;
  14424. return true;
  14425. };
  14426. StandardMaterial.prototype.unbind = function () {
  14427. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  14428. this._effect.setTexture("reflection2DSampler", null);
  14429. }
  14430. };
  14431. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  14432. this._effect.setMatrix("world", world);
  14433. };
  14434. StandardMaterial.prototype.bind = function (world, mesh) {
  14435. var scene = this.getScene();
  14436. // Matrices
  14437. this.bindOnlyWorldMatrix(world);
  14438. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  14439. // Bones
  14440. if (mesh.useBones) {
  14441. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  14442. }
  14443. if (scene.getCachedMaterial() !== this) {
  14444. if (StandardMaterial.FresnelEnabled) {
  14445. // Fresnel
  14446. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  14447. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  14448. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  14449. }
  14450. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  14451. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  14452. }
  14453. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  14454. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  14455. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  14456. }
  14457. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  14458. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  14459. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  14460. }
  14461. }
  14462. // Textures
  14463. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  14464. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  14465. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  14466. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  14467. }
  14468. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  14469. this._effect.setTexture("ambientSampler", this.ambientTexture);
  14470. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  14471. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  14472. }
  14473. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  14474. this._effect.setTexture("opacitySampler", this.opacityTexture);
  14475. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  14476. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  14477. }
  14478. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  14479. if (this.reflectionTexture.isCube) {
  14480. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  14481. }
  14482. else {
  14483. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  14484. }
  14485. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  14486. this._effect.setFloat3("vReflectionInfos", this.reflectionTexture.coordinatesMode, this.reflectionTexture.level, this.reflectionTexture.isCube ? 1 : 0);
  14487. }
  14488. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  14489. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  14490. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  14491. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  14492. }
  14493. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  14494. this._effect.setTexture("specularSampler", this.specularTexture);
  14495. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  14496. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  14497. }
  14498. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  14499. this._effect.setTexture("bumpSampler", this.bumpTexture);
  14500. this._effect.setFloat2("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level);
  14501. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  14502. }
  14503. // Clip plane
  14504. if (scene.clipPlane) {
  14505. var clipPlane = scene.clipPlane;
  14506. this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  14507. }
  14508. // Point size
  14509. if (this.pointsCloud) {
  14510. this._effect.setFloat("pointSize", this.pointSize);
  14511. }
  14512. // Colors
  14513. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  14514. // Scaling down color according to emissive
  14515. this._scaledSpecular.r = this.specularColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  14516. this._scaledSpecular.g = this.specularColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  14517. this._scaledSpecular.b = this.specularColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  14518. this._effect.setVector3("vEyePosition", scene.activeCamera.position);
  14519. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  14520. this._effect.setColor4("vSpecularColor", this._scaledSpecular, this.specularPower);
  14521. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  14522. }
  14523. // Scaling down color according to emissive
  14524. this._scaledDiffuse.r = this.diffuseColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  14525. this._scaledDiffuse.g = this.diffuseColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  14526. this._scaledDiffuse.b = this.diffuseColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  14527. this._effect.setColor4("vDiffuseColor", this._scaledDiffuse, this.alpha * mesh.visibility);
  14528. if (scene.lightsEnabled) {
  14529. var lightIndex = 0;
  14530. for (var index = 0; index < scene.lights.length; index++) {
  14531. var light = scene.lights[index];
  14532. if (!light.isEnabled()) {
  14533. continue;
  14534. }
  14535. if (!light.canAffectMesh(mesh)) {
  14536. continue;
  14537. }
  14538. if (light instanceof BABYLON.PointLight) {
  14539. // Point Light
  14540. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  14541. }
  14542. else if (light instanceof BABYLON.DirectionalLight) {
  14543. // Directional Light
  14544. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  14545. }
  14546. else if (light instanceof BABYLON.SpotLight) {
  14547. // Spot Light
  14548. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  14549. }
  14550. else if (light instanceof BABYLON.HemisphericLight) {
  14551. // Hemispheric Light
  14552. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  14553. }
  14554. light.diffuse.scaleToRef(light.intensity, this._scaledDiffuse);
  14555. light.specular.scaleToRef(light.intensity, this._scaledSpecular);
  14556. this._effect.setColor4("vLightDiffuse" + lightIndex, this._scaledDiffuse, light.range);
  14557. this._effect.setColor3("vLightSpecular" + lightIndex, this._scaledSpecular);
  14558. // Shadows
  14559. if (scene.shadowsEnabled) {
  14560. var shadowGenerator = light.getShadowGenerator();
  14561. if (mesh.receiveShadows && shadowGenerator) {
  14562. this._effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  14563. this._effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  14564. this._effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  14565. }
  14566. }
  14567. lightIndex++;
  14568. if (lightIndex === maxSimultaneousLights)
  14569. break;
  14570. }
  14571. }
  14572. // View
  14573. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  14574. this._effect.setMatrix("view", scene.getViewMatrix());
  14575. }
  14576. // Fog
  14577. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  14578. this._effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  14579. this._effect.setColor3("vFogColor", scene.fogColor);
  14580. }
  14581. _super.prototype.bind.call(this, world, mesh);
  14582. };
  14583. StandardMaterial.prototype.getAnimatables = function () {
  14584. var results = [];
  14585. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  14586. results.push(this.diffuseTexture);
  14587. }
  14588. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  14589. results.push(this.ambientTexture);
  14590. }
  14591. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  14592. results.push(this.opacityTexture);
  14593. }
  14594. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  14595. results.push(this.reflectionTexture);
  14596. }
  14597. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  14598. results.push(this.emissiveTexture);
  14599. }
  14600. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  14601. results.push(this.specularTexture);
  14602. }
  14603. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  14604. results.push(this.bumpTexture);
  14605. }
  14606. return results;
  14607. };
  14608. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  14609. if (this.diffuseTexture) {
  14610. this.diffuseTexture.dispose();
  14611. }
  14612. if (this.ambientTexture) {
  14613. this.ambientTexture.dispose();
  14614. }
  14615. if (this.opacityTexture) {
  14616. this.opacityTexture.dispose();
  14617. }
  14618. if (this.reflectionTexture) {
  14619. this.reflectionTexture.dispose();
  14620. }
  14621. if (this.emissiveTexture) {
  14622. this.emissiveTexture.dispose();
  14623. }
  14624. if (this.specularTexture) {
  14625. this.specularTexture.dispose();
  14626. }
  14627. if (this.bumpTexture) {
  14628. this.bumpTexture.dispose();
  14629. }
  14630. _super.prototype.dispose.call(this, forceDisposeEffect);
  14631. };
  14632. StandardMaterial.prototype.clone = function (name) {
  14633. var newStandardMaterial = new StandardMaterial(name, this.getScene());
  14634. // Base material
  14635. newStandardMaterial.checkReadyOnEveryCall = this.checkReadyOnEveryCall;
  14636. newStandardMaterial.alpha = this.alpha;
  14637. newStandardMaterial.fillMode = this.fillMode;
  14638. newStandardMaterial.backFaceCulling = this.backFaceCulling;
  14639. // Standard material
  14640. if (this.diffuseTexture && this.diffuseTexture.clone) {
  14641. newStandardMaterial.diffuseTexture = this.diffuseTexture.clone();
  14642. }
  14643. if (this.ambientTexture && this.ambientTexture.clone) {
  14644. newStandardMaterial.ambientTexture = this.ambientTexture.clone();
  14645. }
  14646. if (this.opacityTexture && this.opacityTexture.clone) {
  14647. newStandardMaterial.opacityTexture = this.opacityTexture.clone();
  14648. }
  14649. if (this.reflectionTexture && this.reflectionTexture.clone) {
  14650. newStandardMaterial.reflectionTexture = this.reflectionTexture.clone();
  14651. }
  14652. if (this.emissiveTexture && this.emissiveTexture.clone) {
  14653. newStandardMaterial.emissiveTexture = this.emissiveTexture.clone();
  14654. }
  14655. if (this.specularTexture && this.specularTexture.clone) {
  14656. newStandardMaterial.specularTexture = this.specularTexture.clone();
  14657. }
  14658. if (this.bumpTexture && this.bumpTexture.clone) {
  14659. newStandardMaterial.bumpTexture = this.bumpTexture.clone();
  14660. }
  14661. newStandardMaterial.ambientColor = this.ambientColor.clone();
  14662. newStandardMaterial.diffuseColor = this.diffuseColor.clone();
  14663. newStandardMaterial.specularColor = this.specularColor.clone();
  14664. newStandardMaterial.specularPower = this.specularPower;
  14665. newStandardMaterial.emissiveColor = this.emissiveColor.clone();
  14666. return newStandardMaterial;
  14667. };
  14668. // Statics
  14669. // Flags used to enable or disable a type of texture for all Standard Materials
  14670. StandardMaterial.DiffuseTextureEnabled = true;
  14671. StandardMaterial.AmbientTextureEnabled = true;
  14672. StandardMaterial.OpacityTextureEnabled = true;
  14673. StandardMaterial.ReflectionTextureEnabled = true;
  14674. StandardMaterial.EmissiveTextureEnabled = true;
  14675. StandardMaterial.SpecularTextureEnabled = true;
  14676. StandardMaterial.BumpTextureEnabled = true;
  14677. StandardMaterial.FresnelEnabled = true;
  14678. return StandardMaterial;
  14679. })(BABYLON.Material);
  14680. BABYLON.StandardMaterial = StandardMaterial;
  14681. })(BABYLON || (BABYLON = {}));
  14682. //# sourceMappingURL=babylon.standardMaterial.js.map
  14683. var BABYLON;
  14684. (function (BABYLON) {
  14685. var MultiMaterial = (function (_super) {
  14686. __extends(MultiMaterial, _super);
  14687. function MultiMaterial(name, scene) {
  14688. _super.call(this, name, scene, true);
  14689. this.subMaterials = new Array();
  14690. scene.multiMaterials.push(this);
  14691. }
  14692. // Properties
  14693. MultiMaterial.prototype.getSubMaterial = function (index) {
  14694. if (index < 0 || index >= this.subMaterials.length) {
  14695. return this.getScene().defaultMaterial;
  14696. }
  14697. return this.subMaterials[index];
  14698. };
  14699. // Methods
  14700. MultiMaterial.prototype.isReady = function (mesh) {
  14701. for (var index = 0; index < this.subMaterials.length; index++) {
  14702. var subMaterial = this.subMaterials[index];
  14703. if (subMaterial) {
  14704. if (!this.subMaterials[index].isReady(mesh)) {
  14705. return false;
  14706. }
  14707. }
  14708. }
  14709. return true;
  14710. };
  14711. return MultiMaterial;
  14712. })(BABYLON.Material);
  14713. BABYLON.MultiMaterial = MultiMaterial;
  14714. })(BABYLON || (BABYLON = {}));
  14715. //# sourceMappingURL=babylon.multiMaterial.js.mapvar BABYLON;
  14716. (function (BABYLON) {
  14717. var Database = (function () {
  14718. function Database(urlToScene, callbackManifestChecked) {
  14719. // Handling various flavors of prefixed version of IndexedDB
  14720. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  14721. this.callbackManifestChecked = callbackManifestChecked;
  14722. this.currentSceneUrl = BABYLON.Database.ReturnFullUrlLocation(urlToScene);
  14723. this.db = null;
  14724. this.enableSceneOffline = false;
  14725. this.enableTexturesOffline = false;
  14726. this.manifestVersionFound = 0;
  14727. this.mustUpdateRessources = false;
  14728. this.hasReachedQuota = false;
  14729. this.checkManifestFile();
  14730. }
  14731. Database.prototype.checkManifestFile = function () {
  14732. var _this = this;
  14733. function noManifestFile() {
  14734. //BABYLON.Tools.Log("Valid manifest file not found. Scene & textures will be loaded directly from the web server.");
  14735. that.enableSceneOffline = false;
  14736. that.enableTexturesOffline = false;
  14737. that.callbackManifestChecked(false);
  14738. }
  14739. var that = this;
  14740. var manifestURL = this.currentSceneUrl + ".manifest";
  14741. var xhr = new XMLHttpRequest();
  14742. var manifestURLTimeStamped = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  14743. xhr.open("GET", manifestURLTimeStamped, true);
  14744. xhr.addEventListener("load", function () {
  14745. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  14746. try {
  14747. var manifestFile = JSON.parse(xhr.response);
  14748. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  14749. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  14750. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  14751. _this.manifestVersionFound = manifestFile.version;
  14752. }
  14753. if (_this.callbackManifestChecked) {
  14754. _this.callbackManifestChecked(true);
  14755. }
  14756. }
  14757. catch (ex) {
  14758. noManifestFile();
  14759. }
  14760. }
  14761. else {
  14762. noManifestFile();
  14763. }
  14764. }, false);
  14765. xhr.addEventListener("error", function (event) {
  14766. noManifestFile();
  14767. }, false);
  14768. try {
  14769. xhr.send();
  14770. }
  14771. catch (ex) {
  14772. BABYLON.Tools.Error("Error on XHR send request.");
  14773. that.callbackManifestChecked(false);
  14774. }
  14775. };
  14776. Database.prototype.openAsync = function (successCallback, errorCallback) {
  14777. var _this = this;
  14778. function handleError() {
  14779. that.isSupported = false;
  14780. if (errorCallback)
  14781. errorCallback();
  14782. }
  14783. var that = this;
  14784. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  14785. // Your browser doesn't support IndexedDB
  14786. this.isSupported = false;
  14787. if (errorCallback)
  14788. errorCallback();
  14789. }
  14790. else {
  14791. // If the DB hasn't been opened or created yet
  14792. if (!this.db) {
  14793. this.hasReachedQuota = false;
  14794. this.isSupported = true;
  14795. var request = this.idbFactory.open("babylonjs", 1);
  14796. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  14797. request.onerror = function (event) {
  14798. handleError();
  14799. };
  14800. // executes when a version change transaction cannot complete due to other active transactions
  14801. request.onblocked = function (event) {
  14802. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  14803. handleError();
  14804. };
  14805. // DB has been opened successfully
  14806. request.onsuccess = function (event) {
  14807. _this.db = request.result;
  14808. successCallback();
  14809. };
  14810. // Initialization of the DB. Creating Scenes & Textures stores
  14811. request.onupgradeneeded = function (event) {
  14812. _this.db = (event.target).result;
  14813. try {
  14814. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  14815. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  14816. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  14817. }
  14818. catch (ex) {
  14819. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  14820. handleError();
  14821. }
  14822. };
  14823. }
  14824. else {
  14825. if (successCallback)
  14826. successCallback();
  14827. }
  14828. }
  14829. };
  14830. Database.prototype.loadImageFromDB = function (url, image) {
  14831. var _this = this;
  14832. var completeURL = Database.ReturnFullUrlLocation(url);
  14833. var saveAndLoadImage = function () {
  14834. if (!_this.hasReachedQuota && _this.db !== null) {
  14835. // the texture is not yet in the DB, let's try to save it
  14836. _this._saveImageIntoDBAsync(completeURL, image);
  14837. }
  14838. else {
  14839. image.src = url;
  14840. }
  14841. };
  14842. if (!this.mustUpdateRessources) {
  14843. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  14844. }
  14845. else {
  14846. saveAndLoadImage();
  14847. }
  14848. };
  14849. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  14850. if (this.isSupported && this.db !== null) {
  14851. var texture;
  14852. var transaction = this.db.transaction(["textures"]);
  14853. transaction.onabort = function (event) {
  14854. image.src = url;
  14855. };
  14856. transaction.oncomplete = function (event) {
  14857. var blobTextureURL;
  14858. if (texture) {
  14859. var URL = window.URL || window.webkitURL;
  14860. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  14861. image.onerror = function () {
  14862. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  14863. image.src = url;
  14864. };
  14865. image.src = blobTextureURL;
  14866. }
  14867. else {
  14868. notInDBCallback();
  14869. }
  14870. };
  14871. var getRequest = transaction.objectStore("textures").get(url);
  14872. getRequest.onsuccess = function (event) {
  14873. texture = (event.target).result;
  14874. };
  14875. getRequest.onerror = function (event) {
  14876. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  14877. image.src = url;
  14878. };
  14879. }
  14880. else {
  14881. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  14882. image.src = url;
  14883. }
  14884. };
  14885. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  14886. var _this = this;
  14887. if (this.isSupported) {
  14888. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  14889. var generateBlobUrl = function () {
  14890. var blobTextureURL;
  14891. if (blob) {
  14892. var URL = window.URL || window.webkitURL;
  14893. try {
  14894. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  14895. }
  14896. catch (ex) {
  14897. blobTextureURL = URL.createObjectURL(blob);
  14898. }
  14899. }
  14900. image.src = blobTextureURL;
  14901. };
  14902. if (Database.isUASupportingBlobStorage) {
  14903. var xhr = new XMLHttpRequest(), blob;
  14904. xhr.open("GET", url, true);
  14905. xhr.responseType = "blob";
  14906. xhr.addEventListener("load", function () {
  14907. if (xhr.status === 200) {
  14908. // Blob as response (XHR2)
  14909. blob = xhr.response;
  14910. var transaction = _this.db.transaction(["textures"], "readwrite");
  14911. // the transaction could abort because of a QuotaExceededError error
  14912. transaction.onabort = function (event) {
  14913. try {
  14914. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  14915. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  14916. this.hasReachedQuota = true;
  14917. }
  14918. }
  14919. catch (ex) {
  14920. }
  14921. generateBlobUrl();
  14922. };
  14923. transaction.oncomplete = function (event) {
  14924. generateBlobUrl();
  14925. };
  14926. var newTexture = { textureUrl: url, data: blob };
  14927. try {
  14928. // Put the blob into the dabase
  14929. var addRequest = transaction.objectStore("textures").put(newTexture);
  14930. addRequest.onsuccess = function (event) {
  14931. };
  14932. addRequest.onerror = function (event) {
  14933. generateBlobUrl();
  14934. };
  14935. }
  14936. catch (ex) {
  14937. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  14938. if (ex.code === 25) {
  14939. Database.isUASupportingBlobStorage = false;
  14940. }
  14941. image.src = url;
  14942. }
  14943. }
  14944. else {
  14945. image.src = url;
  14946. }
  14947. }, false);
  14948. xhr.addEventListener("error", function (event) {
  14949. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  14950. image.src = url;
  14951. }, false);
  14952. xhr.send();
  14953. }
  14954. else {
  14955. image.src = url;
  14956. }
  14957. }
  14958. else {
  14959. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  14960. image.src = url;
  14961. }
  14962. };
  14963. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  14964. var _this = this;
  14965. var updateVersion = function (event) {
  14966. // the version is not yet in the DB or we need to update it
  14967. _this._saveVersionIntoDBAsync(url, versionLoaded);
  14968. };
  14969. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  14970. };
  14971. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  14972. var _this = this;
  14973. if (this.isSupported) {
  14974. var version;
  14975. try {
  14976. var transaction = this.db.transaction(["versions"]);
  14977. transaction.oncomplete = function (event) {
  14978. if (version) {
  14979. // If the version in the JSON file is > than the version in DB
  14980. if (_this.manifestVersionFound > version.data) {
  14981. _this.mustUpdateRessources = true;
  14982. updateInDBCallback();
  14983. }
  14984. else {
  14985. callback(version.data);
  14986. }
  14987. }
  14988. else {
  14989. _this.mustUpdateRessources = true;
  14990. updateInDBCallback();
  14991. }
  14992. };
  14993. transaction.onabort = function (event) {
  14994. callback(-1);
  14995. };
  14996. var getRequest = transaction.objectStore("versions").get(url);
  14997. getRequest.onsuccess = function (event) {
  14998. version = (event.target).result;
  14999. };
  15000. getRequest.onerror = function (event) {
  15001. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  15002. callback(-1);
  15003. };
  15004. }
  15005. catch (ex) {
  15006. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  15007. callback(-1);
  15008. }
  15009. }
  15010. else {
  15011. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  15012. callback(-1);
  15013. }
  15014. };
  15015. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  15016. var _this = this;
  15017. if (this.isSupported && !this.hasReachedQuota) {
  15018. try {
  15019. // Open a transaction to the database
  15020. var transaction = this.db.transaction(["versions"], "readwrite");
  15021. // the transaction could abort because of a QuotaExceededError error
  15022. transaction.onabort = function (event) {
  15023. try {
  15024. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  15025. _this.hasReachedQuota = true;
  15026. }
  15027. }
  15028. catch (ex) {
  15029. }
  15030. callback(-1);
  15031. };
  15032. transaction.oncomplete = function (event) {
  15033. callback(_this.manifestVersionFound);
  15034. };
  15035. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  15036. // Put the scene into the database
  15037. var addRequest = transaction.objectStore("versions").put(newVersion);
  15038. addRequest.onsuccess = function (event) {
  15039. };
  15040. addRequest.onerror = function (event) {
  15041. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  15042. };
  15043. }
  15044. catch (ex) {
  15045. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  15046. callback(-1);
  15047. }
  15048. }
  15049. else {
  15050. callback(-1);
  15051. }
  15052. };
  15053. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  15054. var _this = this;
  15055. var completeUrl = Database.ReturnFullUrlLocation(url);
  15056. var saveAndLoadFile = function (event) {
  15057. // the scene is not yet in the DB, let's try to save it
  15058. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  15059. };
  15060. this._checkVersionFromDB(completeUrl, function (version) {
  15061. if (version !== -1) {
  15062. if (!_this.mustUpdateRessources) {
  15063. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  15064. }
  15065. else {
  15066. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  15067. }
  15068. }
  15069. else {
  15070. errorCallback();
  15071. }
  15072. });
  15073. };
  15074. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  15075. if (this.isSupported) {
  15076. var targetStore;
  15077. if (url.indexOf(".babylon") !== -1) {
  15078. targetStore = "scenes";
  15079. }
  15080. else {
  15081. targetStore = "textures";
  15082. }
  15083. var file;
  15084. var transaction = this.db.transaction([targetStore]);
  15085. transaction.oncomplete = function (event) {
  15086. if (file) {
  15087. callback(file.data);
  15088. }
  15089. else {
  15090. notInDBCallback();
  15091. }
  15092. };
  15093. transaction.onabort = function (event) {
  15094. notInDBCallback();
  15095. };
  15096. var getRequest = transaction.objectStore(targetStore).get(url);
  15097. getRequest.onsuccess = function (event) {
  15098. file = (event.target).result;
  15099. };
  15100. getRequest.onerror = function (event) {
  15101. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  15102. notInDBCallback();
  15103. };
  15104. }
  15105. else {
  15106. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  15107. callback();
  15108. }
  15109. };
  15110. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  15111. var _this = this;
  15112. if (this.isSupported) {
  15113. var targetStore;
  15114. if (url.indexOf(".babylon") !== -1) {
  15115. targetStore = "scenes";
  15116. }
  15117. else {
  15118. targetStore = "textures";
  15119. }
  15120. // Create XHR
  15121. var xhr = new XMLHttpRequest(), fileData;
  15122. xhr.open("GET", url, true);
  15123. if (useArrayBuffer) {
  15124. xhr.responseType = "arraybuffer";
  15125. }
  15126. xhr.onprogress = progressCallback;
  15127. xhr.addEventListener("load", function () {
  15128. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  15129. // Blob as response (XHR2)
  15130. //fileData = xhr.responseText;
  15131. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  15132. if (!_this.hasReachedQuota) {
  15133. // Open a transaction to the database
  15134. var transaction = _this.db.transaction([targetStore], "readwrite");
  15135. // the transaction could abort because of a QuotaExceededError error
  15136. transaction.onabort = function (event) {
  15137. try {
  15138. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  15139. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  15140. this.hasReachedQuota = true;
  15141. }
  15142. }
  15143. catch (ex) {
  15144. }
  15145. callback(fileData);
  15146. };
  15147. transaction.oncomplete = function (event) {
  15148. callback(fileData);
  15149. };
  15150. var newFile;
  15151. if (targetStore === "scenes") {
  15152. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  15153. }
  15154. else {
  15155. newFile = { textureUrl: url, data: fileData };
  15156. }
  15157. try {
  15158. // Put the scene into the database
  15159. var addRequest = transaction.objectStore(targetStore).put(newFile);
  15160. addRequest.onsuccess = function (event) {
  15161. };
  15162. addRequest.onerror = function (event) {
  15163. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  15164. };
  15165. }
  15166. catch (ex) {
  15167. callback(fileData);
  15168. }
  15169. }
  15170. else {
  15171. callback(fileData);
  15172. }
  15173. }
  15174. else {
  15175. callback();
  15176. }
  15177. }, false);
  15178. xhr.addEventListener("error", function (event) {
  15179. BABYLON.Tools.Error("error on XHR request.");
  15180. callback();
  15181. }, false);
  15182. xhr.send();
  15183. }
  15184. else {
  15185. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  15186. callback();
  15187. }
  15188. };
  15189. Database.isUASupportingBlobStorage = true;
  15190. Database.parseURL = function (url) {
  15191. var a = document.createElement('a');
  15192. a.href = url;
  15193. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  15194. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  15195. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  15196. return absLocation;
  15197. };
  15198. Database.ReturnFullUrlLocation = function (url) {
  15199. if (url.indexOf("http:/") === -1) {
  15200. return (BABYLON.Database.parseURL(window.location.href) + url);
  15201. }
  15202. else {
  15203. return url;
  15204. }
  15205. };
  15206. return Database;
  15207. })();
  15208. BABYLON.Database = Database;
  15209. })(BABYLON || (BABYLON = {}));
  15210. //# sourceMappingURL=babylon.database.js.mapvar BABYLON;
  15211. (function (BABYLON) {
  15212. var SpriteManager = (function () {
  15213. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  15214. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  15215. this.name = name;
  15216. this.cellSize = cellSize;
  15217. this.sprites = new Array();
  15218. this.renderingGroupId = 0;
  15219. this.fogEnabled = true;
  15220. this._vertexDeclaration = [3, 4, 4, 4];
  15221. this._vertexStrideSize = 15 * 4; // 15 floats per sprite (x, y, z, angle, size, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color)
  15222. this._capacity = capacity;
  15223. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  15224. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  15225. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  15226. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  15227. this._scene = scene;
  15228. this._scene.spriteManagers.push(this);
  15229. // VBO
  15230. this._vertexDeclaration = [3, 4, 4, 4];
  15231. this._vertexStrideSize = 15 * 4;
  15232. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  15233. var indices = [];
  15234. var index = 0;
  15235. for (var count = 0; count < capacity; count++) {
  15236. indices.push(index);
  15237. indices.push(index + 1);
  15238. indices.push(index + 2);
  15239. indices.push(index);
  15240. indices.push(index + 2);
  15241. indices.push(index + 3);
  15242. index += 4;
  15243. }
  15244. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  15245. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  15246. // Effects
  15247. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  15248. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  15249. }
  15250. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  15251. var arrayOffset = index * 15;
  15252. if (offsetX === 0)
  15253. offsetX = this._epsilon;
  15254. else if (offsetX === 1)
  15255. offsetX = 1 - this._epsilon;
  15256. if (offsetY === 0)
  15257. offsetY = this._epsilon;
  15258. else if (offsetY === 1)
  15259. offsetY = 1 - this._epsilon;
  15260. this._vertices[arrayOffset] = sprite.position.x;
  15261. this._vertices[arrayOffset + 1] = sprite.position.y;
  15262. this._vertices[arrayOffset + 2] = sprite.position.z;
  15263. this._vertices[arrayOffset + 3] = sprite.angle;
  15264. this._vertices[arrayOffset + 4] = sprite.size;
  15265. this._vertices[arrayOffset + 5] = offsetX;
  15266. this._vertices[arrayOffset + 6] = offsetY;
  15267. this._vertices[arrayOffset + 7] = sprite.invertU ? 1 : 0;
  15268. this._vertices[arrayOffset + 8] = sprite.invertV ? 1 : 0;
  15269. var offset = (sprite.cellIndex / rowSize) >> 0;
  15270. this._vertices[arrayOffset + 9] = sprite.cellIndex - offset * rowSize;
  15271. this._vertices[arrayOffset + 10] = offset;
  15272. // Color
  15273. this._vertices[arrayOffset + 11] = sprite.color.r;
  15274. this._vertices[arrayOffset + 12] = sprite.color.g;
  15275. this._vertices[arrayOffset + 13] = sprite.color.b;
  15276. this._vertices[arrayOffset + 14] = sprite.color.a;
  15277. };
  15278. SpriteManager.prototype.render = function () {
  15279. // Check
  15280. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  15281. return;
  15282. var engine = this._scene.getEngine();
  15283. var baseSize = this._spriteTexture.getBaseSize();
  15284. // Sprites
  15285. var deltaTime = engine.getDeltaTime();
  15286. var max = Math.min(this._capacity, this.sprites.length);
  15287. var rowSize = baseSize.width / this.cellSize;
  15288. var offset = 0;
  15289. for (var index = 0; index < max; index++) {
  15290. var sprite = this.sprites[index];
  15291. if (!sprite) {
  15292. continue;
  15293. }
  15294. sprite._animate(deltaTime);
  15295. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  15296. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  15297. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  15298. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  15299. }
  15300. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  15301. // Render
  15302. var effect = this._effectBase;
  15303. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  15304. effect = this._effectFog;
  15305. }
  15306. engine.enableEffect(effect);
  15307. var viewMatrix = this._scene.getViewMatrix();
  15308. effect.setTexture("diffuseSampler", this._spriteTexture);
  15309. effect.setMatrix("view", viewMatrix);
  15310. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  15311. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  15312. // Fog
  15313. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  15314. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  15315. effect.setColor3("vFogColor", this._scene.fogColor);
  15316. }
  15317. // VBOs
  15318. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  15319. // Draw order
  15320. effect.setBool("alphaTest", true);
  15321. engine.setColorWrite(false);
  15322. engine.draw(true, 0, max * 6);
  15323. engine.setColorWrite(true);
  15324. effect.setBool("alphaTest", false);
  15325. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  15326. engine.draw(true, 0, max * 6);
  15327. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  15328. };
  15329. SpriteManager.prototype.dispose = function () {
  15330. if (this._vertexBuffer) {
  15331. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  15332. this._vertexBuffer = null;
  15333. }
  15334. if (this._indexBuffer) {
  15335. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  15336. this._indexBuffer = null;
  15337. }
  15338. if (this._spriteTexture) {
  15339. this._spriteTexture.dispose();
  15340. this._spriteTexture = null;
  15341. }
  15342. // Remove from scene
  15343. var index = this._scene.spriteManagers.indexOf(this);
  15344. this._scene.spriteManagers.splice(index, 1);
  15345. // Callback
  15346. if (this.onDispose) {
  15347. this.onDispose();
  15348. }
  15349. };
  15350. return SpriteManager;
  15351. })();
  15352. BABYLON.SpriteManager = SpriteManager;
  15353. })(BABYLON || (BABYLON = {}));
  15354. //# sourceMappingURL=babylon.spriteManager.js.mapvar BABYLON;
  15355. (function (BABYLON) {
  15356. var Sprite = (function () {
  15357. function Sprite(name, manager) {
  15358. this.name = name;
  15359. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  15360. this.size = 1.0;
  15361. this.angle = 0;
  15362. this.cellIndex = 0;
  15363. this.invertU = 0;
  15364. this.invertV = 0;
  15365. this.animations = new Array();
  15366. this._animationStarted = false;
  15367. this._loopAnimation = false;
  15368. this._fromIndex = 0;
  15369. this._toIndex = 0;
  15370. this._delay = 0;
  15371. this._direction = 1;
  15372. this._frameCount = 0;
  15373. this._time = 0;
  15374. this._manager = manager;
  15375. this._manager.sprites.push(this);
  15376. this.position = BABYLON.Vector3.Zero();
  15377. }
  15378. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  15379. this._fromIndex = from;
  15380. this._toIndex = to;
  15381. this._loopAnimation = loop;
  15382. this._delay = delay;
  15383. this._animationStarted = true;
  15384. this._direction = from < to ? 1 : -1;
  15385. this.cellIndex = from;
  15386. this._time = 0;
  15387. };
  15388. Sprite.prototype.stopAnimation = function () {
  15389. this._animationStarted = false;
  15390. };
  15391. Sprite.prototype._animate = function (deltaTime) {
  15392. if (!this._animationStarted)
  15393. return;
  15394. this._time += deltaTime;
  15395. if (this._time > this._delay) {
  15396. this._time = this._time % this._delay;
  15397. this.cellIndex += this._direction;
  15398. if (this.cellIndex == this._toIndex) {
  15399. if (this._loopAnimation) {
  15400. this.cellIndex = this._fromIndex;
  15401. }
  15402. else {
  15403. this._animationStarted = false;
  15404. if (this.disposeWhenFinishedAnimating) {
  15405. this.dispose();
  15406. }
  15407. }
  15408. }
  15409. }
  15410. };
  15411. Sprite.prototype.dispose = function () {
  15412. for (var i = 0; i < this._manager.sprites.length; i++) {
  15413. if (this._manager.sprites[i] == this) {
  15414. this._manager.sprites.splice(i, 1);
  15415. }
  15416. }
  15417. };
  15418. return Sprite;
  15419. })();
  15420. BABYLON.Sprite = Sprite;
  15421. })(BABYLON || (BABYLON = {}));
  15422. //# sourceMappingURL=babylon.sprite.js.mapvar BABYLON;
  15423. (function (BABYLON) {
  15424. var Layer = (function () {
  15425. function Layer(name, imgUrl, scene, isBackground, color) {
  15426. this.name = name;
  15427. this._vertexDeclaration = [2];
  15428. this._vertexStrideSize = 2 * 4;
  15429. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  15430. this.isBackground = isBackground === undefined ? true : isBackground;
  15431. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  15432. this._scene = scene;
  15433. this._scene.layers.push(this);
  15434. // VBO
  15435. var vertices = [];
  15436. vertices.push(1, 1);
  15437. vertices.push(-1, 1);
  15438. vertices.push(-1, -1);
  15439. vertices.push(1, -1);
  15440. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  15441. // Indices
  15442. var indices = [];
  15443. indices.push(0);
  15444. indices.push(1);
  15445. indices.push(2);
  15446. indices.push(0);
  15447. indices.push(2);
  15448. indices.push(3);
  15449. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  15450. // Effects
  15451. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color"], ["textureSampler"], "");
  15452. }
  15453. Layer.prototype.render = function () {
  15454. // Check
  15455. if (!this._effect.isReady() || !this.texture || !this.texture.isReady())
  15456. return;
  15457. var engine = this._scene.getEngine();
  15458. // Render
  15459. engine.enableEffect(this._effect);
  15460. engine.setState(false);
  15461. // Texture
  15462. this._effect.setTexture("textureSampler", this.texture);
  15463. this._effect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  15464. // Color
  15465. this._effect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  15466. // VBOs
  15467. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  15468. // Draw order
  15469. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  15470. engine.draw(true, 0, 6);
  15471. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  15472. };
  15473. Layer.prototype.dispose = function () {
  15474. if (this._vertexBuffer) {
  15475. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  15476. this._vertexBuffer = null;
  15477. }
  15478. if (this._indexBuffer) {
  15479. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  15480. this._indexBuffer = null;
  15481. }
  15482. if (this.texture) {
  15483. this.texture.dispose();
  15484. this.texture = null;
  15485. }
  15486. // Remove from scene
  15487. var index = this._scene.layers.indexOf(this);
  15488. this._scene.layers.splice(index, 1);
  15489. // Callback
  15490. if (this.onDispose) {
  15491. this.onDispose();
  15492. }
  15493. };
  15494. return Layer;
  15495. })();
  15496. BABYLON.Layer = Layer;
  15497. })(BABYLON || (BABYLON = {}));
  15498. //# sourceMappingURL=babylon.layer.js.mapvar BABYLON;
  15499. (function (BABYLON) {
  15500. var Particle = (function () {
  15501. function Particle() {
  15502. this.position = BABYLON.Vector3.Zero();
  15503. this.direction = BABYLON.Vector3.Zero();
  15504. this.color = new BABYLON.Color4(0, 0, 0, 0);
  15505. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  15506. this.lifeTime = 1.0;
  15507. this.age = 0;
  15508. this.size = 0;
  15509. this.angle = 0;
  15510. this.angularSpeed = 0;
  15511. }
  15512. Particle.prototype.copyTo = function (other) {
  15513. other.position.copyFrom(this.position);
  15514. other.direction.copyFrom(this.direction);
  15515. other.color.copyFrom(this.color);
  15516. other.colorStep.copyFrom(this.colorStep);
  15517. other.lifeTime = this.lifeTime;
  15518. other.age = this.age;
  15519. other.size = this.size;
  15520. other.angle = this.angle;
  15521. other.angularSpeed = this.angularSpeed;
  15522. };
  15523. return Particle;
  15524. })();
  15525. BABYLON.Particle = Particle;
  15526. })(BABYLON || (BABYLON = {}));
  15527. //# sourceMappingURL=babylon.particle.js.mapvar BABYLON;
  15528. (function (BABYLON) {
  15529. var randomNumber = function (min, max) {
  15530. if (min === max) {
  15531. return (min);
  15532. }
  15533. var random = Math.random();
  15534. return ((random * (max - min)) + min);
  15535. };
  15536. var ParticleSystem = (function () {
  15537. function ParticleSystem(name, capacity, scene, customEffect) {
  15538. var _this = this;
  15539. this.name = name;
  15540. this.renderingGroupId = 0;
  15541. this.emitter = null;
  15542. this.emitRate = 10;
  15543. this.manualEmitCount = -1;
  15544. this.updateSpeed = 0.01;
  15545. this.targetStopDuration = 0;
  15546. this.disposeOnStop = false;
  15547. this.minEmitPower = 1;
  15548. this.maxEmitPower = 1;
  15549. this.minLifeTime = 1;
  15550. this.maxLifeTime = 1;
  15551. this.minSize = 1;
  15552. this.maxSize = 1;
  15553. this.minAngularSpeed = 0;
  15554. this.maxAngularSpeed = 0;
  15555. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  15556. this.forceDepthWrite = false;
  15557. this.gravity = BABYLON.Vector3.Zero();
  15558. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  15559. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  15560. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  15561. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  15562. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  15563. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  15564. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  15565. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  15566. this.particles = new Array();
  15567. this._vertexDeclaration = [3, 4, 4];
  15568. this._vertexStrideSize = 11 * 4; // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY)
  15569. this._stockParticles = new Array();
  15570. this._newPartsExcess = 0;
  15571. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  15572. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  15573. this._scaledDirection = BABYLON.Vector3.Zero();
  15574. this._scaledGravity = BABYLON.Vector3.Zero();
  15575. this._currentRenderId = -1;
  15576. this._started = false;
  15577. this._stopped = false;
  15578. this._actualFrame = 0;
  15579. this.id = name;
  15580. this._capacity = capacity;
  15581. this._scene = scene;
  15582. this._customEffect = customEffect;
  15583. scene.particleSystems.push(this);
  15584. // VBO
  15585. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  15586. var indices = [];
  15587. var index = 0;
  15588. for (var count = 0; count < capacity; count++) {
  15589. indices.push(index);
  15590. indices.push(index + 1);
  15591. indices.push(index + 2);
  15592. indices.push(index);
  15593. indices.push(index + 2);
  15594. indices.push(index + 3);
  15595. index += 4;
  15596. }
  15597. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  15598. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  15599. // Default behaviors
  15600. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate) {
  15601. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  15602. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  15603. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  15604. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  15605. };
  15606. this.startPositionFunction = function (worldMatrix, positionToUpdate) {
  15607. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  15608. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  15609. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  15610. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  15611. };
  15612. this.updateFunction = function (particles) {
  15613. for (var index = 0; index < particles.length; index++) {
  15614. var particle = particles[index];
  15615. particle.age += _this._scaledUpdateSpeed;
  15616. if (particle.age >= particle.lifeTime) {
  15617. _this.recycleParticle(particle);
  15618. index--;
  15619. continue;
  15620. }
  15621. else {
  15622. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  15623. particle.color.addInPlace(_this._scaledColorStep);
  15624. if (particle.color.a < 0)
  15625. particle.color.a = 0;
  15626. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  15627. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  15628. particle.position.addInPlace(_this._scaledDirection);
  15629. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  15630. particle.direction.addInPlace(_this._scaledGravity);
  15631. }
  15632. }
  15633. };
  15634. }
  15635. ParticleSystem.prototype.recycleParticle = function (particle) {
  15636. var lastParticle = this.particles.pop();
  15637. if (lastParticle !== particle) {
  15638. lastParticle.copyTo(particle);
  15639. this._stockParticles.push(lastParticle);
  15640. }
  15641. };
  15642. ParticleSystem.prototype.getCapacity = function () {
  15643. return this._capacity;
  15644. };
  15645. ParticleSystem.prototype.isAlive = function () {
  15646. return this._alive;
  15647. };
  15648. ParticleSystem.prototype.isStarted = function () {
  15649. return this._started;
  15650. };
  15651. ParticleSystem.prototype.start = function () {
  15652. this._started = true;
  15653. this._stopped = false;
  15654. this._actualFrame = 0;
  15655. };
  15656. ParticleSystem.prototype.stop = function () {
  15657. this._stopped = true;
  15658. };
  15659. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  15660. var offset = index * 11;
  15661. this._vertices[offset] = particle.position.x;
  15662. this._vertices[offset + 1] = particle.position.y;
  15663. this._vertices[offset + 2] = particle.position.z;
  15664. this._vertices[offset + 3] = particle.color.r;
  15665. this._vertices[offset + 4] = particle.color.g;
  15666. this._vertices[offset + 5] = particle.color.b;
  15667. this._vertices[offset + 6] = particle.color.a;
  15668. this._vertices[offset + 7] = particle.angle;
  15669. this._vertices[offset + 8] = particle.size;
  15670. this._vertices[offset + 9] = offsetX;
  15671. this._vertices[offset + 10] = offsetY;
  15672. };
  15673. ParticleSystem.prototype._update = function (newParticles) {
  15674. // Update current
  15675. this._alive = this.particles.length > 0;
  15676. this.updateFunction(this.particles);
  15677. // Add new ones
  15678. var worldMatrix;
  15679. if (this.emitter.position) {
  15680. worldMatrix = this.emitter.getWorldMatrix();
  15681. }
  15682. else {
  15683. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  15684. }
  15685. for (var index = 0; index < newParticles; index++) {
  15686. if (this.particles.length === this._capacity) {
  15687. break;
  15688. }
  15689. if (this._stockParticles.length !== 0) {
  15690. var particle = this._stockParticles.pop();
  15691. particle.age = 0;
  15692. }
  15693. else {
  15694. particle = new BABYLON.Particle();
  15695. }
  15696. this.particles.push(particle);
  15697. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  15698. this.startDirectionFunction(emitPower, worldMatrix, particle.direction);
  15699. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  15700. particle.size = randomNumber(this.minSize, this.maxSize);
  15701. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  15702. this.startPositionFunction(worldMatrix, particle.position);
  15703. var step = randomNumber(0, 1.0);
  15704. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  15705. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  15706. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  15707. }
  15708. };
  15709. ParticleSystem.prototype._getEffect = function () {
  15710. if (this._customEffect) {
  15711. return this._customEffect;
  15712. }
  15713. ;
  15714. var defines = [];
  15715. if (this._scene.clipPlane) {
  15716. defines.push("#define CLIPPLANE");
  15717. }
  15718. // Effect
  15719. var join = defines.join("\n");
  15720. if (this._cachedDefines !== join) {
  15721. this._cachedDefines = join;
  15722. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  15723. }
  15724. return this._effect;
  15725. };
  15726. ParticleSystem.prototype.animate = function () {
  15727. if (!this._started)
  15728. return;
  15729. var effect = this._getEffect();
  15730. // Check
  15731. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  15732. return;
  15733. if (this._currentRenderId === this._scene.getRenderId()) {
  15734. return;
  15735. }
  15736. this._currentRenderId = this._scene.getRenderId();
  15737. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  15738. // determine the number of particles we need to create
  15739. var emitCout;
  15740. if (this.manualEmitCount > -1) {
  15741. emitCout = this.manualEmitCount;
  15742. this.manualEmitCount = 0;
  15743. }
  15744. else {
  15745. emitCout = this.emitRate;
  15746. }
  15747. var newParticles = ((emitCout * this._scaledUpdateSpeed) >> 0);
  15748. this._newPartsExcess += emitCout * this._scaledUpdateSpeed - newParticles;
  15749. if (this._newPartsExcess > 1.0) {
  15750. newParticles += this._newPartsExcess >> 0;
  15751. this._newPartsExcess -= this._newPartsExcess >> 0;
  15752. }
  15753. this._alive = false;
  15754. if (!this._stopped) {
  15755. this._actualFrame += this._scaledUpdateSpeed;
  15756. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  15757. this.stop();
  15758. }
  15759. else {
  15760. newParticles = 0;
  15761. }
  15762. this._update(newParticles);
  15763. // Stopped?
  15764. if (this._stopped) {
  15765. if (!this._alive) {
  15766. this._started = false;
  15767. if (this.disposeOnStop) {
  15768. this._scene._toBeDisposed.push(this);
  15769. }
  15770. }
  15771. }
  15772. // Update VBO
  15773. var offset = 0;
  15774. for (var index = 0; index < this.particles.length; index++) {
  15775. var particle = this.particles[index];
  15776. this._appendParticleVertex(offset++, particle, 0, 0);
  15777. this._appendParticleVertex(offset++, particle, 1, 0);
  15778. this._appendParticleVertex(offset++, particle, 1, 1);
  15779. this._appendParticleVertex(offset++, particle, 0, 1);
  15780. }
  15781. var engine = this._scene.getEngine();
  15782. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  15783. };
  15784. ParticleSystem.prototype.render = function () {
  15785. var effect = this._getEffect();
  15786. // Check
  15787. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  15788. return 0;
  15789. var engine = this._scene.getEngine();
  15790. // Render
  15791. engine.enableEffect(effect);
  15792. engine.setState(false);
  15793. var viewMatrix = this._scene.getViewMatrix();
  15794. effect.setTexture("diffuseSampler", this.particleTexture);
  15795. effect.setMatrix("view", viewMatrix);
  15796. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  15797. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  15798. if (this._scene.clipPlane) {
  15799. var clipPlane = this._scene.clipPlane;
  15800. var invView = viewMatrix.clone();
  15801. invView.invert();
  15802. effect.setMatrix("invView", invView);
  15803. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  15804. }
  15805. // VBOs
  15806. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  15807. // Draw order
  15808. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  15809. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  15810. }
  15811. else {
  15812. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  15813. }
  15814. if (this.forceDepthWrite) {
  15815. engine.setDepthWrite(true);
  15816. }
  15817. engine.draw(true, 0, this.particles.length * 6);
  15818. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  15819. return this.particles.length;
  15820. };
  15821. ParticleSystem.prototype.dispose = function () {
  15822. if (this._vertexBuffer) {
  15823. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  15824. this._vertexBuffer = null;
  15825. }
  15826. if (this._indexBuffer) {
  15827. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  15828. this._indexBuffer = null;
  15829. }
  15830. if (this.particleTexture) {
  15831. this.particleTexture.dispose();
  15832. this.particleTexture = null;
  15833. }
  15834. // Remove from scene
  15835. var index = this._scene.particleSystems.indexOf(this);
  15836. this._scene.particleSystems.splice(index, 1);
  15837. // Callback
  15838. if (this.onDispose) {
  15839. this.onDispose();
  15840. }
  15841. };
  15842. // Clone
  15843. ParticleSystem.prototype.clone = function (name, newEmitter) {
  15844. var result = new ParticleSystem(name, this._capacity, this._scene);
  15845. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  15846. if (newEmitter === undefined) {
  15847. newEmitter = this.emitter;
  15848. }
  15849. result.emitter = newEmitter;
  15850. if (this.particleTexture) {
  15851. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  15852. }
  15853. result.start();
  15854. return result;
  15855. };
  15856. // Statics
  15857. ParticleSystem.BLENDMODE_ONEONE = 0;
  15858. ParticleSystem.BLENDMODE_STANDARD = 1;
  15859. return ParticleSystem;
  15860. })();
  15861. BABYLON.ParticleSystem = ParticleSystem;
  15862. })(BABYLON || (BABYLON = {}));
  15863. //# sourceMappingURL=babylon.particleSystem.js.mapvar BABYLON;
  15864. (function (BABYLON) {
  15865. var Animation = (function () {
  15866. function Animation(name, targetProperty, framePerSecond, dataType, loopMode) {
  15867. this.name = name;
  15868. this.targetProperty = targetProperty;
  15869. this.framePerSecond = framePerSecond;
  15870. this.dataType = dataType;
  15871. this.loopMode = loopMode;
  15872. this._offsetsCache = {};
  15873. this._highLimitsCache = {};
  15874. this._stopped = false;
  15875. this.targetPropertyPath = targetProperty.split(".");
  15876. this.dataType = dataType;
  15877. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  15878. }
  15879. Animation.CreateAndStartAnimation = function (name, mesh, tartgetProperty, framePerSecond, totalFrame, from, to, loopMode) {
  15880. var dataType = undefined;
  15881. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  15882. dataType = Animation.ANIMATIONTYPE_FLOAT;
  15883. }
  15884. else if (from instanceof BABYLON.Quaternion) {
  15885. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  15886. }
  15887. else if (from instanceof BABYLON.Vector3) {
  15888. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  15889. }
  15890. else if (from instanceof BABYLON.Vector2) {
  15891. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  15892. }
  15893. else if (from instanceof BABYLON.Color3) {
  15894. dataType = Animation.ANIMATIONTYPE_COLOR3;
  15895. }
  15896. if (dataType == undefined) {
  15897. return null;
  15898. }
  15899. var animation = new Animation(name, tartgetProperty, framePerSecond, dataType, loopMode);
  15900. var keys = [];
  15901. keys.push({ frame: 0, value: from });
  15902. keys.push({ frame: totalFrame, value: to });
  15903. animation.setKeys(keys);
  15904. mesh.animations.push(animation);
  15905. return mesh.getScene().beginAnimation(mesh, 0, totalFrame, (animation.loopMode === 1));
  15906. };
  15907. // Methods
  15908. Animation.prototype.isStopped = function () {
  15909. return this._stopped;
  15910. };
  15911. Animation.prototype.getKeys = function () {
  15912. return this._keys;
  15913. };
  15914. Animation.prototype.getEasingFunction = function () {
  15915. return this._easingFunction;
  15916. };
  15917. Animation.prototype.setEasingFunction = function (easingFunction) {
  15918. this._easingFunction = easingFunction;
  15919. };
  15920. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  15921. return startValue + (endValue - startValue) * gradient;
  15922. };
  15923. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  15924. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  15925. };
  15926. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  15927. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  15928. };
  15929. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  15930. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  15931. };
  15932. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  15933. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  15934. };
  15935. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  15936. var startScale = new BABYLON.Vector3(0, 0, 0);
  15937. var startRotation = new BABYLON.Quaternion();
  15938. var startTranslation = new BABYLON.Vector3(0, 0, 0);
  15939. startValue.decompose(startScale, startRotation, startTranslation);
  15940. var endScale = new BABYLON.Vector3(0, 0, 0);
  15941. var endRotation = new BABYLON.Quaternion();
  15942. var endTranslation = new BABYLON.Vector3(0, 0, 0);
  15943. endValue.decompose(endScale, endRotation, endTranslation);
  15944. var resultScale = this.vector3InterpolateFunction(startScale, endScale, gradient);
  15945. var resultRotation = this.quaternionInterpolateFunction(startRotation, endRotation, gradient);
  15946. var resultTranslation = this.vector3InterpolateFunction(startTranslation, endTranslation, gradient);
  15947. var result = BABYLON.Matrix.Compose(resultScale, resultRotation, resultTranslation);
  15948. return result;
  15949. };
  15950. Animation.prototype.clone = function () {
  15951. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  15952. clone.setKeys(this._keys);
  15953. return clone;
  15954. };
  15955. Animation.prototype.setKeys = function (values) {
  15956. this._keys = values.slice(0);
  15957. this._offsetsCache = {};
  15958. this._highLimitsCache = {};
  15959. };
  15960. Animation.prototype._getKeyValue = function (value) {
  15961. if (typeof value === "function") {
  15962. return value();
  15963. }
  15964. return value;
  15965. };
  15966. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  15967. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  15968. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  15969. }
  15970. this.currentFrame = currentFrame;
  15971. for (var key = 0; key < this._keys.length; key++) {
  15972. // for each frame, we need the key just before the frame superior
  15973. if (this._keys[key + 1].frame >= currentFrame) {
  15974. var startValue = this._getKeyValue(this._keys[key].value);
  15975. var endValue = this._getKeyValue(this._keys[key + 1].value);
  15976. // gradient : percent of currentFrame between the frame inf and the frame sup
  15977. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  15978. // check for easingFunction and correction of gradient
  15979. if (this._easingFunction != null) {
  15980. gradient = this._easingFunction.ease(gradient);
  15981. }
  15982. switch (this.dataType) {
  15983. case Animation.ANIMATIONTYPE_FLOAT:
  15984. switch (loopMode) {
  15985. case Animation.ANIMATIONLOOPMODE_CYCLE:
  15986. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  15987. return this.floatInterpolateFunction(startValue, endValue, gradient);
  15988. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  15989. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  15990. }
  15991. break;
  15992. case Animation.ANIMATIONTYPE_QUATERNION:
  15993. var quaternion = null;
  15994. switch (loopMode) {
  15995. case Animation.ANIMATIONLOOPMODE_CYCLE:
  15996. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  15997. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  15998. break;
  15999. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  16000. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  16001. break;
  16002. }
  16003. return quaternion;
  16004. case Animation.ANIMATIONTYPE_VECTOR3:
  16005. switch (loopMode) {
  16006. case Animation.ANIMATIONLOOPMODE_CYCLE:
  16007. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  16008. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  16009. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  16010. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  16011. }
  16012. case Animation.ANIMATIONTYPE_VECTOR2:
  16013. switch (loopMode) {
  16014. case Animation.ANIMATIONLOOPMODE_CYCLE:
  16015. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  16016. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  16017. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  16018. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  16019. }
  16020. case Animation.ANIMATIONTYPE_COLOR3:
  16021. switch (loopMode) {
  16022. case Animation.ANIMATIONLOOPMODE_CYCLE:
  16023. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  16024. return this.color3InterpolateFunction(startValue, endValue, gradient);
  16025. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  16026. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  16027. }
  16028. case Animation.ANIMATIONTYPE_MATRIX:
  16029. switch (loopMode) {
  16030. case Animation.ANIMATIONLOOPMODE_CYCLE:
  16031. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  16032. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  16033. return startValue;
  16034. }
  16035. default:
  16036. break;
  16037. }
  16038. break;
  16039. }
  16040. }
  16041. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  16042. };
  16043. Animation.prototype.animate = function (delay, from, to, loop, speedRatio) {
  16044. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  16045. this._stopped = true;
  16046. return false;
  16047. }
  16048. var returnValue = true;
  16049. // Adding a start key at frame 0 if missing
  16050. if (this._keys[0].frame !== 0) {
  16051. var newKey = { frame: 0, value: this._keys[0].value };
  16052. this._keys.splice(0, 0, newKey);
  16053. }
  16054. // Check limits
  16055. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  16056. from = this._keys[0].frame;
  16057. }
  16058. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  16059. to = this._keys[this._keys.length - 1].frame;
  16060. }
  16061. // Compute ratio
  16062. var range = to - from;
  16063. var offsetValue;
  16064. // ratio represents the frame delta between from and to
  16065. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  16066. var highLimitValue = 0;
  16067. if (ratio > range && !loop) {
  16068. returnValue = false;
  16069. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  16070. }
  16071. else {
  16072. // Get max value if required
  16073. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  16074. var keyOffset = to.toString() + from.toString();
  16075. if (!this._offsetsCache[keyOffset]) {
  16076. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  16077. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  16078. switch (this.dataType) {
  16079. case Animation.ANIMATIONTYPE_FLOAT:
  16080. this._offsetsCache[keyOffset] = toValue - fromValue;
  16081. break;
  16082. case Animation.ANIMATIONTYPE_QUATERNION:
  16083. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  16084. break;
  16085. case Animation.ANIMATIONTYPE_VECTOR3:
  16086. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  16087. case Animation.ANIMATIONTYPE_VECTOR2:
  16088. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  16089. case Animation.ANIMATIONTYPE_COLOR3:
  16090. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  16091. default:
  16092. break;
  16093. }
  16094. this._highLimitsCache[keyOffset] = toValue;
  16095. }
  16096. highLimitValue = this._highLimitsCache[keyOffset];
  16097. offsetValue = this._offsetsCache[keyOffset];
  16098. }
  16099. }
  16100. if (offsetValue === undefined) {
  16101. switch (this.dataType) {
  16102. case Animation.ANIMATIONTYPE_FLOAT:
  16103. offsetValue = 0;
  16104. break;
  16105. case Animation.ANIMATIONTYPE_QUATERNION:
  16106. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  16107. break;
  16108. case Animation.ANIMATIONTYPE_VECTOR3:
  16109. offsetValue = BABYLON.Vector3.Zero();
  16110. break;
  16111. case Animation.ANIMATIONTYPE_VECTOR2:
  16112. offsetValue = BABYLON.Vector2.Zero();
  16113. break;
  16114. case Animation.ANIMATIONTYPE_COLOR3:
  16115. offsetValue = BABYLON.Color3.Black();
  16116. }
  16117. }
  16118. // Compute value
  16119. var repeatCount = (ratio / range) >> 0;
  16120. var currentFrame = returnValue ? from + ratio % range : to;
  16121. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  16122. // Set value
  16123. if (this.targetPropertyPath.length > 1) {
  16124. var property = this._target[this.targetPropertyPath[0]];
  16125. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  16126. property = property[this.targetPropertyPath[index]];
  16127. }
  16128. property[this.targetPropertyPath[this.targetPropertyPath.length - 1]] = currentValue;
  16129. }
  16130. else {
  16131. this._target[this.targetPropertyPath[0]] = currentValue;
  16132. }
  16133. if (this._target.markAsDirty) {
  16134. this._target.markAsDirty(this.targetProperty);
  16135. }
  16136. if (!returnValue) {
  16137. this._stopped = true;
  16138. }
  16139. return returnValue;
  16140. };
  16141. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  16142. get: function () {
  16143. return Animation._ANIMATIONTYPE_FLOAT;
  16144. },
  16145. enumerable: true,
  16146. configurable: true
  16147. });
  16148. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  16149. get: function () {
  16150. return Animation._ANIMATIONTYPE_VECTOR3;
  16151. },
  16152. enumerable: true,
  16153. configurable: true
  16154. });
  16155. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  16156. get: function () {
  16157. return Animation._ANIMATIONTYPE_VECTOR2;
  16158. },
  16159. enumerable: true,
  16160. configurable: true
  16161. });
  16162. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  16163. get: function () {
  16164. return Animation._ANIMATIONTYPE_QUATERNION;
  16165. },
  16166. enumerable: true,
  16167. configurable: true
  16168. });
  16169. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  16170. get: function () {
  16171. return Animation._ANIMATIONTYPE_MATRIX;
  16172. },
  16173. enumerable: true,
  16174. configurable: true
  16175. });
  16176. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  16177. get: function () {
  16178. return Animation._ANIMATIONTYPE_COLOR3;
  16179. },
  16180. enumerable: true,
  16181. configurable: true
  16182. });
  16183. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  16184. get: function () {
  16185. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  16186. },
  16187. enumerable: true,
  16188. configurable: true
  16189. });
  16190. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  16191. get: function () {
  16192. return Animation._ANIMATIONLOOPMODE_CYCLE;
  16193. },
  16194. enumerable: true,
  16195. configurable: true
  16196. });
  16197. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  16198. get: function () {
  16199. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  16200. },
  16201. enumerable: true,
  16202. configurable: true
  16203. });
  16204. // Statics
  16205. Animation._ANIMATIONTYPE_FLOAT = 0;
  16206. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  16207. Animation._ANIMATIONTYPE_QUATERNION = 2;
  16208. Animation._ANIMATIONTYPE_MATRIX = 3;
  16209. Animation._ANIMATIONTYPE_COLOR3 = 4;
  16210. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  16211. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  16212. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  16213. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  16214. return Animation;
  16215. })();
  16216. BABYLON.Animation = Animation;
  16217. })(BABYLON || (BABYLON = {}));
  16218. //# sourceMappingURL=babylon.animation.js.mapvar BABYLON;
  16219. (function (BABYLON) {
  16220. var Animatable = (function () {
  16221. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  16222. if (fromFrame === void 0) { fromFrame = 0; }
  16223. if (toFrame === void 0) { toFrame = 100; }
  16224. if (loopAnimation === void 0) { loopAnimation = false; }
  16225. if (speedRatio === void 0) { speedRatio = 1.0; }
  16226. this.target = target;
  16227. this.fromFrame = fromFrame;
  16228. this.toFrame = toFrame;
  16229. this.loopAnimation = loopAnimation;
  16230. this.speedRatio = speedRatio;
  16231. this.onAnimationEnd = onAnimationEnd;
  16232. this._animations = new Array();
  16233. this._paused = false;
  16234. this.animationStarted = false;
  16235. if (animations) {
  16236. this.appendAnimations(target, animations);
  16237. }
  16238. this._scene = scene;
  16239. scene._activeAnimatables.push(this);
  16240. }
  16241. // Methods
  16242. Animatable.prototype.appendAnimations = function (target, animations) {
  16243. for (var index = 0; index < animations.length; index++) {
  16244. var animation = animations[index];
  16245. animation._target = target;
  16246. this._animations.push(animation);
  16247. }
  16248. };
  16249. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  16250. var animations = this._animations;
  16251. for (var index = 0; index < animations.length; index++) {
  16252. if (animations[index].targetProperty === property) {
  16253. return animations[index];
  16254. }
  16255. }
  16256. return null;
  16257. };
  16258. Animatable.prototype.pause = function () {
  16259. if (this._paused) {
  16260. return;
  16261. }
  16262. this._paused = true;
  16263. };
  16264. Animatable.prototype.restart = function () {
  16265. this._paused = false;
  16266. };
  16267. Animatable.prototype.stop = function () {
  16268. var index = this._scene._activeAnimatables.indexOf(this);
  16269. if (index > -1) {
  16270. this._scene._activeAnimatables.splice(index, 1);
  16271. }
  16272. if (this.onAnimationEnd) {
  16273. this.onAnimationEnd();
  16274. }
  16275. };
  16276. Animatable.prototype._animate = function (delay) {
  16277. if (this._paused) {
  16278. if (!this._pausedDelay) {
  16279. this._pausedDelay = delay;
  16280. }
  16281. return true;
  16282. }
  16283. if (!this._localDelayOffset) {
  16284. this._localDelayOffset = delay;
  16285. }
  16286. else if (this._pausedDelay) {
  16287. this._localDelayOffset += delay - this._pausedDelay;
  16288. this._pausedDelay = null;
  16289. }
  16290. // Animating
  16291. var running = false;
  16292. var animations = this._animations;
  16293. for (var index = 0; index < animations.length; index++) {
  16294. var animation = animations[index];
  16295. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  16296. running = running || isRunning;
  16297. }
  16298. if (!running && this.onAnimationEnd) {
  16299. this.onAnimationEnd();
  16300. }
  16301. return running;
  16302. };
  16303. return Animatable;
  16304. })();
  16305. BABYLON.Animatable = Animatable;
  16306. })(BABYLON || (BABYLON = {}));
  16307. //# sourceMappingURL=babylon.animatable.js.map
  16308. var BABYLON;
  16309. (function (BABYLON) {
  16310. var EasingFunction = (function () {
  16311. function EasingFunction() {
  16312. // Properties
  16313. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  16314. }
  16315. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  16316. get: function () {
  16317. return EasingFunction._EASINGMODE_EASEIN;
  16318. },
  16319. enumerable: true,
  16320. configurable: true
  16321. });
  16322. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  16323. get: function () {
  16324. return EasingFunction._EASINGMODE_EASEOUT;
  16325. },
  16326. enumerable: true,
  16327. configurable: true
  16328. });
  16329. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  16330. get: function () {
  16331. return EasingFunction._EASINGMODE_EASEINOUT;
  16332. },
  16333. enumerable: true,
  16334. configurable: true
  16335. });
  16336. EasingFunction.prototype.setEasingMode = function (easingMode) {
  16337. var n = Math.min(Math.max(easingMode, 0), 2);
  16338. this._easingMode = n;
  16339. };
  16340. EasingFunction.prototype.getEasingMode = function () {
  16341. return this._easingMode;
  16342. };
  16343. EasingFunction.prototype.easeInCore = function (gradient) {
  16344. throw new Error('You must implement this method');
  16345. };
  16346. EasingFunction.prototype.ease = function (gradient) {
  16347. switch (this._easingMode) {
  16348. case EasingFunction.EASINGMODE_EASEIN:
  16349. return this.easeInCore(gradient);
  16350. case EasingFunction.EASINGMODE_EASEOUT:
  16351. return (1 - this.easeInCore(1 - gradient));
  16352. }
  16353. if (gradient >= 0.5) {
  16354. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  16355. }
  16356. return (this.easeInCore(gradient * 2) * 0.5);
  16357. };
  16358. //Statics
  16359. EasingFunction._EASINGMODE_EASEIN = 0;
  16360. EasingFunction._EASINGMODE_EASEOUT = 1;
  16361. EasingFunction._EASINGMODE_EASEINOUT = 2;
  16362. return EasingFunction;
  16363. })();
  16364. BABYLON.EasingFunction = EasingFunction;
  16365. var CircleEase = (function (_super) {
  16366. __extends(CircleEase, _super);
  16367. function CircleEase() {
  16368. _super.apply(this, arguments);
  16369. }
  16370. CircleEase.prototype.easeInCore = function (gradient) {
  16371. gradient = Math.max(0, Math.min(1, gradient));
  16372. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  16373. };
  16374. return CircleEase;
  16375. })(EasingFunction);
  16376. BABYLON.CircleEase = CircleEase;
  16377. var BackEase = (function (_super) {
  16378. __extends(BackEase, _super);
  16379. function BackEase(amplitude) {
  16380. if (amplitude === void 0) { amplitude = 1; }
  16381. _super.call(this);
  16382. this.amplitude = amplitude;
  16383. }
  16384. BackEase.prototype.easeInCore = function (gradient) {
  16385. var num = Math.max(0, this.amplitude);
  16386. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  16387. };
  16388. return BackEase;
  16389. })(EasingFunction);
  16390. BABYLON.BackEase = BackEase;
  16391. var BounceEase = (function (_super) {
  16392. __extends(BounceEase, _super);
  16393. function BounceEase(bounces, bounciness) {
  16394. if (bounces === void 0) { bounces = 3; }
  16395. if (bounciness === void 0) { bounciness = 2; }
  16396. _super.call(this);
  16397. this.bounces = bounces;
  16398. this.bounciness = bounciness;
  16399. }
  16400. BounceEase.prototype.easeInCore = function (gradient) {
  16401. var y = Math.max(0.0, this.bounces);
  16402. var bounciness = this.bounciness;
  16403. if (bounciness <= 1.0) {
  16404. bounciness = 1.001;
  16405. }
  16406. var num9 = Math.pow(bounciness, y);
  16407. var num5 = 1.0 - bounciness;
  16408. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  16409. var num15 = gradient * num4;
  16410. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  16411. var num3 = Math.floor(num65);
  16412. var num13 = num3 + 1.0;
  16413. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  16414. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  16415. var num7 = (num8 + num12) * 0.5;
  16416. var num6 = gradient - num7;
  16417. var num2 = num7 - num8;
  16418. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  16419. };
  16420. return BounceEase;
  16421. })(EasingFunction);
  16422. BABYLON.BounceEase = BounceEase;
  16423. var CubicEase = (function (_super) {
  16424. __extends(CubicEase, _super);
  16425. function CubicEase() {
  16426. _super.apply(this, arguments);
  16427. }
  16428. CubicEase.prototype.easeInCore = function (gradient) {
  16429. return (gradient * gradient * gradient);
  16430. };
  16431. return CubicEase;
  16432. })(EasingFunction);
  16433. BABYLON.CubicEase = CubicEase;
  16434. var ElasticEase = (function (_super) {
  16435. __extends(ElasticEase, _super);
  16436. function ElasticEase(oscillations, springiness) {
  16437. if (oscillations === void 0) { oscillations = 3; }
  16438. if (springiness === void 0) { springiness = 3; }
  16439. _super.call(this);
  16440. this.oscillations = oscillations;
  16441. this.springiness = springiness;
  16442. }
  16443. ElasticEase.prototype.easeInCore = function (gradient) {
  16444. var num2;
  16445. var num3 = Math.max(0.0, this.oscillations);
  16446. var num = Math.max(0.0, this.springiness);
  16447. if (num == 0) {
  16448. num2 = gradient;
  16449. }
  16450. else {
  16451. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  16452. }
  16453. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  16454. };
  16455. return ElasticEase;
  16456. })(EasingFunction);
  16457. BABYLON.ElasticEase = ElasticEase;
  16458. var ExponentialEase = (function (_super) {
  16459. __extends(ExponentialEase, _super);
  16460. function ExponentialEase(exponent) {
  16461. if (exponent === void 0) { exponent = 2; }
  16462. _super.call(this);
  16463. this.exponent = exponent;
  16464. }
  16465. ExponentialEase.prototype.easeInCore = function (gradient) {
  16466. if (this.exponent <= 0) {
  16467. return gradient;
  16468. }
  16469. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  16470. };
  16471. return ExponentialEase;
  16472. })(EasingFunction);
  16473. BABYLON.ExponentialEase = ExponentialEase;
  16474. var PowerEase = (function (_super) {
  16475. __extends(PowerEase, _super);
  16476. function PowerEase(power) {
  16477. if (power === void 0) { power = 2; }
  16478. _super.call(this);
  16479. this.power = power;
  16480. }
  16481. PowerEase.prototype.easeInCore = function (gradient) {
  16482. var y = Math.max(0.0, this.power);
  16483. return Math.pow(gradient, y);
  16484. };
  16485. return PowerEase;
  16486. })(EasingFunction);
  16487. BABYLON.PowerEase = PowerEase;
  16488. var QuadraticEase = (function (_super) {
  16489. __extends(QuadraticEase, _super);
  16490. function QuadraticEase() {
  16491. _super.apply(this, arguments);
  16492. }
  16493. QuadraticEase.prototype.easeInCore = function (gradient) {
  16494. return (gradient * gradient);
  16495. };
  16496. return QuadraticEase;
  16497. })(EasingFunction);
  16498. BABYLON.QuadraticEase = QuadraticEase;
  16499. var QuarticEase = (function (_super) {
  16500. __extends(QuarticEase, _super);
  16501. function QuarticEase() {
  16502. _super.apply(this, arguments);
  16503. }
  16504. QuarticEase.prototype.easeInCore = function (gradient) {
  16505. return (gradient * gradient * gradient * gradient);
  16506. };
  16507. return QuarticEase;
  16508. })(EasingFunction);
  16509. BABYLON.QuarticEase = QuarticEase;
  16510. var QuinticEase = (function (_super) {
  16511. __extends(QuinticEase, _super);
  16512. function QuinticEase() {
  16513. _super.apply(this, arguments);
  16514. }
  16515. QuinticEase.prototype.easeInCore = function (gradient) {
  16516. return (gradient * gradient * gradient * gradient * gradient);
  16517. };
  16518. return QuinticEase;
  16519. })(EasingFunction);
  16520. BABYLON.QuinticEase = QuinticEase;
  16521. var SineEase = (function (_super) {
  16522. __extends(SineEase, _super);
  16523. function SineEase() {
  16524. _super.apply(this, arguments);
  16525. }
  16526. SineEase.prototype.easeInCore = function (gradient) {
  16527. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  16528. };
  16529. return SineEase;
  16530. })(EasingFunction);
  16531. BABYLON.SineEase = SineEase;
  16532. var BezierCurveEase = (function (_super) {
  16533. __extends(BezierCurveEase, _super);
  16534. function BezierCurveEase(x1, y1, x2, y2) {
  16535. if (x1 === void 0) { x1 = 0; }
  16536. if (y1 === void 0) { y1 = 0; }
  16537. if (x2 === void 0) { x2 = 1; }
  16538. if (y2 === void 0) { y2 = 1; }
  16539. _super.call(this);
  16540. this.x1 = x1;
  16541. this.y1 = y1;
  16542. this.x2 = x2;
  16543. this.y2 = y2;
  16544. }
  16545. BezierCurveEase.prototype.easeInCore = function (gradient) {
  16546. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  16547. };
  16548. return BezierCurveEase;
  16549. })(EasingFunction);
  16550. BABYLON.BezierCurveEase = BezierCurveEase;
  16551. })(BABYLON || (BABYLON = {}));
  16552. //# sourceMappingURL=babylon.easing.js.mapvar BABYLON;
  16553. (function (BABYLON) {
  16554. var Octree = (function () {
  16555. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  16556. if (maxDepth === void 0) { maxDepth = 2; }
  16557. this.maxDepth = maxDepth;
  16558. this.dynamicContent = new Array();
  16559. this._maxBlockCapacity = maxBlockCapacity || 64;
  16560. this._selectionContent = new BABYLON.SmartArray(1024);
  16561. this._creationFunc = creationFunc;
  16562. }
  16563. // Methods
  16564. Octree.prototype.update = function (worldMin, worldMax, entries) {
  16565. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  16566. };
  16567. Octree.prototype.addMesh = function (entry) {
  16568. for (var index = 0; index < this.blocks.length; index++) {
  16569. var block = this.blocks[index];
  16570. block.addEntry(entry);
  16571. }
  16572. };
  16573. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  16574. this._selectionContent.reset();
  16575. for (var index = 0; index < this.blocks.length; index++) {
  16576. var block = this.blocks[index];
  16577. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  16578. }
  16579. if (allowDuplicate) {
  16580. this._selectionContent.concat(this.dynamicContent);
  16581. }
  16582. else {
  16583. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  16584. }
  16585. return this._selectionContent;
  16586. };
  16587. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  16588. this._selectionContent.reset();
  16589. for (var index = 0; index < this.blocks.length; index++) {
  16590. var block = this.blocks[index];
  16591. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  16592. }
  16593. if (allowDuplicate) {
  16594. this._selectionContent.concat(this.dynamicContent);
  16595. }
  16596. else {
  16597. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  16598. }
  16599. return this._selectionContent;
  16600. };
  16601. Octree.prototype.intersectsRay = function (ray) {
  16602. this._selectionContent.reset();
  16603. for (var index = 0; index < this.blocks.length; index++) {
  16604. var block = this.blocks[index];
  16605. block.intersectsRay(ray, this._selectionContent);
  16606. }
  16607. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  16608. return this._selectionContent;
  16609. };
  16610. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  16611. target.blocks = new Array();
  16612. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  16613. for (var x = 0; x < 2; x++) {
  16614. for (var y = 0; y < 2; y++) {
  16615. for (var z = 0; z < 2; z++) {
  16616. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  16617. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  16618. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  16619. block.addEntries(entries);
  16620. target.blocks.push(block);
  16621. }
  16622. }
  16623. }
  16624. };
  16625. Octree.CreationFuncForMeshes = function (entry, block) {
  16626. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  16627. block.entries.push(entry);
  16628. }
  16629. };
  16630. Octree.CreationFuncForSubMeshes = function (entry, block) {
  16631. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  16632. block.entries.push(entry);
  16633. }
  16634. };
  16635. return Octree;
  16636. })();
  16637. BABYLON.Octree = Octree;
  16638. })(BABYLON || (BABYLON = {}));
  16639. //# sourceMappingURL=babylon.octree.js.mapvar BABYLON;
  16640. (function (BABYLON) {
  16641. var OctreeBlock = (function () {
  16642. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  16643. this.entries = new Array();
  16644. this._boundingVectors = new Array();
  16645. this._capacity = capacity;
  16646. this._depth = depth;
  16647. this._maxDepth = maxDepth;
  16648. this._creationFunc = creationFunc;
  16649. this._minPoint = minPoint;
  16650. this._maxPoint = maxPoint;
  16651. this._boundingVectors.push(minPoint.clone());
  16652. this._boundingVectors.push(maxPoint.clone());
  16653. this._boundingVectors.push(minPoint.clone());
  16654. this._boundingVectors[2].x = maxPoint.x;
  16655. this._boundingVectors.push(minPoint.clone());
  16656. this._boundingVectors[3].y = maxPoint.y;
  16657. this._boundingVectors.push(minPoint.clone());
  16658. this._boundingVectors[4].z = maxPoint.z;
  16659. this._boundingVectors.push(maxPoint.clone());
  16660. this._boundingVectors[5].z = minPoint.z;
  16661. this._boundingVectors.push(maxPoint.clone());
  16662. this._boundingVectors[6].x = minPoint.x;
  16663. this._boundingVectors.push(maxPoint.clone());
  16664. this._boundingVectors[7].y = minPoint.y;
  16665. }
  16666. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  16667. // Property
  16668. get: function () {
  16669. return this._capacity;
  16670. },
  16671. enumerable: true,
  16672. configurable: true
  16673. });
  16674. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  16675. get: function () {
  16676. return this._minPoint;
  16677. },
  16678. enumerable: true,
  16679. configurable: true
  16680. });
  16681. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  16682. get: function () {
  16683. return this._maxPoint;
  16684. },
  16685. enumerable: true,
  16686. configurable: true
  16687. });
  16688. // Methods
  16689. OctreeBlock.prototype.addEntry = function (entry) {
  16690. if (this.blocks) {
  16691. for (var index = 0; index < this.blocks.length; index++) {
  16692. var block = this.blocks[index];
  16693. block.addEntry(entry);
  16694. }
  16695. return;
  16696. }
  16697. this._creationFunc(entry, this);
  16698. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  16699. this.createInnerBlocks();
  16700. }
  16701. };
  16702. OctreeBlock.prototype.addEntries = function (entries) {
  16703. for (var index = 0; index < entries.length; index++) {
  16704. var mesh = entries[index];
  16705. this.addEntry(mesh);
  16706. }
  16707. };
  16708. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  16709. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  16710. if (this.blocks) {
  16711. for (var index = 0; index < this.blocks.length; index++) {
  16712. var block = this.blocks[index];
  16713. block.select(frustumPlanes, selection, allowDuplicate);
  16714. }
  16715. return;
  16716. }
  16717. if (allowDuplicate) {
  16718. selection.concat(this.entries);
  16719. }
  16720. else {
  16721. selection.concatWithNoDuplicate(this.entries);
  16722. }
  16723. }
  16724. };
  16725. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  16726. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  16727. if (this.blocks) {
  16728. for (var index = 0; index < this.blocks.length; index++) {
  16729. var block = this.blocks[index];
  16730. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  16731. }
  16732. return;
  16733. }
  16734. if (allowDuplicate) {
  16735. selection.concat(this.entries);
  16736. }
  16737. else {
  16738. selection.concatWithNoDuplicate(this.entries);
  16739. }
  16740. }
  16741. };
  16742. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  16743. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  16744. if (this.blocks) {
  16745. for (var index = 0; index < this.blocks.length; index++) {
  16746. var block = this.blocks[index];
  16747. block.intersectsRay(ray, selection);
  16748. }
  16749. return;
  16750. }
  16751. selection.concatWithNoDuplicate(this.entries);
  16752. }
  16753. };
  16754. OctreeBlock.prototype.createInnerBlocks = function () {
  16755. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  16756. };
  16757. return OctreeBlock;
  16758. })();
  16759. BABYLON.OctreeBlock = OctreeBlock;
  16760. })(BABYLON || (BABYLON = {}));
  16761. //# sourceMappingURL=babylon.octreeBlock.js.mapvar BABYLON;
  16762. (function (BABYLON) {
  16763. var Bone = (function () {
  16764. function Bone(name, skeleton, parentBone, matrix) {
  16765. this.name = name;
  16766. this.children = new Array();
  16767. this.animations = new Array();
  16768. this._worldTransform = new BABYLON.Matrix();
  16769. this._absoluteTransform = new BABYLON.Matrix();
  16770. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  16771. this._skeleton = skeleton;
  16772. this._matrix = matrix;
  16773. this._baseMatrix = matrix;
  16774. skeleton.bones.push(this);
  16775. if (parentBone) {
  16776. this._parent = parentBone;
  16777. parentBone.children.push(this);
  16778. }
  16779. else {
  16780. this._parent = null;
  16781. }
  16782. this._updateDifferenceMatrix();
  16783. }
  16784. // Members
  16785. Bone.prototype.getParent = function () {
  16786. return this._parent;
  16787. };
  16788. Bone.prototype.getLocalMatrix = function () {
  16789. return this._matrix;
  16790. };
  16791. Bone.prototype.getBaseMatrix = function () {
  16792. return this._baseMatrix;
  16793. };
  16794. Bone.prototype.getWorldMatrix = function () {
  16795. return this._worldTransform;
  16796. };
  16797. Bone.prototype.getInvertedAbsoluteTransform = function () {
  16798. return this._invertedAbsoluteTransform;
  16799. };
  16800. Bone.prototype.getAbsoluteMatrix = function () {
  16801. var matrix = this._matrix.clone();
  16802. var parent = this._parent;
  16803. while (parent) {
  16804. matrix = matrix.multiply(parent.getLocalMatrix());
  16805. parent = parent.getParent();
  16806. }
  16807. return matrix;
  16808. };
  16809. // Methods
  16810. Bone.prototype.updateMatrix = function (matrix) {
  16811. this._matrix = matrix;
  16812. this._skeleton._markAsDirty();
  16813. this._updateDifferenceMatrix();
  16814. };
  16815. Bone.prototype._updateDifferenceMatrix = function () {
  16816. if (this._parent) {
  16817. this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  16818. }
  16819. else {
  16820. this._absoluteTransform.copyFrom(this._matrix);
  16821. }
  16822. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  16823. for (var index = 0; index < this.children.length; index++) {
  16824. this.children[index]._updateDifferenceMatrix();
  16825. }
  16826. };
  16827. Bone.prototype.markAsDirty = function () {
  16828. this._skeleton._markAsDirty();
  16829. };
  16830. return Bone;
  16831. })();
  16832. BABYLON.Bone = Bone;
  16833. })(BABYLON || (BABYLON = {}));
  16834. //# sourceMappingURL=babylon.bone.js.mapvar BABYLON;
  16835. (function (BABYLON) {
  16836. var Skeleton = (function () {
  16837. function Skeleton(name, id, scene) {
  16838. this.name = name;
  16839. this.id = id;
  16840. this.bones = new Array();
  16841. this._isDirty = true;
  16842. this._identity = BABYLON.Matrix.Identity();
  16843. this.bones = [];
  16844. this._scene = scene;
  16845. scene.skeletons.push(this);
  16846. }
  16847. // Members
  16848. Skeleton.prototype.getTransformMatrices = function () {
  16849. return this._transformMatrices;
  16850. };
  16851. // Methods
  16852. Skeleton.prototype._markAsDirty = function () {
  16853. this._isDirty = true;
  16854. };
  16855. Skeleton.prototype.prepare = function () {
  16856. if (!this._isDirty) {
  16857. return;
  16858. }
  16859. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  16860. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  16861. }
  16862. for (var index = 0; index < this.bones.length; index++) {
  16863. var bone = this.bones[index];
  16864. var parentBone = bone.getParent();
  16865. if (parentBone) {
  16866. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  16867. }
  16868. else {
  16869. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  16870. }
  16871. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), this._transformMatrices, index * 16);
  16872. }
  16873. this._identity.copyToArray(this._transformMatrices, this.bones.length * 16);
  16874. this._isDirty = false;
  16875. this._scene._activeBones += this.bones.length;
  16876. };
  16877. Skeleton.prototype.getAnimatables = function () {
  16878. if (!this._animatables || this._animatables.length !== this.bones.length) {
  16879. this._animatables = [];
  16880. for (var index = 0; index < this.bones.length; index++) {
  16881. this._animatables.push(this.bones[index]);
  16882. }
  16883. }
  16884. return this._animatables;
  16885. };
  16886. Skeleton.prototype.clone = function (name, id) {
  16887. var result = new Skeleton(name, id || name, this._scene);
  16888. for (var index = 0; index < this.bones.length; index++) {
  16889. var source = this.bones[index];
  16890. var parentBone = null;
  16891. if (source.getParent()) {
  16892. var parentIndex = this.bones.indexOf(source.getParent());
  16893. parentBone = result.bones[parentIndex];
  16894. }
  16895. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix());
  16896. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  16897. }
  16898. return result;
  16899. };
  16900. return Skeleton;
  16901. })();
  16902. BABYLON.Skeleton = Skeleton;
  16903. })(BABYLON || (BABYLON = {}));
  16904. //# sourceMappingURL=babylon.skeleton.js.mapvar BABYLON;
  16905. (function (BABYLON) {
  16906. var PostProcess = (function () {
  16907. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable, defines) {
  16908. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  16909. this.name = name;
  16910. this.width = -1;
  16911. this.height = -1;
  16912. this._reusable = false;
  16913. this._textures = new BABYLON.SmartArray(2);
  16914. this._currentRenderTextureInd = 0;
  16915. if (camera != null) {
  16916. this._camera = camera;
  16917. this._scene = camera.getScene();
  16918. camera.attachPostProcess(this);
  16919. this._engine = this._scene.getEngine();
  16920. }
  16921. else {
  16922. this._engine = engine;
  16923. }
  16924. this._renderRatio = ratio;
  16925. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  16926. this._reusable = reusable || false;
  16927. samplers = samplers || [];
  16928. samplers.push("textureSampler");
  16929. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: fragmentUrl }, ["position"], parameters || [], samplers, defines !== undefined ? defines : "");
  16930. }
  16931. PostProcess.prototype.isReusable = function () {
  16932. return this._reusable;
  16933. };
  16934. PostProcess.prototype.activate = function (camera, sourceTexture) {
  16935. camera = camera || this._camera;
  16936. var scene = camera.getScene();
  16937. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  16938. var desiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  16939. var desiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  16940. desiredWidth = BABYLON.Tools.GetExponantOfTwo(desiredWidth, maxSize);
  16941. desiredHeight = BABYLON.Tools.GetExponantOfTwo(desiredHeight, maxSize);
  16942. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  16943. if (this._textures.length > 0) {
  16944. for (var i = 0; i < this._textures.length; i++) {
  16945. this._engine._releaseTexture(this._textures.data[i]);
  16946. }
  16947. this._textures.reset();
  16948. }
  16949. this.width = desiredWidth;
  16950. this.height = desiredHeight;
  16951. 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 }));
  16952. if (this._reusable) {
  16953. 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 }));
  16954. }
  16955. if (this.onSizeChanged) {
  16956. this.onSizeChanged();
  16957. }
  16958. }
  16959. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  16960. if (this.onActivate) {
  16961. this.onActivate(camera);
  16962. }
  16963. // Clear
  16964. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  16965. if (this._reusable) {
  16966. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  16967. }
  16968. };
  16969. PostProcess.prototype.apply = function () {
  16970. // Check
  16971. if (!this._effect.isReady())
  16972. return null;
  16973. // States
  16974. this._engine.enableEffect(this._effect);
  16975. this._engine.setState(false);
  16976. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  16977. this._engine.setDepthBuffer(false);
  16978. this._engine.setDepthWrite(false);
  16979. // Texture
  16980. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  16981. // Parameters
  16982. if (this.onApply) {
  16983. this.onApply(this._effect);
  16984. }
  16985. return this._effect;
  16986. };
  16987. PostProcess.prototype.dispose = function (camera) {
  16988. camera = camera || this._camera;
  16989. if (this._textures.length > 0) {
  16990. for (var i = 0; i < this._textures.length; i++) {
  16991. this._engine._releaseTexture(this._textures.data[i]);
  16992. }
  16993. this._textures.reset();
  16994. }
  16995. if (!camera) {
  16996. return;
  16997. }
  16998. camera.detachPostProcess(this);
  16999. var index = camera._postProcesses.indexOf(this);
  17000. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  17001. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1; // invalidate frameBuffer to hint the postprocess to create a depth buffer
  17002. }
  17003. };
  17004. return PostProcess;
  17005. })();
  17006. BABYLON.PostProcess = PostProcess;
  17007. })(BABYLON || (BABYLON = {}));
  17008. //# sourceMappingURL=babylon.postProcess.js.mapvar BABYLON;
  17009. (function (BABYLON) {
  17010. var PostProcessManager = (function () {
  17011. function PostProcessManager(scene) {
  17012. this._vertexDeclaration = [2];
  17013. this._vertexStrideSize = 2 * 4;
  17014. this._scene = scene;
  17015. // VBO
  17016. var vertices = [];
  17017. vertices.push(1, 1);
  17018. vertices.push(-1, 1);
  17019. vertices.push(-1, -1);
  17020. vertices.push(1, -1);
  17021. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  17022. // Indices
  17023. var indices = [];
  17024. indices.push(0);
  17025. indices.push(1);
  17026. indices.push(2);
  17027. indices.push(0);
  17028. indices.push(2);
  17029. indices.push(3);
  17030. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  17031. }
  17032. // Methods
  17033. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  17034. var postProcesses = this._scene.activeCamera._postProcesses;
  17035. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  17036. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  17037. return false;
  17038. }
  17039. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  17040. return true;
  17041. };
  17042. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  17043. var engine = this._scene.getEngine();
  17044. for (var index = 0; index < postProcesses.length; index++) {
  17045. if (index < postProcesses.length - 1) {
  17046. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  17047. }
  17048. else {
  17049. if (targetTexture) {
  17050. engine.bindFramebuffer(targetTexture);
  17051. }
  17052. else {
  17053. engine.restoreDefaultFramebuffer();
  17054. }
  17055. }
  17056. var pp = postProcesses[index];
  17057. var effect = pp.apply();
  17058. if (effect) {
  17059. if (pp.onBeforeRender) {
  17060. pp.onBeforeRender(effect);
  17061. }
  17062. // VBOs
  17063. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  17064. // Draw order
  17065. engine.draw(true, 0, 6);
  17066. }
  17067. }
  17068. // Restore depth buffer
  17069. engine.setDepthBuffer(true);
  17070. engine.setDepthWrite(true);
  17071. };
  17072. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, postProcesses) {
  17073. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  17074. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  17075. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  17076. return;
  17077. }
  17078. var engine = this._scene.getEngine();
  17079. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  17080. if (index < postProcessesTakenIndices.length - 1) {
  17081. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera);
  17082. }
  17083. else {
  17084. if (targetTexture) {
  17085. engine.bindFramebuffer(targetTexture);
  17086. }
  17087. else {
  17088. engine.restoreDefaultFramebuffer();
  17089. }
  17090. }
  17091. if (doNotPresent) {
  17092. break;
  17093. }
  17094. var pp = postProcesses[postProcessesTakenIndices[index]];
  17095. var effect = pp.apply();
  17096. if (effect) {
  17097. if (pp.onBeforeRender) {
  17098. pp.onBeforeRender(effect);
  17099. }
  17100. // VBOs
  17101. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  17102. // Draw order
  17103. engine.draw(true, 0, 6);
  17104. }
  17105. }
  17106. // Restore depth buffer
  17107. engine.setDepthBuffer(true);
  17108. engine.setDepthWrite(true);
  17109. };
  17110. PostProcessManager.prototype.dispose = function () {
  17111. if (this._vertexBuffer) {
  17112. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  17113. this._vertexBuffer = null;
  17114. }
  17115. if (this._indexBuffer) {
  17116. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  17117. this._indexBuffer = null;
  17118. }
  17119. };
  17120. return PostProcessManager;
  17121. })();
  17122. BABYLON.PostProcessManager = PostProcessManager;
  17123. })(BABYLON || (BABYLON = {}));
  17124. //# sourceMappingURL=babylon.postProcessManager.js.map
  17125. var BABYLON;
  17126. (function (BABYLON) {
  17127. var PassPostProcess = (function (_super) {
  17128. __extends(PassPostProcess, _super);
  17129. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  17130. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  17131. }
  17132. return PassPostProcess;
  17133. })(BABYLON.PostProcess);
  17134. BABYLON.PassPostProcess = PassPostProcess;
  17135. })(BABYLON || (BABYLON = {}));
  17136. //# sourceMappingURL=babylon.passPostProcess.js.map
  17137. var BABYLON;
  17138. (function (BABYLON) {
  17139. var BlurPostProcess = (function (_super) {
  17140. __extends(BlurPostProcess, _super);
  17141. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  17142. var _this = this;
  17143. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  17144. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  17145. this.direction = direction;
  17146. this.blurWidth = blurWidth;
  17147. this.onApply = function (effect) {
  17148. effect.setFloat2("screenSize", _this.width, _this.height);
  17149. effect.setVector2("direction", _this.direction);
  17150. effect.setFloat("blurWidth", _this.blurWidth);
  17151. };
  17152. }
  17153. return BlurPostProcess;
  17154. })(BABYLON.PostProcess);
  17155. BABYLON.BlurPostProcess = BlurPostProcess;
  17156. })(BABYLON || (BABYLON = {}));
  17157. //# sourceMappingURL=babylon.blurPostProcess.js.map
  17158. var BABYLON;
  17159. (function (BABYLON) {
  17160. var FilterPostProcess = (function (_super) {
  17161. __extends(FilterPostProcess, _super);
  17162. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  17163. var _this = this;
  17164. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  17165. this.kernelMatrix = kernelMatrix;
  17166. this.onApply = function (effect) {
  17167. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  17168. };
  17169. }
  17170. return FilterPostProcess;
  17171. })(BABYLON.PostProcess);
  17172. BABYLON.FilterPostProcess = FilterPostProcess;
  17173. })(BABYLON || (BABYLON = {}));
  17174. //# sourceMappingURL=babylon.filterPostProcess.js.map
  17175. var BABYLON;
  17176. (function (BABYLON) {
  17177. var RefractionPostProcess = (function (_super) {
  17178. __extends(RefractionPostProcess, _super);
  17179. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  17180. var _this = this;
  17181. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  17182. this.color = color;
  17183. this.depth = depth;
  17184. this.colorLevel = colorLevel;
  17185. this.onActivate = function (cam) {
  17186. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  17187. };
  17188. this.onApply = function (effect) {
  17189. effect.setColor3("baseColor", _this.color);
  17190. effect.setFloat("depth", _this.depth);
  17191. effect.setFloat("colorLevel", _this.colorLevel);
  17192. effect.setTexture("refractionSampler", _this._refRexture);
  17193. };
  17194. }
  17195. // Methods
  17196. RefractionPostProcess.prototype.dispose = function (camera) {
  17197. if (this._refRexture) {
  17198. this._refRexture.dispose();
  17199. }
  17200. _super.prototype.dispose.call(this, camera);
  17201. };
  17202. return RefractionPostProcess;
  17203. })(BABYLON.PostProcess);
  17204. BABYLON.RefractionPostProcess = RefractionPostProcess;
  17205. })(BABYLON || (BABYLON = {}));
  17206. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  17207. var BABYLON;
  17208. (function (BABYLON) {
  17209. var BlackAndWhitePostProcess = (function (_super) {
  17210. __extends(BlackAndWhitePostProcess, _super);
  17211. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  17212. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  17213. }
  17214. return BlackAndWhitePostProcess;
  17215. })(BABYLON.PostProcess);
  17216. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  17217. })(BABYLON || (BABYLON = {}));
  17218. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  17219. var BABYLON;
  17220. (function (BABYLON) {
  17221. var ConvolutionPostProcess = (function (_super) {
  17222. __extends(ConvolutionPostProcess, _super);
  17223. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  17224. var _this = this;
  17225. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  17226. this.kernel = kernel;
  17227. this.onApply = function (effect) {
  17228. effect.setFloat2("screenSize", _this.width, _this.height);
  17229. effect.setArray("kernel", _this.kernel);
  17230. };
  17231. }
  17232. // Statics
  17233. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  17234. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  17235. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  17236. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  17237. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  17238. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  17239. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  17240. return ConvolutionPostProcess;
  17241. })(BABYLON.PostProcess);
  17242. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  17243. })(BABYLON || (BABYLON = {}));
  17244. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  17245. var BABYLON;
  17246. (function (BABYLON) {
  17247. var FxaaPostProcess = (function (_super) {
  17248. __extends(FxaaPostProcess, _super);
  17249. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  17250. var _this = this;
  17251. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  17252. this.onSizeChanged = function () {
  17253. _this.texelWidth = 1.0 / _this.width;
  17254. _this.texelHeight = 1.0 / _this.height;
  17255. };
  17256. this.onApply = function (effect) {
  17257. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  17258. };
  17259. }
  17260. return FxaaPostProcess;
  17261. })(BABYLON.PostProcess);
  17262. BABYLON.FxaaPostProcess = FxaaPostProcess;
  17263. })(BABYLON || (BABYLON = {}));
  17264. //# sourceMappingURL=babylon.fxaaPostProcess.js.mapvar BABYLON;
  17265. (function (BABYLON) {
  17266. var LensFlare = (function () {
  17267. function LensFlare(size, position, color, imgUrl, system) {
  17268. this.size = size;
  17269. this.position = position;
  17270. this.dispose = function () {
  17271. if (this.texture) {
  17272. this.texture.dispose();
  17273. }
  17274. // Remove from scene
  17275. var index = this._system.lensFlares.indexOf(this);
  17276. this._system.lensFlares.splice(index, 1);
  17277. };
  17278. this.color = color || new BABYLON.Color3(1, 1, 1);
  17279. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  17280. this._system = system;
  17281. system.lensFlares.push(this);
  17282. }
  17283. return LensFlare;
  17284. })();
  17285. BABYLON.LensFlare = LensFlare;
  17286. })(BABYLON || (BABYLON = {}));
  17287. //# sourceMappingURL=babylon.lensFlare.js.mapvar BABYLON;
  17288. (function (BABYLON) {
  17289. var LensFlareSystem = (function () {
  17290. function LensFlareSystem(name, emitter, scene) {
  17291. this.name = name;
  17292. this.lensFlares = new Array();
  17293. this.borderLimit = 300;
  17294. this._vertexDeclaration = [2];
  17295. this._vertexStrideSize = 2 * 4;
  17296. this._isEnabled = true;
  17297. this._scene = scene;
  17298. this._emitter = emitter;
  17299. scene.lensFlareSystems.push(this);
  17300. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  17301. // VBO
  17302. var vertices = [];
  17303. vertices.push(1, 1);
  17304. vertices.push(-1, 1);
  17305. vertices.push(-1, -1);
  17306. vertices.push(1, -1);
  17307. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  17308. // Indices
  17309. var indices = [];
  17310. indices.push(0);
  17311. indices.push(1);
  17312. indices.push(2);
  17313. indices.push(0);
  17314. indices.push(2);
  17315. indices.push(3);
  17316. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  17317. // Effects
  17318. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  17319. }
  17320. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  17321. get: function () {
  17322. return this._isEnabled;
  17323. },
  17324. set: function (value) {
  17325. this._isEnabled = value;
  17326. },
  17327. enumerable: true,
  17328. configurable: true
  17329. });
  17330. LensFlareSystem.prototype.getScene = function () {
  17331. return this._scene;
  17332. };
  17333. LensFlareSystem.prototype.getEmitter = function () {
  17334. return this._emitter;
  17335. };
  17336. LensFlareSystem.prototype.getEmitterPosition = function () {
  17337. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  17338. };
  17339. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  17340. var position = this.getEmitterPosition();
  17341. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  17342. this._positionX = position.x;
  17343. this._positionY = position.y;
  17344. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  17345. if (position.z > 0) {
  17346. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  17347. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  17348. return true;
  17349. }
  17350. }
  17351. return false;
  17352. };
  17353. LensFlareSystem.prototype._isVisible = function () {
  17354. if (!this._isEnabled) {
  17355. return false;
  17356. }
  17357. var emitterPosition = this.getEmitterPosition();
  17358. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  17359. var distance = direction.length();
  17360. direction.normalize();
  17361. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  17362. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  17363. return !pickInfo.hit || pickInfo.distance > distance;
  17364. };
  17365. LensFlareSystem.prototype.render = function () {
  17366. if (!this._effect.isReady())
  17367. return false;
  17368. var engine = this._scene.getEngine();
  17369. var viewport = this._scene.activeCamera.viewport;
  17370. var globalViewport = viewport.toGlobal(engine);
  17371. // Position
  17372. if (!this.computeEffectivePosition(globalViewport)) {
  17373. return false;
  17374. }
  17375. // Visibility
  17376. if (!this._isVisible()) {
  17377. return false;
  17378. }
  17379. // Intensity
  17380. var awayX;
  17381. var awayY;
  17382. if (this._positionX < this.borderLimit + globalViewport.x) {
  17383. awayX = this.borderLimit + globalViewport.x - this._positionX;
  17384. }
  17385. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  17386. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  17387. }
  17388. else {
  17389. awayX = 0;
  17390. }
  17391. if (this._positionY < this.borderLimit + globalViewport.y) {
  17392. awayY = this.borderLimit + globalViewport.y - this._positionY;
  17393. }
  17394. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  17395. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  17396. }
  17397. else {
  17398. awayY = 0;
  17399. }
  17400. var away = (awayX > awayY) ? awayX : awayY;
  17401. if (away > this.borderLimit) {
  17402. away = this.borderLimit;
  17403. }
  17404. var intensity = 1.0 - (away / this.borderLimit);
  17405. if (intensity < 0) {
  17406. return false;
  17407. }
  17408. if (intensity > 1.0) {
  17409. intensity = 1.0;
  17410. }
  17411. // Position
  17412. var centerX = globalViewport.x + globalViewport.width / 2;
  17413. var centerY = globalViewport.y + globalViewport.height / 2;
  17414. var distX = centerX - this._positionX;
  17415. var distY = centerY - this._positionY;
  17416. // Effects
  17417. engine.enableEffect(this._effect);
  17418. engine.setState(false);
  17419. engine.setDepthBuffer(false);
  17420. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  17421. // VBOs
  17422. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  17423. for (var index = 0; index < this.lensFlares.length; index++) {
  17424. var flare = this.lensFlares[index];
  17425. var x = centerX - (distX * flare.position);
  17426. var y = centerY - (distY * flare.position);
  17427. var cw = flare.size;
  17428. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera);
  17429. var cx = 2 * (x / globalViewport.width) - 1.0;
  17430. var cy = 1.0 - 2 * (y / globalViewport.height);
  17431. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  17432. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  17433. // Texture
  17434. this._effect.setTexture("textureSampler", flare.texture);
  17435. // Color
  17436. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  17437. // Draw order
  17438. engine.draw(true, 0, 6);
  17439. }
  17440. engine.setDepthBuffer(true);
  17441. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  17442. return true;
  17443. };
  17444. LensFlareSystem.prototype.dispose = function () {
  17445. if (this._vertexBuffer) {
  17446. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  17447. this._vertexBuffer = null;
  17448. }
  17449. if (this._indexBuffer) {
  17450. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  17451. this._indexBuffer = null;
  17452. }
  17453. while (this.lensFlares.length) {
  17454. this.lensFlares[0].dispose();
  17455. }
  17456. // Remove from scene
  17457. var index = this._scene.lensFlareSystems.indexOf(this);
  17458. this._scene.lensFlareSystems.splice(index, 1);
  17459. };
  17460. return LensFlareSystem;
  17461. })();
  17462. BABYLON.LensFlareSystem = LensFlareSystem;
  17463. })(BABYLON || (BABYLON = {}));
  17464. //# sourceMappingURL=babylon.lensFlareSystem.js.mapvar BABYLON;
  17465. (function (BABYLON) {
  17466. var IntersectionInfo = (function () {
  17467. function IntersectionInfo(bu, bv, distance) {
  17468. this.bu = bu;
  17469. this.bv = bv;
  17470. this.distance = distance;
  17471. this.faceId = 0;
  17472. this.subMeshId = 0;
  17473. }
  17474. return IntersectionInfo;
  17475. })();
  17476. BABYLON.IntersectionInfo = IntersectionInfo;
  17477. var PickingInfo = (function () {
  17478. function PickingInfo() {
  17479. this.hit = false;
  17480. this.distance = 0;
  17481. this.pickedPoint = null;
  17482. this.pickedMesh = null;
  17483. this.bu = 0;
  17484. this.bv = 0;
  17485. this.faceId = -1;
  17486. this.subMeshId = 0;
  17487. }
  17488. // Methods
  17489. PickingInfo.prototype.getNormal = function () {
  17490. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  17491. return null;
  17492. }
  17493. var indices = this.pickedMesh.getIndices();
  17494. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  17495. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  17496. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  17497. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  17498. normal0 = normal0.scale(this.bu);
  17499. normal1 = normal1.scale(this.bv);
  17500. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  17501. return new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  17502. };
  17503. PickingInfo.prototype.getTextureCoordinates = function () {
  17504. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  17505. return null;
  17506. }
  17507. var indices = this.pickedMesh.getIndices();
  17508. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  17509. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  17510. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  17511. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  17512. uv0 = uv0.scale(this.bu);
  17513. uv1 = uv1.scale(this.bv);
  17514. uv2 = uv2.scale(1.0 - this.bu - this.bv);
  17515. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  17516. };
  17517. return PickingInfo;
  17518. })();
  17519. BABYLON.PickingInfo = PickingInfo;
  17520. })(BABYLON || (BABYLON = {}));
  17521. //# sourceMappingURL=babylon.pickingInfo.js.mapvar BABYLON;
  17522. (function (BABYLON) {
  17523. var FilesInput = (function () {
  17524. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  17525. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  17526. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  17527. this._engine = p_engine;
  17528. this._canvas = p_canvas;
  17529. this._currentScene = p_scene;
  17530. this._sceneLoadedCallback = p_sceneLoadedCallback;
  17531. this._progressCallback = p_progressCallback;
  17532. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  17533. this._textureLoadingCallback = p_textureLoadingCallback;
  17534. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  17535. }
  17536. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  17537. var _this = this;
  17538. if (p_elementToMonitor) {
  17539. this._elementToMonitor = p_elementToMonitor;
  17540. this._elementToMonitor.addEventListener("dragenter", function (e) {
  17541. _this.drag(e);
  17542. }, false);
  17543. this._elementToMonitor.addEventListener("dragover", function (e) {
  17544. _this.drag(e);
  17545. }, false);
  17546. this._elementToMonitor.addEventListener("drop", function (e) {
  17547. _this.drop(e);
  17548. }, false);
  17549. }
  17550. };
  17551. FilesInput.prototype.renderFunction = function () {
  17552. if (this._additionnalRenderLoopLogicCallback) {
  17553. this._additionnalRenderLoopLogicCallback();
  17554. }
  17555. if (this._currentScene) {
  17556. if (this._textureLoadingCallback) {
  17557. var remaining = this._currentScene.getWaitingItemsCount();
  17558. if (remaining > 0) {
  17559. this._textureLoadingCallback(remaining);
  17560. }
  17561. }
  17562. this._currentScene.render();
  17563. }
  17564. };
  17565. FilesInput.prototype.drag = function (e) {
  17566. e.stopPropagation();
  17567. e.preventDefault();
  17568. };
  17569. FilesInput.prototype.drop = function (eventDrop) {
  17570. eventDrop.stopPropagation();
  17571. eventDrop.preventDefault();
  17572. this.loadFiles(eventDrop);
  17573. };
  17574. FilesInput.prototype.loadFiles = function (event) {
  17575. if (this._startingProcessingFilesCallback)
  17576. this._startingProcessingFilesCallback();
  17577. // Handling data transfer via drag'n'drop
  17578. if (event && event.dataTransfer && event.dataTransfer.files) {
  17579. this._filesToLoad = event.dataTransfer.files;
  17580. }
  17581. // Handling files from input files
  17582. if (event && event.target && event.target.files) {
  17583. this._filesToLoad = event.target.files;
  17584. }
  17585. if (this._filesToLoad && this._filesToLoad.length > 0) {
  17586. for (var i = 0; i < this._filesToLoad.length; i++) {
  17587. switch (this._filesToLoad[i].type) {
  17588. case "image/jpeg":
  17589. case "image/png":
  17590. case "image/bmp":
  17591. FilesInput.FilesTextures[this._filesToLoad[i].name] = this._filesToLoad[i];
  17592. break;
  17593. case "image/targa":
  17594. case "image/vnd.ms-dds":
  17595. case "audio/wav":
  17596. case "audio/x-wav":
  17597. case "audio/mp3":
  17598. case "audio/mpeg":
  17599. case "audio/mpeg3":
  17600. case "audio/x-mpeg-3":
  17601. case "audio/ogg":
  17602. FilesInput.FilesToLoad[this._filesToLoad[i].name] = this._filesToLoad[i];
  17603. break;
  17604. default:
  17605. 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) {
  17606. this._sceneFileToLoad = this._filesToLoad[i];
  17607. }
  17608. break;
  17609. }
  17610. }
  17611. this.reload();
  17612. }
  17613. };
  17614. FilesInput.prototype.reload = function () {
  17615. var _this = this;
  17616. var that = this;
  17617. // If a ".babylon" file has been provided
  17618. if (this._sceneFileToLoad) {
  17619. if (this._currentScene) {
  17620. this._engine.stopRenderLoop();
  17621. this._currentScene.dispose();
  17622. }
  17623. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  17624. that._currentScene = newScene;
  17625. // Wait for textures and shaders to be ready
  17626. that._currentScene.executeWhenReady(function () {
  17627. // Attach camera to canvas inputs
  17628. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  17629. that._currentScene.createDefaultCameraOrLight();
  17630. }
  17631. that._currentScene.activeCamera.attachControl(that._canvas);
  17632. if (that._sceneLoadedCallback) {
  17633. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  17634. }
  17635. that._engine.runRenderLoop(function () {
  17636. that.renderFunction();
  17637. });
  17638. });
  17639. }, function (progress) {
  17640. if (_this._progressCallback) {
  17641. _this._progressCallback(progress);
  17642. }
  17643. });
  17644. }
  17645. else {
  17646. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  17647. }
  17648. };
  17649. FilesInput.FilesTextures = new Array();
  17650. FilesInput.FilesToLoad = new Array();
  17651. return FilesInput;
  17652. })();
  17653. BABYLON.FilesInput = FilesInput;
  17654. })(BABYLON || (BABYLON = {}));
  17655. //# sourceMappingURL=babylon.filesInput.js.mapvar BABYLON;
  17656. (function (BABYLON) {
  17657. var OimoJSPlugin = (function () {
  17658. function OimoJSPlugin() {
  17659. this._registeredMeshes = [];
  17660. /**
  17661. * Update the body position according to the mesh position
  17662. * @param mesh
  17663. */
  17664. this.updateBodyPosition = function (mesh) {
  17665. for (var index = 0; index < this._registeredMeshes.length; index++) {
  17666. var registeredMesh = this._registeredMeshes[index];
  17667. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  17668. var body = registeredMesh.body.body;
  17669. mesh.computeWorldMatrix(true);
  17670. var center = mesh.getBoundingInfo().boundingBox.center;
  17671. body.setPosition(center.x, center.y, center.z);
  17672. body.setRotation(mesh.rotation.x, mesh.rotation.y, mesh.rotation.z);
  17673. return;
  17674. }
  17675. // Case where the parent has been updated
  17676. if (registeredMesh.mesh.parent === mesh) {
  17677. mesh.computeWorldMatrix(true);
  17678. registeredMesh.mesh.computeWorldMatrix(true);
  17679. var absolutePosition = registeredMesh.mesh.getAbsolutePosition();
  17680. var absoluteRotation = mesh.rotation;
  17681. body = registeredMesh.body.body;
  17682. body.setPosition(absolutePosition.x, absolutePosition.y, absolutePosition.z);
  17683. body.setRotation(absoluteRotation.x, absoluteRotation.y, absoluteRotation.z);
  17684. return;
  17685. }
  17686. }
  17687. };
  17688. }
  17689. OimoJSPlugin.prototype._checkWithEpsilon = function (value) {
  17690. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  17691. };
  17692. OimoJSPlugin.prototype.initialize = function (iterations) {
  17693. this._world = new OIMO.World();
  17694. this._world.clear();
  17695. };
  17696. OimoJSPlugin.prototype.setGravity = function (gravity) {
  17697. this._world.gravity = gravity;
  17698. };
  17699. OimoJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  17700. var body = null;
  17701. this.unregisterMesh(mesh);
  17702. mesh.computeWorldMatrix(true);
  17703. var initialRotation = null;
  17704. if (mesh.rotationQuaternion) {
  17705. initialRotation = mesh.rotationQuaternion.clone();
  17706. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  17707. mesh.computeWorldMatrix(true);
  17708. }
  17709. var bbox = mesh.getBoundingInfo().boundingBox;
  17710. // The delta between the mesh position and the mesh bounding box center
  17711. var deltaPosition = mesh.position.subtract(bbox.center);
  17712. // Transform delta position with the rotation
  17713. if (initialRotation) {
  17714. var m = new BABYLON.Matrix();
  17715. initialRotation.toRotationMatrix(m);
  17716. deltaPosition = BABYLON.Vector3.TransformCoordinates(deltaPosition, m);
  17717. }
  17718. switch (impostor) {
  17719. case BABYLON.PhysicsEngine.SphereImpostor:
  17720. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  17721. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  17722. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  17723. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  17724. body = new OIMO.Body({
  17725. type: 'sphere',
  17726. size: [size],
  17727. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  17728. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  17729. move: options.mass != 0,
  17730. config: [options.mass, options.friction, options.restitution],
  17731. world: this._world
  17732. });
  17733. break;
  17734. case BABYLON.PhysicsEngine.PlaneImpostor:
  17735. case BABYLON.PhysicsEngine.CylinderImpostor:
  17736. case BABYLON.PhysicsEngine.BoxImpostor:
  17737. var min = bbox.minimumWorld;
  17738. var max = bbox.maximumWorld;
  17739. var box = max.subtract(min);
  17740. var sizeX = this._checkWithEpsilon(box.x);
  17741. var sizeY = this._checkWithEpsilon(box.y);
  17742. var sizeZ = this._checkWithEpsilon(box.z);
  17743. body = new OIMO.Body({
  17744. type: 'box',
  17745. size: [sizeX, sizeY, sizeZ],
  17746. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  17747. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  17748. move: options.mass != 0,
  17749. config: [options.mass, options.friction, options.restitution],
  17750. world: this._world
  17751. });
  17752. break;
  17753. }
  17754. //If quaternion was set as the rotation of the object
  17755. if (initialRotation) {
  17756. //We have to access the rigid body's properties to set the quaternion.
  17757. //The setQuaternion function of Oimo only sets the newOrientation that is only set after an impulse is given or a collision.
  17758. body.body.orientation = new OIMO.Quat(initialRotation.w, initialRotation.x, initialRotation.y, initialRotation.z);
  17759. //update the internal rotation matrix
  17760. body.body.syncShapes();
  17761. }
  17762. this._registeredMeshes.push({
  17763. mesh: mesh,
  17764. body: body,
  17765. delta: deltaPosition
  17766. });
  17767. return body;
  17768. };
  17769. OimoJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  17770. var types = [], sizes = [], positions = [], rotations = [];
  17771. var initialMesh = parts[0].mesh;
  17772. for (var index = 0; index < parts.length; index++) {
  17773. var part = parts[index];
  17774. var bodyParameters = this._createBodyAsCompound(part, options, initialMesh);
  17775. types.push(bodyParameters.type);
  17776. sizes.push.apply(sizes, bodyParameters.size);
  17777. positions.push.apply(positions, bodyParameters.pos);
  17778. rotations.push.apply(rotations, bodyParameters.rot);
  17779. }
  17780. var body = new OIMO.Body({
  17781. type: types,
  17782. size: sizes,
  17783. pos: positions,
  17784. rot: rotations,
  17785. move: options.mass != 0,
  17786. config: [options.mass, options.friction, options.restitution],
  17787. world: this._world
  17788. });
  17789. this._registeredMeshes.push({
  17790. mesh: initialMesh,
  17791. body: body
  17792. });
  17793. return body;
  17794. };
  17795. OimoJSPlugin.prototype._createBodyAsCompound = function (part, options, initialMesh) {
  17796. var bodyParameters = null;
  17797. var mesh = part.mesh;
  17798. // We need the bounding box/sphere info to compute the physics body
  17799. mesh.computeWorldMatrix();
  17800. switch (part.impostor) {
  17801. case BABYLON.PhysicsEngine.SphereImpostor:
  17802. var bbox = mesh.getBoundingInfo().boundingBox;
  17803. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  17804. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  17805. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  17806. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  17807. bodyParameters = {
  17808. type: 'sphere',
  17809. /* bug with oimo : sphere needs 3 sizes in this case */
  17810. size: [size, -1, -1],
  17811. pos: [mesh.position.x, mesh.position.y, mesh.position.z],
  17812. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  17813. };
  17814. break;
  17815. case BABYLON.PhysicsEngine.PlaneImpostor:
  17816. case BABYLON.PhysicsEngine.BoxImpostor:
  17817. bbox = mesh.getBoundingInfo().boundingBox;
  17818. var min = bbox.minimumWorld;
  17819. var max = bbox.maximumWorld;
  17820. var box = max.subtract(min);
  17821. var sizeX = this._checkWithEpsilon(box.x);
  17822. var sizeY = this._checkWithEpsilon(box.y);
  17823. var sizeZ = this._checkWithEpsilon(box.z);
  17824. var relativePosition = mesh.position;
  17825. bodyParameters = {
  17826. type: 'box',
  17827. size: [sizeX, sizeY, sizeZ],
  17828. pos: [relativePosition.x, relativePosition.y, relativePosition.z],
  17829. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  17830. };
  17831. break;
  17832. }
  17833. return bodyParameters;
  17834. };
  17835. OimoJSPlugin.prototype.unregisterMesh = function (mesh) {
  17836. for (var index = 0; index < this._registeredMeshes.length; index++) {
  17837. var registeredMesh = this._registeredMeshes[index];
  17838. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  17839. if (registeredMesh.body) {
  17840. this._world.removeRigidBody(registeredMesh.body.body);
  17841. this._unbindBody(registeredMesh.body);
  17842. }
  17843. this._registeredMeshes.splice(index, 1);
  17844. return;
  17845. }
  17846. }
  17847. };
  17848. OimoJSPlugin.prototype._unbindBody = function (body) {
  17849. for (var index = 0; index < this._registeredMeshes.length; index++) {
  17850. var registeredMesh = this._registeredMeshes[index];
  17851. if (registeredMesh.body === body) {
  17852. registeredMesh.body = null;
  17853. }
  17854. }
  17855. };
  17856. OimoJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  17857. for (var index = 0; index < this._registeredMeshes.length; index++) {
  17858. var registeredMesh = this._registeredMeshes[index];
  17859. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  17860. // Get object mass to have a behaviour similar to cannon.js
  17861. var mass = registeredMesh.body.body.massInfo.mass;
  17862. // The force is scaled with the mass of object
  17863. registeredMesh.body.body.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  17864. return;
  17865. }
  17866. }
  17867. };
  17868. OimoJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  17869. var body1 = null, body2 = null;
  17870. for (var index = 0; index < this._registeredMeshes.length; index++) {
  17871. var registeredMesh = this._registeredMeshes[index];
  17872. if (registeredMesh.mesh === mesh1) {
  17873. body1 = registeredMesh.body.body;
  17874. }
  17875. else if (registeredMesh.mesh === mesh2) {
  17876. body2 = registeredMesh.body.body;
  17877. }
  17878. }
  17879. if (!body1 || !body2) {
  17880. return false;
  17881. }
  17882. if (!options) {
  17883. options = {};
  17884. }
  17885. new OIMO.Link({
  17886. type: options.type,
  17887. body1: body1,
  17888. body2: body2,
  17889. min: options.min,
  17890. max: options.max,
  17891. axe1: options.axe1,
  17892. axe2: options.axe2,
  17893. pos1: [pivot1.x, pivot1.y, pivot1.z],
  17894. pos2: [pivot2.x, pivot2.y, pivot2.z],
  17895. collision: options.collision,
  17896. spring: options.spring,
  17897. world: this._world
  17898. });
  17899. return true;
  17900. };
  17901. OimoJSPlugin.prototype.dispose = function () {
  17902. this._world.clear();
  17903. while (this._registeredMeshes.length) {
  17904. this.unregisterMesh(this._registeredMeshes[0].mesh);
  17905. }
  17906. };
  17907. OimoJSPlugin.prototype.isSupported = function () {
  17908. return OIMO !== undefined;
  17909. };
  17910. OimoJSPlugin.prototype._getLastShape = function (body) {
  17911. var lastShape = body.shapes;
  17912. while (lastShape.next) {
  17913. lastShape = lastShape.next;
  17914. }
  17915. return lastShape;
  17916. };
  17917. OimoJSPlugin.prototype.runOneStep = function (time) {
  17918. this._world.step();
  17919. // Update the position of all registered meshes
  17920. var i = this._registeredMeshes.length;
  17921. var m;
  17922. while (i--) {
  17923. var body = this._registeredMeshes[i].body.body;
  17924. var mesh = this._registeredMeshes[i].mesh;
  17925. var delta = this._registeredMeshes[i].delta;
  17926. if (!body.sleeping) {
  17927. if (body.shapes.next) {
  17928. var parentShape = this._getLastShape(body);
  17929. mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  17930. mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  17931. mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  17932. var mtx = BABYLON.Matrix.FromArray(body.getMatrix());
  17933. if (!mesh.rotationQuaternion) {
  17934. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  17935. }
  17936. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  17937. mesh.computeWorldMatrix();
  17938. }
  17939. else {
  17940. m = body.getMatrix();
  17941. mtx = BABYLON.Matrix.FromArray(m);
  17942. // Body position
  17943. var bodyX = mtx.m[12], bodyY = mtx.m[13], bodyZ = mtx.m[14];
  17944. if (!delta) {
  17945. mesh.position.x = bodyX;
  17946. mesh.position.y = bodyY;
  17947. mesh.position.z = bodyZ;
  17948. }
  17949. else {
  17950. mesh.position.x = bodyX + delta.x;
  17951. mesh.position.y = bodyY + delta.y;
  17952. mesh.position.z = bodyZ + delta.z;
  17953. }
  17954. if (!mesh.rotationQuaternion) {
  17955. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  17956. }
  17957. BABYLON.Quaternion.FromRotationMatrixToRef(mtx, mesh.rotationQuaternion);
  17958. mesh.computeWorldMatrix();
  17959. }
  17960. }
  17961. }
  17962. };
  17963. return OimoJSPlugin;
  17964. })();
  17965. BABYLON.OimoJSPlugin = OimoJSPlugin;
  17966. })(BABYLON || (BABYLON = {}));
  17967. //# sourceMappingURL=babylon.oimoJSPlugin.js.mapvar BABYLON;
  17968. (function (BABYLON) {
  17969. var PhysicsEngine = (function () {
  17970. function PhysicsEngine(plugin) {
  17971. this._currentPlugin = plugin || new BABYLON.OimoJSPlugin();
  17972. }
  17973. PhysicsEngine.prototype._initialize = function (gravity) {
  17974. this._currentPlugin.initialize();
  17975. this._setGravity(gravity);
  17976. };
  17977. PhysicsEngine.prototype._runOneStep = function (delta) {
  17978. if (delta > 0.1) {
  17979. delta = 0.1;
  17980. }
  17981. else if (delta <= 0) {
  17982. delta = 1.0 / 60.0;
  17983. }
  17984. this._currentPlugin.runOneStep(delta);
  17985. };
  17986. PhysicsEngine.prototype._setGravity = function (gravity) {
  17987. this.gravity = gravity || new BABYLON.Vector3(0, -9.82, 0);
  17988. this._currentPlugin.setGravity(this.gravity);
  17989. };
  17990. PhysicsEngine.prototype._registerMesh = function (mesh, impostor, options) {
  17991. return this._currentPlugin.registerMesh(mesh, impostor, options);
  17992. };
  17993. PhysicsEngine.prototype._registerMeshesAsCompound = function (parts, options) {
  17994. return this._currentPlugin.registerMeshesAsCompound(parts, options);
  17995. };
  17996. PhysicsEngine.prototype._unregisterMesh = function (mesh) {
  17997. this._currentPlugin.unregisterMesh(mesh);
  17998. };
  17999. PhysicsEngine.prototype._applyImpulse = function (mesh, force, contactPoint) {
  18000. this._currentPlugin.applyImpulse(mesh, force, contactPoint);
  18001. };
  18002. PhysicsEngine.prototype._createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  18003. return this._currentPlugin.createLink(mesh1, mesh2, pivot1, pivot2, options);
  18004. };
  18005. PhysicsEngine.prototype._updateBodyPosition = function (mesh) {
  18006. this._currentPlugin.updateBodyPosition(mesh);
  18007. };
  18008. PhysicsEngine.prototype.dispose = function () {
  18009. this._currentPlugin.dispose();
  18010. };
  18011. PhysicsEngine.prototype.isSupported = function () {
  18012. return this._currentPlugin.isSupported();
  18013. };
  18014. // Statics
  18015. PhysicsEngine.NoImpostor = 0;
  18016. PhysicsEngine.SphereImpostor = 1;
  18017. PhysicsEngine.BoxImpostor = 2;
  18018. PhysicsEngine.PlaneImpostor = 3;
  18019. PhysicsEngine.MeshImpostor = 4;
  18020. PhysicsEngine.CapsuleImpostor = 5;
  18021. PhysicsEngine.ConeImpostor = 6;
  18022. PhysicsEngine.CylinderImpostor = 7;
  18023. PhysicsEngine.ConvexHullImpostor = 8;
  18024. PhysicsEngine.Epsilon = 0.001;
  18025. return PhysicsEngine;
  18026. })();
  18027. BABYLON.PhysicsEngine = PhysicsEngine;
  18028. })(BABYLON || (BABYLON = {}));
  18029. //# sourceMappingURL=babylon.physicsEngine.js.mapvar BABYLON;
  18030. (function (BABYLON) {
  18031. var serializeLight = function (light) {
  18032. var serializationObject = {};
  18033. serializationObject.name = light.name;
  18034. serializationObject.id = light.id;
  18035. serializationObject.tags = BABYLON.Tags.GetTags(light);
  18036. if (light instanceof BABYLON.PointLight) {
  18037. serializationObject.type = 0;
  18038. serializationObject.position = light.position.asArray();
  18039. }
  18040. else if (light instanceof BABYLON.DirectionalLight) {
  18041. serializationObject.type = 1;
  18042. var directionalLight = light;
  18043. serializationObject.position = directionalLight.position.asArray();
  18044. serializationObject.direction = directionalLight.direction.asArray();
  18045. }
  18046. else if (light instanceof BABYLON.SpotLight) {
  18047. serializationObject.type = 2;
  18048. var spotLight = light;
  18049. serializationObject.position = spotLight.position.asArray();
  18050. serializationObject.direction = spotLight.position.asArray();
  18051. serializationObject.angle = spotLight.angle;
  18052. serializationObject.exponent = spotLight.exponent;
  18053. }
  18054. else if (light instanceof BABYLON.HemisphericLight) {
  18055. serializationObject.type = 3;
  18056. var hemisphericLight = light;
  18057. serializationObject.direction = hemisphericLight.direction.asArray();
  18058. serializationObject.groundColor = hemisphericLight.groundColor.asArray();
  18059. }
  18060. if (light.intensity) {
  18061. serializationObject.intensity = light.intensity;
  18062. }
  18063. serializationObject.range = light.range;
  18064. serializationObject.diffuse = light.diffuse.asArray();
  18065. serializationObject.specular = light.specular.asArray();
  18066. return serializationObject;
  18067. };
  18068. var serializeFresnelParameter = function (fresnelParameter) {
  18069. var serializationObject = {};
  18070. serializationObject.isEnabled = fresnelParameter.isEnabled;
  18071. serializationObject.leftColor = fresnelParameter.leftColor;
  18072. serializationObject.rightColor = fresnelParameter.rightColor;
  18073. serializationObject.bias = fresnelParameter.bias;
  18074. serializationObject.power = fresnelParameter.power;
  18075. return serializationObject;
  18076. };
  18077. var appendAnimations = function (source, destination) {
  18078. if (source.animations) {
  18079. destination.animations = [];
  18080. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  18081. var animation = source.animations[animationIndex];
  18082. destination.animations.push(serializeAnimation(animation));
  18083. }
  18084. }
  18085. };
  18086. var serializeCamera = function (camera) {
  18087. var serializationObject = {};
  18088. serializationObject.name = camera.name;
  18089. serializationObject.tags = BABYLON.Tags.GetTags(camera) || [];
  18090. serializationObject.id = camera.id;
  18091. serializationObject.position = camera.position.asArray();
  18092. // Parent
  18093. if (camera.parent) {
  18094. serializationObject.parentId = camera.parent.id;
  18095. }
  18096. serializationObject.fov = camera.fov;
  18097. serializationObject.minZ = camera.minZ;
  18098. serializationObject.maxZ = camera.maxZ;
  18099. serializationObject.inertia = camera.inertia;
  18100. //setting the type
  18101. if (camera instanceof BABYLON.FreeCamera) {
  18102. serializationObject.type = "FreeCamera";
  18103. }
  18104. else if (camera instanceof BABYLON.ArcRotateCamera) {
  18105. serializationObject.type = "ArcRotateCamera";
  18106. }
  18107. else if (camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  18108. serializationObject.type = "AnaglyphArcRotateCamera";
  18109. }
  18110. else if (camera instanceof BABYLON.GamepadCamera) {
  18111. serializationObject.type = "GamepadCamera";
  18112. }
  18113. else if (camera instanceof BABYLON.AnaglyphFreeCamera) {
  18114. serializationObject.type = "AnaglyphFreeCamera";
  18115. }
  18116. else if (camera instanceof BABYLON.DeviceOrientationCamera) {
  18117. serializationObject.type = "DeviceOrientationCamera";
  18118. }
  18119. else if (camera instanceof BABYLON.FollowCamera) {
  18120. serializationObject.type = "FollowCamera";
  18121. }
  18122. else if (camera instanceof BABYLON.OculusCamera) {
  18123. serializationObject.type = "OculusCamera";
  18124. }
  18125. else if (camera instanceof BABYLON.OculusGamepadCamera) {
  18126. serializationObject.type = "OculusGamepadCamera";
  18127. }
  18128. else if (camera instanceof BABYLON.TouchCamera) {
  18129. serializationObject.type = "TouchCamera";
  18130. }
  18131. else if (camera instanceof BABYLON.VirtualJoysticksCamera) {
  18132. serializationObject.type = "VirtualJoysticksCamera";
  18133. }
  18134. else if (camera instanceof BABYLON.WebVRCamera) {
  18135. serializationObject.type = "WebVRCamera";
  18136. }
  18137. else if (camera instanceof BABYLON.VRDeviceOrientationCamera) {
  18138. serializationObject.type = "VRDeviceOrientationCamera";
  18139. }
  18140. //special properties of specific cameras
  18141. if (camera instanceof BABYLON.ArcRotateCamera || camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  18142. var arcCamera = camera;
  18143. serializationObject.alpha = arcCamera.alpha;
  18144. serializationObject.beta = arcCamera.beta;
  18145. serializationObject.radius = arcCamera.radius;
  18146. if (arcCamera.target && arcCamera.target.id) {
  18147. serializationObject.lockedTargetId = arcCamera.target.id;
  18148. }
  18149. }
  18150. else if (camera instanceof BABYLON.FollowCamera) {
  18151. var followCam = camera;
  18152. serializationObject.radius = followCam.radius;
  18153. serializationObject.heightOffset = followCam.heightOffset;
  18154. serializationObject.rotationOffset = followCam.rotationOffset;
  18155. }
  18156. else if (camera instanceof BABYLON.AnaglyphFreeCamera || camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  18157. //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.
  18158. if (camera['_eyeSpace'] !== undefined) {
  18159. serializationObject.eye_space = BABYLON.Tools.ToDegrees(camera['_eyeSpace']);
  18160. }
  18161. }
  18162. //general properties that not all cameras have. The [] is due to typescript's type safety
  18163. if (camera['speed'] !== undefined) {
  18164. serializationObject.speed = camera['speed'];
  18165. }
  18166. if (camera['target'] && camera['target'] instanceof BABYLON.Vector3) {
  18167. serializationObject.target = camera['target'].asArray();
  18168. }
  18169. // Target
  18170. if (camera['rotation'] && camera['rotation'] instanceof BABYLON.Vector3) {
  18171. serializationObject.rotation = camera['rotation'].asArray();
  18172. }
  18173. // Locked target
  18174. if (camera['lockedTarget'] && camera['lockedTarget'].id) {
  18175. serializationObject.lockedTargetId = camera['lockedTarget'].id;
  18176. }
  18177. serializationObject.checkCollisions = camera['checkCollisions'] || false;
  18178. serializationObject.applyGravity = camera['applyGravity'] || false;
  18179. if (camera['ellipsoid']) {
  18180. serializationObject.ellipsoid = camera['ellipsoid'].asArray();
  18181. }
  18182. // Animations
  18183. appendAnimations(camera, serializationObject);
  18184. // Layer mask
  18185. serializationObject.layerMask = camera.layerMask;
  18186. return serializationObject;
  18187. };
  18188. var serializeAnimation = function (animation) {
  18189. var serializationObject = {};
  18190. serializationObject.name = animation.name;
  18191. serializationObject.property = animation.targetProperty;
  18192. serializationObject.framePerSecond = animation.framePerSecond;
  18193. serializationObject.dataType = animation.dataType;
  18194. serializationObject.loopBehavior = animation.loopMode;
  18195. var dataType = animation.dataType;
  18196. serializationObject.keys = [];
  18197. var keys = animation.getKeys();
  18198. for (var index = 0; index < keys.length; index++) {
  18199. var animationKey = keys[index];
  18200. var key = {};
  18201. key.frame = animationKey.frame;
  18202. switch (dataType) {
  18203. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  18204. key.values = [animationKey.value];
  18205. break;
  18206. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  18207. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  18208. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  18209. key.values = animationKey.value.asArray();
  18210. break;
  18211. }
  18212. serializationObject.keys.push(key);
  18213. }
  18214. return serializationObject;
  18215. };
  18216. var serializeMultiMaterial = function (material) {
  18217. var serializationObject = {};
  18218. serializationObject.name = material.name;
  18219. serializationObject.id = material.id;
  18220. serializationObject.tags = BABYLON.Tags.GetTags(material);
  18221. serializationObject.materials = [];
  18222. for (var matIndex = 0; matIndex < material.subMaterials.length; matIndex++) {
  18223. var subMat = material.subMaterials[matIndex];
  18224. if (subMat) {
  18225. serializationObject.materials.push(subMat.id);
  18226. }
  18227. else {
  18228. serializationObject.materials.push(null);
  18229. }
  18230. }
  18231. return serializationObject;
  18232. };
  18233. var serializeMaterial = function (material) {
  18234. var serializationObject = {};
  18235. serializationObject.name = material.name;
  18236. serializationObject.ambient = material.ambientColor.asArray();
  18237. serializationObject.diffuse = material.diffuseColor.asArray();
  18238. serializationObject.specular = material.specularColor.asArray();
  18239. serializationObject.specularPower = material.specularPower;
  18240. serializationObject.emissive = material.emissiveColor.asArray();
  18241. serializationObject.alpha = material.alpha;
  18242. serializationObject.id = material.id;
  18243. serializationObject.tags = BABYLON.Tags.GetTags(material);
  18244. serializationObject.backFaceCulling = material.backFaceCulling;
  18245. if (material.diffuseTexture) {
  18246. serializationObject.diffuseTexture = serializeTexture(material.diffuseTexture);
  18247. }
  18248. if (material.diffuseFresnelParameters) {
  18249. serializationObject.diffuseFresnelParameters = serializeFresnelParameter(material.diffuseFresnelParameters);
  18250. }
  18251. if (material.ambientTexture) {
  18252. serializationObject.ambientTexture = serializeTexture(material.ambientTexture);
  18253. }
  18254. if (material.opacityTexture) {
  18255. serializationObject.opacityTexture = serializeTexture(material.opacityTexture);
  18256. }
  18257. if (material.opacityFresnelParameters) {
  18258. serializationObject.opacityFresnelParameters = serializeFresnelParameter(material.opacityFresnelParameters);
  18259. }
  18260. if (material.reflectionTexture) {
  18261. serializationObject.reflectionTexture = serializeTexture(material.reflectionTexture);
  18262. }
  18263. if (material.reflectionFresnelParameters) {
  18264. serializationObject.reflectionFresnelParameters = serializeFresnelParameter(material.reflectionFresnelParameters);
  18265. }
  18266. if (material.emissiveTexture) {
  18267. serializationObject.emissiveTexture = serializeTexture(material.emissiveTexture);
  18268. }
  18269. if (material.emissiveFresnelParameters) {
  18270. serializationObject.emissiveFresnelParameters = serializeFresnelParameter(material.emissiveFresnelParameters);
  18271. }
  18272. if (material.specularTexture) {
  18273. serializationObject.specularTexture = serializeTexture(material.specularTexture);
  18274. }
  18275. if (material.bumpTexture) {
  18276. serializationObject.bumpTexture = serializeTexture(material.bumpTexture);
  18277. }
  18278. return serializationObject;
  18279. };
  18280. var serializeTexture = function (texture) {
  18281. var serializationObject = {};
  18282. if (!texture.name) {
  18283. return null;
  18284. }
  18285. if (texture instanceof BABYLON.CubeTexture) {
  18286. serializationObject.name = texture.name;
  18287. serializationObject.hasAlpha = texture.hasAlpha;
  18288. serializationObject.level = texture.level;
  18289. serializationObject.coordinatesMode = texture.coordinatesMode;
  18290. return serializationObject;
  18291. }
  18292. if (texture instanceof BABYLON.MirrorTexture) {
  18293. var mirrorTexture = texture;
  18294. serializationObject.renderTargetSize = mirrorTexture.getRenderSize();
  18295. serializationObject.renderList = [];
  18296. for (var index = 0; index < mirrorTexture.renderList.length; index++) {
  18297. serializationObject.renderList.push(mirrorTexture.renderList[index].id);
  18298. }
  18299. serializationObject.mirrorPlane = mirrorTexture.mirrorPlane.asArray();
  18300. }
  18301. else if (texture instanceof BABYLON.RenderTargetTexture) {
  18302. var renderTargetTexture = texture;
  18303. serializationObject.renderTargetSize = renderTargetTexture.getRenderSize();
  18304. serializationObject.renderList = [];
  18305. for (index = 0; index < renderTargetTexture.renderList.length; index++) {
  18306. serializationObject.renderList.push(renderTargetTexture.renderList[index].id);
  18307. }
  18308. }
  18309. var regularTexture = texture;
  18310. serializationObject.name = texture.name;
  18311. serializationObject.hasAlpha = texture.hasAlpha;
  18312. serializationObject.level = texture.level;
  18313. serializationObject.coordinatesIndex = texture.coordinatesIndex;
  18314. serializationObject.coordinatesMode = texture.coordinatesMode;
  18315. serializationObject.uOffset = regularTexture.uOffset;
  18316. serializationObject.vOffset = regularTexture.vOffset;
  18317. serializationObject.uScale = regularTexture.uScale;
  18318. serializationObject.vScale = regularTexture.vScale;
  18319. serializationObject.uAng = regularTexture.uAng;
  18320. serializationObject.vAng = regularTexture.vAng;
  18321. serializationObject.wAng = regularTexture.wAng;
  18322. serializationObject.wrapU = texture.wrapU;
  18323. serializationObject.wrapV = texture.wrapV;
  18324. // Animations
  18325. appendAnimations(texture, serializationObject);
  18326. return serializationObject;
  18327. };
  18328. var serializeSkeleton = function (skeleton) {
  18329. var serializationObject = {};
  18330. serializationObject.name = skeleton.name;
  18331. serializationObject.id = skeleton.id;
  18332. serializationObject.bones = [];
  18333. for (var index = 0; index < skeleton.bones.length; index++) {
  18334. var bone = skeleton.bones[index];
  18335. var serializedBone = {
  18336. parentBoneIndex: bone.getParent() ? skeleton.bones.indexOf(bone.getParent()) : -1,
  18337. name: bone.name,
  18338. matrix: bone.getLocalMatrix().toArray()
  18339. };
  18340. serializationObject.bones.push(serializedBone);
  18341. if (bone.animations && bone.animations.length > 0) {
  18342. serializedBone.animation = serializeAnimation(bone.animations[0]);
  18343. }
  18344. }
  18345. return serializationObject;
  18346. };
  18347. var serializeParticleSystem = function (particleSystem) {
  18348. var serializationObject = {};
  18349. serializationObject.emitterId = particleSystem.emitter.id;
  18350. serializationObject.capacity = particleSystem.getCapacity();
  18351. if (particleSystem.particleTexture) {
  18352. serializationObject.textureName = particleSystem.particleTexture.name;
  18353. }
  18354. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  18355. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  18356. serializationObject.minSize = particleSystem.minSize;
  18357. serializationObject.maxSize = particleSystem.maxSize;
  18358. serializationObject.minLifeTime = particleSystem.minLifeTime;
  18359. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  18360. serializationObject.emitRate = particleSystem.emitRate;
  18361. serializationObject.minEmitBox = particleSystem.minEmitBox.asArray();
  18362. serializationObject.maxEmitBox = particleSystem.maxEmitBox.asArray();
  18363. serializationObject.gravity = particleSystem.gravity.asArray();
  18364. serializationObject.direction1 = particleSystem.direction1.asArray();
  18365. serializationObject.direction2 = particleSystem.direction2.asArray();
  18366. serializationObject.color1 = particleSystem.color1.asArray();
  18367. serializationObject.color2 = particleSystem.color2.asArray();
  18368. serializationObject.colorDead = particleSystem.colorDead.asArray();
  18369. serializationObject.updateSpeed = particleSystem.updateSpeed;
  18370. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  18371. serializationObject.textureMask = particleSystem.textureMask.asArray();
  18372. serializationObject.blendMode = particleSystem.blendMode;
  18373. return serializationObject;
  18374. };
  18375. var serializeLensFlareSystem = function (lensFlareSystem) {
  18376. var serializationObject = {};
  18377. serializationObject.emitterId = lensFlareSystem.getEmitter().id;
  18378. serializationObject.borderLimit = lensFlareSystem.borderLimit;
  18379. serializationObject.flares = [];
  18380. for (var index = 0; index < lensFlareSystem.lensFlares.length; index++) {
  18381. var flare = lensFlareSystem.lensFlares[index];
  18382. serializationObject.flares.push({
  18383. size: flare.size,
  18384. position: flare.position,
  18385. color: flare.color.asArray(),
  18386. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  18387. });
  18388. }
  18389. return serializationObject;
  18390. };
  18391. var serializeShadowGenerator = function (light) {
  18392. var serializationObject = {};
  18393. var shadowGenerator = light.getShadowGenerator();
  18394. serializationObject.lightId = light.id;
  18395. serializationObject.mapSize = shadowGenerator.getShadowMap().getRenderSize();
  18396. serializationObject.useVarianceShadowMap = shadowGenerator.useVarianceShadowMap;
  18397. serializationObject.usePoissonSampling = shadowGenerator.usePoissonSampling;
  18398. serializationObject.renderList = [];
  18399. for (var meshIndex = 0; meshIndex < shadowGenerator.getShadowMap().renderList.length; meshIndex++) {
  18400. var mesh = shadowGenerator.getShadowMap().renderList[meshIndex];
  18401. serializationObject.renderList.push(mesh.id);
  18402. }
  18403. return serializationObject;
  18404. };
  18405. var serializedGeometries = [];
  18406. var serializeGeometry = function (geometry, serializationGeometries) {
  18407. if (serializedGeometries[geometry.id]) {
  18408. return;
  18409. }
  18410. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  18411. serializationGeometries.boxes.push(serializeBox(geometry));
  18412. }
  18413. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  18414. serializationGeometries.spheres.push(serializeSphere(geometry));
  18415. }
  18416. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  18417. serializationGeometries.cylinders.push(serializeCylinder(geometry));
  18418. }
  18419. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  18420. serializationGeometries.toruses.push(serializeTorus(geometry));
  18421. }
  18422. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  18423. serializationGeometries.grounds.push(serializeGround(geometry));
  18424. }
  18425. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  18426. serializationGeometries.planes.push(serializePlane(geometry));
  18427. }
  18428. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  18429. serializationGeometries.torusKnots.push(serializeTorusKnot(geometry));
  18430. }
  18431. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  18432. throw new Error("Unknow primitive type");
  18433. }
  18434. else {
  18435. serializationGeometries.vertexData.push(serializeVertexData(geometry));
  18436. }
  18437. serializedGeometries[geometry.id] = true;
  18438. };
  18439. var serializeGeometryBase = function (geometry) {
  18440. var serializationObject = {};
  18441. serializationObject.id = geometry.id;
  18442. if (BABYLON.Tags.HasTags(geometry)) {
  18443. serializationObject.tags = BABYLON.Tags.GetTags(geometry);
  18444. }
  18445. return serializationObject;
  18446. };
  18447. var serializeVertexData = function (vertexData) {
  18448. var serializationObject = serializeGeometryBase(vertexData);
  18449. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  18450. serializationObject.positions = vertexData.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18451. }
  18452. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  18453. serializationObject.normals = vertexData.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18454. }
  18455. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  18456. serializationObject.uvs = vertexData.getVerticesData(BABYLON.VertexBuffer.UVKind);
  18457. }
  18458. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  18459. serializationObject.uvs2 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  18460. }
  18461. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  18462. serializationObject.colors = vertexData.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  18463. }
  18464. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  18465. serializationObject.matricesIndices = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  18466. serializationObject.matricesIndices._isExpanded = true;
  18467. }
  18468. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  18469. serializationObject.matricesWeights = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  18470. }
  18471. serializationObject.indices = vertexData.getIndices();
  18472. return serializationObject;
  18473. };
  18474. var serializePrimitive = function (primitive) {
  18475. var serializationObject = serializeGeometryBase(primitive);
  18476. serializationObject.canBeRegenerated = primitive.canBeRegenerated();
  18477. return serializationObject;
  18478. };
  18479. var serializeBox = function (box) {
  18480. var serializationObject = serializePrimitive(box);
  18481. serializationObject.size = box.size;
  18482. return serializationObject;
  18483. };
  18484. var serializeSphere = function (sphere) {
  18485. var serializationObject = serializePrimitive(sphere);
  18486. serializationObject.segments = sphere.segments;
  18487. serializationObject.diameter = sphere.diameter;
  18488. return serializationObject;
  18489. };
  18490. var serializeCylinder = function (cylinder) {
  18491. var serializationObject = serializePrimitive(cylinder);
  18492. serializationObject.height = cylinder.height;
  18493. serializationObject.diameterTop = cylinder.diameterTop;
  18494. serializationObject.diameterBottom = cylinder.diameterBottom;
  18495. serializationObject.tessellation = cylinder.tessellation;
  18496. return serializationObject;
  18497. };
  18498. var serializeTorus = function (torus) {
  18499. var serializationObject = serializePrimitive(torus);
  18500. serializationObject.diameter = torus.diameter;
  18501. serializationObject.thickness = torus.thickness;
  18502. serializationObject.tessellation = torus.tessellation;
  18503. return serializationObject;
  18504. };
  18505. var serializeGround = function (ground) {
  18506. var serializationObject = serializePrimitive(ground);
  18507. serializationObject.width = ground.width;
  18508. serializationObject.height = ground.height;
  18509. serializationObject.subdivisions = ground.subdivisions;
  18510. return serializationObject;
  18511. };
  18512. var serializePlane = function (plane) {
  18513. var serializationObject = serializePrimitive(plane);
  18514. serializationObject.size = plane.size;
  18515. return serializationObject;
  18516. };
  18517. var serializeTorusKnot = function (torusKnot) {
  18518. var serializationObject = serializePrimitive(torusKnot);
  18519. serializationObject.radius = torusKnot.radius;
  18520. serializationObject.tube = torusKnot.tube;
  18521. serializationObject.radialSegments = torusKnot.radialSegments;
  18522. serializationObject.tubularSegments = torusKnot.tubularSegments;
  18523. serializationObject.p = torusKnot.p;
  18524. serializationObject.q = torusKnot.q;
  18525. return serializationObject;
  18526. };
  18527. var serializeMesh = function (mesh, serializationScene) {
  18528. var serializationObject = {};
  18529. serializationObject.name = mesh.name;
  18530. serializationObject.id = mesh.id;
  18531. if (BABYLON.Tags.HasTags(mesh)) {
  18532. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  18533. }
  18534. serializationObject.position = mesh.position.asArray();
  18535. if (mesh.rotationQuaternion) {
  18536. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  18537. }
  18538. else if (mesh.rotation) {
  18539. serializationObject.rotation = mesh.rotation.asArray();
  18540. }
  18541. serializationObject.scaling = mesh.scaling.asArray();
  18542. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  18543. serializationObject.isEnabled = mesh.isEnabled();
  18544. serializationObject.isVisible = mesh.isVisible;
  18545. serializationObject.infiniteDistance = mesh.infiniteDistance;
  18546. serializationObject.pickable = mesh.isPickable;
  18547. serializationObject.receiveShadows = mesh.receiveShadows;
  18548. serializationObject.billboardMode = mesh.billboardMode;
  18549. serializationObject.visibility = mesh.visibility;
  18550. serializationObject.checkCollisions = mesh.checkCollisions;
  18551. // Parent
  18552. if (mesh.parent) {
  18553. serializationObject.parentId = mesh.parent.id;
  18554. }
  18555. // Geometry
  18556. var geometry = mesh._geometry;
  18557. if (geometry) {
  18558. var geometryId = geometry.id;
  18559. serializationObject.geometryId = geometryId;
  18560. if (!mesh.getScene().getGeometryByID(geometryId)) {
  18561. // 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
  18562. serializeGeometry(geometry, serializationScene.geometries);
  18563. }
  18564. // SubMeshes
  18565. serializationObject.subMeshes = [];
  18566. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  18567. var subMesh = mesh.subMeshes[subIndex];
  18568. serializationObject.subMeshes.push({
  18569. materialIndex: subMesh.materialIndex,
  18570. verticesStart: subMesh.verticesStart,
  18571. verticesCount: subMesh.verticesCount,
  18572. indexStart: subMesh.indexStart,
  18573. indexCount: subMesh.indexCount
  18574. });
  18575. }
  18576. }
  18577. // Material
  18578. if (mesh.material) {
  18579. serializationObject.materialId = mesh.material.id;
  18580. }
  18581. else {
  18582. mesh.material = null;
  18583. }
  18584. // Skeleton
  18585. if (mesh.skeleton) {
  18586. serializationObject.skeletonId = mesh.skeleton.id;
  18587. }
  18588. // Physics
  18589. if (mesh.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  18590. serializationObject.physicsMass = mesh.getPhysicsMass();
  18591. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  18592. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  18593. switch (mesh.getPhysicsImpostor()) {
  18594. case BABYLON.PhysicsEngine.BoxImpostor:
  18595. serializationObject.physicsImpostor = 1;
  18596. break;
  18597. case BABYLON.PhysicsEngine.SphereImpostor:
  18598. serializationObject.physicsImpostor = 2;
  18599. break;
  18600. }
  18601. }
  18602. // Instances
  18603. serializationObject.instances = [];
  18604. for (var index = 0; index < mesh.instances.length; index++) {
  18605. var instance = mesh.instances[index];
  18606. var serializationInstance = {
  18607. name: instance.name,
  18608. position: instance.position,
  18609. rotation: instance.rotation,
  18610. rotationQuaternion: instance.rotationQuaternion,
  18611. scaling: instance.scaling
  18612. };
  18613. serializationObject.instances.push(serializationInstance);
  18614. // Animations
  18615. appendAnimations(instance, serializationInstance);
  18616. }
  18617. // Animations
  18618. appendAnimations(mesh, serializationObject);
  18619. // Layer mask
  18620. serializationObject.layerMask = mesh.layerMask;
  18621. return serializationObject;
  18622. };
  18623. var SceneSerializer = (function () {
  18624. function SceneSerializer() {
  18625. }
  18626. SceneSerializer.Serialize = function (scene) {
  18627. var serializationObject = {};
  18628. // Scene
  18629. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  18630. serializationObject.autoClear = scene.autoClear;
  18631. serializationObject.clearColor = scene.clearColor.asArray();
  18632. serializationObject.ambientColor = scene.ambientColor.asArray();
  18633. serializationObject.gravity = scene.gravity.asArray();
  18634. // Fog
  18635. if (scene.fogMode && scene.fogMode !== 0) {
  18636. serializationObject.fogMode = scene.fogMode;
  18637. serializationObject.fogColor = scene.fogColor.asArray();
  18638. serializationObject.fogStart = scene.fogStart;
  18639. serializationObject.fogEnd = scene.fogEnd;
  18640. serializationObject.fogDensity = scene.fogDensity;
  18641. }
  18642. // Lights
  18643. serializationObject.lights = [];
  18644. for (var index = 0; index < scene.lights.length; index++) {
  18645. var light = scene.lights[index];
  18646. serializationObject.lights.push(serializeLight(light));
  18647. }
  18648. // Cameras
  18649. serializationObject.cameras = [];
  18650. for (index = 0; index < scene.cameras.length; index++) {
  18651. var camera = scene.cameras[index];
  18652. serializationObject.cameras.push(serializeCamera(camera));
  18653. }
  18654. if (scene.activeCamera) {
  18655. serializationObject.activeCameraID = scene.activeCamera.id;
  18656. }
  18657. // Materials
  18658. serializationObject.materials = [];
  18659. serializationObject.multiMaterials = [];
  18660. for (index = 0; index < scene.materials.length; index++) {
  18661. var material = scene.materials[index];
  18662. if (material instanceof BABYLON.StandardMaterial) {
  18663. serializationObject.materials.push(serializeMaterial(material));
  18664. }
  18665. else if (material instanceof BABYLON.MultiMaterial) {
  18666. serializationObject.multiMaterials.push(serializeMultiMaterial(material));
  18667. }
  18668. }
  18669. // Skeletons
  18670. serializationObject.skeletons = [];
  18671. for (index = 0; index < scene.skeletons.length; index++) {
  18672. serializationObject.skeletons.push(serializeSkeleton(scene.skeletons[index]));
  18673. }
  18674. // Geometries
  18675. serializationObject.geometries = {};
  18676. serializationObject.geometries.boxes = [];
  18677. serializationObject.geometries.spheres = [];
  18678. serializationObject.geometries.cylinders = [];
  18679. serializationObject.geometries.toruses = [];
  18680. serializationObject.geometries.grounds = [];
  18681. serializationObject.geometries.planes = [];
  18682. serializationObject.geometries.torusKnots = [];
  18683. serializationObject.geometries.vertexData = [];
  18684. serializedGeometries = [];
  18685. var geometries = scene.getGeometries();
  18686. for (index = 0; index < geometries.length; index++) {
  18687. var geometry = geometries[index];
  18688. if (geometry.isReady()) {
  18689. serializeGeometry(geometry, serializationObject.geometries);
  18690. }
  18691. }
  18692. // Meshes
  18693. serializationObject.meshes = [];
  18694. for (index = 0; index < scene.meshes.length; index++) {
  18695. var abstractMesh = scene.meshes[index];
  18696. if (abstractMesh instanceof BABYLON.Mesh) {
  18697. var mesh = abstractMesh;
  18698. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  18699. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  18700. }
  18701. }
  18702. }
  18703. // Particles Systems
  18704. serializationObject.particleSystems = [];
  18705. for (index = 0; index < scene.particleSystems.length; index++) {
  18706. serializationObject.particleSystems.push(serializeParticleSystem(scene.particleSystems[index]));
  18707. }
  18708. // Lens flares
  18709. serializationObject.lensFlareSystems = [];
  18710. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  18711. serializationObject.lensFlareSystems.push(serializeLensFlareSystem(scene.lensFlareSystems[index]));
  18712. }
  18713. // Shadows
  18714. serializationObject.shadowGenerators = [];
  18715. for (index = 0; index < scene.lights.length; index++) {
  18716. light = scene.lights[index];
  18717. if (light.getShadowGenerator()) {
  18718. serializationObject.shadowGenerators.push(serializeShadowGenerator(light));
  18719. }
  18720. }
  18721. return serializationObject;
  18722. };
  18723. return SceneSerializer;
  18724. })();
  18725. BABYLON.SceneSerializer = SceneSerializer;
  18726. })(BABYLON || (BABYLON = {}));
  18727. //# sourceMappingURL=babylon.sceneSerializer.js.mapvar BABYLON;
  18728. (function (BABYLON) {
  18729. var SceneLoader = (function () {
  18730. function SceneLoader() {
  18731. }
  18732. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  18733. get: function () {
  18734. return SceneLoader._ForceFullSceneLoadingForIncremental;
  18735. },
  18736. set: function (value) {
  18737. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  18738. },
  18739. enumerable: true,
  18740. configurable: true
  18741. });
  18742. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  18743. get: function () {
  18744. return SceneLoader._ShowLoadingScreen;
  18745. },
  18746. set: function (value) {
  18747. SceneLoader._ShowLoadingScreen = value;
  18748. },
  18749. enumerable: true,
  18750. configurable: true
  18751. });
  18752. SceneLoader._getPluginForFilename = function (sceneFilename) {
  18753. var dotPosition = sceneFilename.lastIndexOf(".");
  18754. var queryStringPosition = sceneFilename.indexOf("?");
  18755. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  18756. for (var index = 0; index < this._registeredPlugins.length; index++) {
  18757. var plugin = this._registeredPlugins[index];
  18758. if (plugin.extensions.indexOf(extension) !== -1) {
  18759. return plugin;
  18760. }
  18761. }
  18762. return this._registeredPlugins[this._registeredPlugins.length - 1];
  18763. };
  18764. // Public functions
  18765. SceneLoader.RegisterPlugin = function (plugin) {
  18766. plugin.extensions = plugin.extensions.toLowerCase();
  18767. SceneLoader._registeredPlugins.push(plugin);
  18768. };
  18769. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  18770. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  18771. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  18772. return;
  18773. }
  18774. var manifestChecked = function (success) {
  18775. scene.database = database;
  18776. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  18777. var importMeshFromData = function (data) {
  18778. var meshes = [];
  18779. var particleSystems = [];
  18780. var skeletons = [];
  18781. try {
  18782. if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  18783. if (onerror) {
  18784. onerror(scene, 'unable to load the scene');
  18785. }
  18786. return;
  18787. }
  18788. }
  18789. catch (e) {
  18790. if (onerror) {
  18791. onerror(scene, e);
  18792. }
  18793. return;
  18794. }
  18795. if (onsuccess) {
  18796. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  18797. onsuccess(meshes, particleSystems, skeletons);
  18798. }
  18799. };
  18800. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  18801. // Direct load
  18802. importMeshFromData(sceneFilename.substr(5));
  18803. return;
  18804. }
  18805. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  18806. importMeshFromData(data);
  18807. }, progressCallBack, database);
  18808. };
  18809. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  18810. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  18811. };
  18812. /**
  18813. * Load a scene
  18814. * @param rootUrl a string that defines the root url for scene and resources
  18815. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  18816. * @param engine is the instance of BABYLON.Engine to use to create the scene
  18817. */
  18818. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  18819. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  18820. };
  18821. /**
  18822. * Append a scene
  18823. * @param rootUrl a string that defines the root url for scene and resources
  18824. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  18825. * @param scene is the instance of BABYLON.Scene to append to
  18826. */
  18827. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  18828. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  18829. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  18830. return;
  18831. }
  18832. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  18833. var database;
  18834. if (SceneLoader.ShowLoadingScreen) {
  18835. scene.getEngine().displayLoadingUI();
  18836. }
  18837. var loadSceneFromData = function (data) {
  18838. scene.database = database;
  18839. if (!plugin.load(scene, data, rootUrl)) {
  18840. if (onerror) {
  18841. onerror(scene);
  18842. }
  18843. scene.getEngine().hideLoadingUI();
  18844. return;
  18845. }
  18846. if (onsuccess) {
  18847. onsuccess(scene);
  18848. }
  18849. if (SceneLoader.ShowLoadingScreen) {
  18850. scene.executeWhenReady(function () {
  18851. scene.getEngine().hideLoadingUI();
  18852. });
  18853. }
  18854. };
  18855. var manifestChecked = function (success) {
  18856. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  18857. };
  18858. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  18859. // Direct load
  18860. loadSceneFromData(sceneFilename.substr(5));
  18861. return;
  18862. }
  18863. if (rootUrl.indexOf("file:") === -1) {
  18864. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  18865. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  18866. }
  18867. else {
  18868. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  18869. }
  18870. };
  18871. // Flags
  18872. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  18873. SceneLoader._ShowLoadingScreen = true;
  18874. // Members
  18875. SceneLoader._registeredPlugins = new Array();
  18876. return SceneLoader;
  18877. })();
  18878. BABYLON.SceneLoader = SceneLoader;
  18879. ;
  18880. })(BABYLON || (BABYLON = {}));
  18881. //# sourceMappingURL=babylon.sceneLoader.js.mapvar BABYLON;
  18882. (function (BABYLON) {
  18883. var Internals;
  18884. (function (Internals) {
  18885. var checkColors4 = function (colors, count) {
  18886. // Check if color3 was used
  18887. if (colors.length === count * 3) {
  18888. var colors4 = [];
  18889. for (var index = 0; index < colors.length; index += 3) {
  18890. var newIndex = (index / 3) * 4;
  18891. colors4[newIndex] = colors[index];
  18892. colors4[newIndex + 1] = colors[index + 1];
  18893. colors4[newIndex + 2] = colors[index + 2];
  18894. colors4[newIndex + 3] = 1.0;
  18895. }
  18896. return colors4;
  18897. }
  18898. return colors;
  18899. };
  18900. var loadCubeTexture = function (rootUrl, parsedTexture, scene) {
  18901. var texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene);
  18902. texture.name = parsedTexture.name;
  18903. texture.hasAlpha = parsedTexture.hasAlpha;
  18904. texture.level = parsedTexture.level;
  18905. texture.coordinatesMode = parsedTexture.coordinatesMode;
  18906. return texture;
  18907. };
  18908. var loadTexture = function (rootUrl, parsedTexture, scene) {
  18909. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  18910. return null;
  18911. }
  18912. if (parsedTexture.isCube) {
  18913. return loadCubeTexture(rootUrl, parsedTexture, scene);
  18914. }
  18915. var texture;
  18916. if (parsedTexture.mirrorPlane) {
  18917. texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  18918. texture._waitingRenderList = parsedTexture.renderList;
  18919. texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  18920. }
  18921. else if (parsedTexture.isRenderTarget) {
  18922. texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  18923. texture._waitingRenderList = parsedTexture.renderList;
  18924. }
  18925. else {
  18926. texture = new BABYLON.Texture(rootUrl + parsedTexture.name, scene);
  18927. }
  18928. texture.name = parsedTexture.name;
  18929. texture.hasAlpha = parsedTexture.hasAlpha;
  18930. texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
  18931. texture.level = parsedTexture.level;
  18932. texture.coordinatesIndex = parsedTexture.coordinatesIndex;
  18933. texture.coordinatesMode = parsedTexture.coordinatesMode;
  18934. texture.uOffset = parsedTexture.uOffset;
  18935. texture.vOffset = parsedTexture.vOffset;
  18936. texture.uScale = parsedTexture.uScale;
  18937. texture.vScale = parsedTexture.vScale;
  18938. texture.uAng = parsedTexture.uAng;
  18939. texture.vAng = parsedTexture.vAng;
  18940. texture.wAng = parsedTexture.wAng;
  18941. texture.wrapU = parsedTexture.wrapU;
  18942. texture.wrapV = parsedTexture.wrapV;
  18943. // Animations
  18944. if (parsedTexture.animations) {
  18945. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  18946. var parsedAnimation = parsedTexture.animations[animationIndex];
  18947. texture.animations.push(parseAnimation(parsedAnimation));
  18948. }
  18949. }
  18950. return texture;
  18951. };
  18952. var parseSkeleton = function (parsedSkeleton, scene) {
  18953. var skeleton = new BABYLON.Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  18954. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  18955. var parsedBone = parsedSkeleton.bones[index];
  18956. var parentBone = null;
  18957. if (parsedBone.parentBoneIndex > -1) {
  18958. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  18959. }
  18960. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix));
  18961. if (parsedBone.animation) {
  18962. bone.animations.push(parseAnimation(parsedBone.animation));
  18963. }
  18964. }
  18965. return skeleton;
  18966. };
  18967. var parseFresnelParameters = function (parsedFresnelParameters) {
  18968. var fresnelParameters = new BABYLON.FresnelParameters();
  18969. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  18970. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  18971. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  18972. fresnelParameters.bias = parsedFresnelParameters.bias;
  18973. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  18974. return fresnelParameters;
  18975. };
  18976. var parseMaterial = function (parsedMaterial, scene, rootUrl) {
  18977. var material;
  18978. material = new BABYLON.StandardMaterial(parsedMaterial.name, scene);
  18979. material.ambientColor = BABYLON.Color3.FromArray(parsedMaterial.ambient);
  18980. material.diffuseColor = BABYLON.Color3.FromArray(parsedMaterial.diffuse);
  18981. material.specularColor = BABYLON.Color3.FromArray(parsedMaterial.specular);
  18982. material.specularPower = parsedMaterial.specularPower;
  18983. material.emissiveColor = BABYLON.Color3.FromArray(parsedMaterial.emissive);
  18984. material.alpha = parsedMaterial.alpha;
  18985. material.id = parsedMaterial.id;
  18986. BABYLON.Tags.AddTagsTo(material, parsedMaterial.tags);
  18987. material.backFaceCulling = parsedMaterial.backFaceCulling;
  18988. material.wireframe = parsedMaterial.wireframe;
  18989. if (parsedMaterial.diffuseTexture) {
  18990. material.diffuseTexture = loadTexture(rootUrl, parsedMaterial.diffuseTexture, scene);
  18991. }
  18992. if (parsedMaterial.diffuseFresnelParameters) {
  18993. material.diffuseFresnelParameters = parseFresnelParameters(parsedMaterial.diffuseFresnelParameters);
  18994. }
  18995. if (parsedMaterial.ambientTexture) {
  18996. material.ambientTexture = loadTexture(rootUrl, parsedMaterial.ambientTexture, scene);
  18997. }
  18998. if (parsedMaterial.opacityTexture) {
  18999. material.opacityTexture = loadTexture(rootUrl, parsedMaterial.opacityTexture, scene);
  19000. }
  19001. if (parsedMaterial.opacityFresnelParameters) {
  19002. material.opacityFresnelParameters = parseFresnelParameters(parsedMaterial.opacityFresnelParameters);
  19003. }
  19004. if (parsedMaterial.reflectionTexture) {
  19005. material.reflectionTexture = loadTexture(rootUrl, parsedMaterial.reflectionTexture, scene);
  19006. }
  19007. if (parsedMaterial.reflectionFresnelParameters) {
  19008. material.reflectionFresnelParameters = parseFresnelParameters(parsedMaterial.reflectionFresnelParameters);
  19009. }
  19010. if (parsedMaterial.emissiveTexture) {
  19011. material.emissiveTexture = loadTexture(rootUrl, parsedMaterial.emissiveTexture, scene);
  19012. }
  19013. if (parsedMaterial.emissiveFresnelParameters) {
  19014. material.emissiveFresnelParameters = parseFresnelParameters(parsedMaterial.emissiveFresnelParameters);
  19015. }
  19016. if (parsedMaterial.specularTexture) {
  19017. material.specularTexture = loadTexture(rootUrl, parsedMaterial.specularTexture, scene);
  19018. }
  19019. if (parsedMaterial.bumpTexture) {
  19020. material.bumpTexture = loadTexture(rootUrl, parsedMaterial.bumpTexture, scene);
  19021. }
  19022. return material;
  19023. };
  19024. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  19025. for (var index = 0; index < parsedData.materials.length; index++) {
  19026. var parsedMaterial = parsedData.materials[index];
  19027. if (parsedMaterial.id === id) {
  19028. return parseMaterial(parsedMaterial, scene, rootUrl);
  19029. }
  19030. }
  19031. return null;
  19032. };
  19033. var parseMultiMaterial = function (parsedMultiMaterial, scene) {
  19034. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  19035. multiMaterial.id = parsedMultiMaterial.id;
  19036. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  19037. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  19038. var subMatId = parsedMultiMaterial.materials[matIndex];
  19039. if (subMatId) {
  19040. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  19041. }
  19042. else {
  19043. multiMaterial.subMaterials.push(null);
  19044. }
  19045. }
  19046. return multiMaterial;
  19047. };
  19048. var parseLensFlareSystem = function (parsedLensFlareSystem, scene, rootUrl) {
  19049. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  19050. var lensFlareSystem = new BABYLON.LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  19051. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  19052. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  19053. var parsedFlare = parsedLensFlareSystem.flares[index];
  19054. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  19055. }
  19056. return lensFlareSystem;
  19057. };
  19058. var parseParticleSystem = function (parsedParticleSystem, scene, rootUrl) {
  19059. var emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  19060. var particleSystem = new BABYLON.ParticleSystem("particles#" + emitter.name, parsedParticleSystem.capacity, scene);
  19061. if (parsedParticleSystem.textureName) {
  19062. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  19063. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  19064. }
  19065. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  19066. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  19067. particleSystem.minSize = parsedParticleSystem.minSize;
  19068. particleSystem.maxSize = parsedParticleSystem.maxSize;
  19069. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  19070. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  19071. particleSystem.emitter = emitter;
  19072. particleSystem.emitRate = parsedParticleSystem.emitRate;
  19073. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  19074. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  19075. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  19076. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  19077. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  19078. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  19079. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  19080. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  19081. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  19082. particleSystem.targetStopDuration = parsedParticleSystem.targetStopFrame;
  19083. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  19084. particleSystem.blendMode = parsedParticleSystem.blendMode;
  19085. particleSystem.start();
  19086. return particleSystem;
  19087. };
  19088. var parseShadowGenerator = function (parsedShadowGenerator, scene) {
  19089. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  19090. var shadowGenerator = new BABYLON.ShadowGenerator(parsedShadowGenerator.mapSize, light);
  19091. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  19092. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  19093. shadowGenerator.getShadowMap().renderList.push(mesh);
  19094. }
  19095. if (parsedShadowGenerator.usePoissonSampling) {
  19096. shadowGenerator.usePoissonSampling = true;
  19097. }
  19098. else if (parsedShadowGenerator.useVarianceShadowMap) {
  19099. shadowGenerator.useVarianceShadowMap = true;
  19100. }
  19101. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  19102. shadowGenerator.useBlurVarianceShadowMap = true;
  19103. }
  19104. if (parsedShadowGenerator.bias) {
  19105. shadowGenerator.bias = parsedShadowGenerator.bias;
  19106. }
  19107. return shadowGenerator;
  19108. };
  19109. var parseAnimation = function (parsedAnimation) {
  19110. var animation = new BABYLON.Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  19111. var dataType = parsedAnimation.dataType;
  19112. var keys = [];
  19113. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  19114. var key = parsedAnimation.keys[index];
  19115. var data;
  19116. switch (dataType) {
  19117. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  19118. data = key.values[0];
  19119. break;
  19120. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  19121. data = BABYLON.Quaternion.FromArray(key.values);
  19122. break;
  19123. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  19124. data = BABYLON.Matrix.FromArray(key.values);
  19125. break;
  19126. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  19127. default:
  19128. data = BABYLON.Vector3.FromArray(key.values);
  19129. break;
  19130. }
  19131. keys.push({
  19132. frame: key.frame,
  19133. value: data
  19134. });
  19135. }
  19136. animation.setKeys(keys);
  19137. return animation;
  19138. };
  19139. var parseLight = function (parsedLight, scene) {
  19140. var light;
  19141. switch (parsedLight.type) {
  19142. case 0:
  19143. light = new BABYLON.PointLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), scene);
  19144. break;
  19145. case 1:
  19146. light = new BABYLON.DirectionalLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  19147. light.position = BABYLON.Vector3.FromArray(parsedLight.position);
  19148. break;
  19149. case 2:
  19150. light = new BABYLON.SpotLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), BABYLON.Vector3.FromArray(parsedLight.direction), parsedLight.angle, parsedLight.exponent, scene);
  19151. break;
  19152. case 3:
  19153. light = new BABYLON.HemisphericLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  19154. light.groundColor = BABYLON.Color3.FromArray(parsedLight.groundColor);
  19155. break;
  19156. }
  19157. light.id = parsedLight.id;
  19158. BABYLON.Tags.AddTagsTo(light, parsedLight.tags);
  19159. if (parsedLight.intensity !== undefined) {
  19160. light.intensity = parsedLight.intensity;
  19161. }
  19162. if (parsedLight.range) {
  19163. light.range = parsedLight.range;
  19164. }
  19165. light.diffuse = BABYLON.Color3.FromArray(parsedLight.diffuse);
  19166. light.specular = BABYLON.Color3.FromArray(parsedLight.specular);
  19167. if (parsedLight.excludedMeshesIds) {
  19168. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  19169. }
  19170. // Parent
  19171. if (parsedLight.parentId) {
  19172. light._waitingParentId = parsedLight.parentId;
  19173. }
  19174. if (parsedLight.includedOnlyMeshesIds) {
  19175. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  19176. }
  19177. // Animations
  19178. if (parsedLight.animations) {
  19179. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  19180. var parsedAnimation = parsedLight.animations[animationIndex];
  19181. light.animations.push(parseAnimation(parsedAnimation));
  19182. }
  19183. }
  19184. if (parsedLight.autoAnimate) {
  19185. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, 1.0);
  19186. }
  19187. };
  19188. var parseCamera = function (parsedCamera, scene) {
  19189. var camera;
  19190. var position = BABYLON.Vector3.FromArray(parsedCamera.position);
  19191. var lockedTargetMesh = (parsedCamera.lockedTargetId) ? scene.getLastMeshByID(parsedCamera.lockedTargetId) : null;
  19192. if (parsedCamera.type === "AnaglyphArcRotateCamera" || parsedCamera.type === "ArcRotateCamera") {
  19193. var alpha = parsedCamera.alpha;
  19194. var beta = parsedCamera.beta;
  19195. var radius = parsedCamera.radius;
  19196. if (parsedCamera.type === "AnaglyphArcRotateCamera") {
  19197. var eye_space = parsedCamera.eye_space;
  19198. camera = new BABYLON.AnaglyphArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, eye_space, scene);
  19199. }
  19200. else {
  19201. camera = new BABYLON.ArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, scene);
  19202. }
  19203. }
  19204. else if (parsedCamera.type === "AnaglyphFreeCamera") {
  19205. eye_space = parsedCamera.eye_space;
  19206. camera = new BABYLON.AnaglyphFreeCamera(parsedCamera.name, position, eye_space, scene);
  19207. }
  19208. else if (parsedCamera.type === "DeviceOrientationCamera") {
  19209. camera = new BABYLON.DeviceOrientationCamera(parsedCamera.name, position, scene);
  19210. }
  19211. else if (parsedCamera.type === "FollowCamera") {
  19212. camera = new BABYLON.FollowCamera(parsedCamera.name, position, scene);
  19213. camera.heightOffset = parsedCamera.heightOffset;
  19214. camera.radius = parsedCamera.radius;
  19215. camera.rotationOffset = parsedCamera.rotationOffset;
  19216. if (lockedTargetMesh)
  19217. camera.target = lockedTargetMesh;
  19218. }
  19219. else if (parsedCamera.type === "GamepadCamera") {
  19220. camera = new BABYLON.GamepadCamera(parsedCamera.name, position, scene);
  19221. }
  19222. else if (parsedCamera.type === "OculusCamera") {
  19223. camera = new BABYLON.OculusCamera(parsedCamera.name, position, scene);
  19224. }
  19225. else if (parsedCamera.type === "OculusGamepadCamera") {
  19226. camera = new BABYLON.OculusGamepadCamera(parsedCamera.name, position, scene);
  19227. }
  19228. else if (parsedCamera.type === "TouchCamera") {
  19229. camera = new BABYLON.TouchCamera(parsedCamera.name, position, scene);
  19230. }
  19231. else if (parsedCamera.type === "VirtualJoysticksCamera") {
  19232. camera = new BABYLON.VirtualJoysticksCamera(parsedCamera.name, position, scene);
  19233. }
  19234. else if (parsedCamera.type === "WebVRCamera") {
  19235. camera = new BABYLON.WebVRCamera(parsedCamera.name, position, scene);
  19236. }
  19237. else if (parsedCamera.type === "VRDeviceOrientationCamera") {
  19238. camera = new BABYLON.VRDeviceOrientationCamera(parsedCamera.name, position, scene);
  19239. }
  19240. else {
  19241. // Free Camera is the default value
  19242. camera = new BABYLON.FreeCamera(parsedCamera.name, position, scene);
  19243. }
  19244. // Test for lockedTargetMesh & FreeCamera outside of if-else-if nest, since things like GamepadCamera extend FreeCamera
  19245. if (lockedTargetMesh && camera instanceof BABYLON.FreeCamera) {
  19246. camera.lockedTarget = lockedTargetMesh;
  19247. }
  19248. camera.id = parsedCamera.id;
  19249. BABYLON.Tags.AddTagsTo(camera, parsedCamera.tags);
  19250. // Parent
  19251. if (parsedCamera.parentId) {
  19252. camera._waitingParentId = parsedCamera.parentId;
  19253. }
  19254. // Target
  19255. if (parsedCamera.target) {
  19256. if (camera.setTarget) {
  19257. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  19258. }
  19259. else {
  19260. //For ArcRotate
  19261. camera.target = BABYLON.Vector3.FromArray(parsedCamera.target);
  19262. }
  19263. }
  19264. else {
  19265. camera.rotation = BABYLON.Vector3.FromArray(parsedCamera.rotation);
  19266. }
  19267. camera.fov = parsedCamera.fov;
  19268. camera.minZ = parsedCamera.minZ;
  19269. camera.maxZ = parsedCamera.maxZ;
  19270. camera.speed = parsedCamera.speed;
  19271. camera.inertia = parsedCamera.inertia;
  19272. camera.checkCollisions = parsedCamera.checkCollisions;
  19273. camera.applyGravity = parsedCamera.applyGravity;
  19274. if (parsedCamera.ellipsoid) {
  19275. camera.ellipsoid = BABYLON.Vector3.FromArray(parsedCamera.ellipsoid);
  19276. }
  19277. // Animations
  19278. if (parsedCamera.animations) {
  19279. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  19280. var parsedAnimation = parsedCamera.animations[animationIndex];
  19281. camera.animations.push(parseAnimation(parsedAnimation));
  19282. }
  19283. }
  19284. if (parsedCamera.autoAnimate) {
  19285. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, 1.0);
  19286. }
  19287. // Layer Mask
  19288. if (parsedCamera.layerMask && (!isNaN(parsedCamera.layerMask))) {
  19289. camera.layerMask = Math.abs(parseInt(parsedCamera.layerMask));
  19290. }
  19291. else {
  19292. camera.layerMask = 0xFFFFFFFF;
  19293. }
  19294. return camera;
  19295. };
  19296. var parseGeometry = function (parsedGeometry, scene) {
  19297. var id = parsedGeometry.id;
  19298. return scene.getGeometryByID(id);
  19299. };
  19300. var parseBox = function (parsedBox, scene) {
  19301. if (parseGeometry(parsedBox, scene)) {
  19302. return null; // null since geometry could be something else than a box...
  19303. }
  19304. var box = new BABYLON.Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  19305. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  19306. scene.pushGeometry(box, true);
  19307. return box;
  19308. };
  19309. var parseSphere = function (parsedSphere, scene) {
  19310. if (parseGeometry(parsedSphere, scene)) {
  19311. return null; // null since geometry could be something else than a sphere...
  19312. }
  19313. var sphere = new BABYLON.Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  19314. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  19315. scene.pushGeometry(sphere, true);
  19316. return sphere;
  19317. };
  19318. var parseCylinder = function (parsedCylinder, scene) {
  19319. if (parseGeometry(parsedCylinder, scene)) {
  19320. return null; // null since geometry could be something else than a cylinder...
  19321. }
  19322. var cylinder = new BABYLON.Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  19323. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  19324. scene.pushGeometry(cylinder, true);
  19325. return cylinder;
  19326. };
  19327. var parseTorus = function (parsedTorus, scene) {
  19328. if (parseGeometry(parsedTorus, scene)) {
  19329. return null; // null since geometry could be something else than a torus...
  19330. }
  19331. var torus = new BABYLON.Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  19332. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  19333. scene.pushGeometry(torus, true);
  19334. return torus;
  19335. };
  19336. var parseGround = function (parsedGround, scene) {
  19337. if (parseGeometry(parsedGround, scene)) {
  19338. return null; // null since geometry could be something else than a ground...
  19339. }
  19340. var ground = new BABYLON.Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  19341. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  19342. scene.pushGeometry(ground, true);
  19343. return ground;
  19344. };
  19345. var parsePlane = function (parsedPlane, scene) {
  19346. if (parseGeometry(parsedPlane, scene)) {
  19347. return null; // null since geometry could be something else than a plane...
  19348. }
  19349. var plane = new BABYLON.Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  19350. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  19351. scene.pushGeometry(plane, true);
  19352. return plane;
  19353. };
  19354. var parseTorusKnot = function (parsedTorusKnot, scene) {
  19355. if (parseGeometry(parsedTorusKnot, scene)) {
  19356. return null; // null since geometry could be something else than a torusKnot...
  19357. }
  19358. 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);
  19359. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  19360. scene.pushGeometry(torusKnot, true);
  19361. return torusKnot;
  19362. };
  19363. var parseVertexData = function (parsedVertexData, scene, rootUrl) {
  19364. if (parseGeometry(parsedVertexData, scene)) {
  19365. return null; // null since geometry could be a primitive
  19366. }
  19367. var geometry = new BABYLON.Geometry(parsedVertexData.id, scene);
  19368. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  19369. if (parsedVertexData.delayLoadingFile) {
  19370. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  19371. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  19372. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  19373. geometry._delayInfo = [];
  19374. if (parsedVertexData.hasUVs) {
  19375. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  19376. }
  19377. if (parsedVertexData.hasUVs2) {
  19378. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  19379. }
  19380. if (parsedVertexData.hasColors) {
  19381. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  19382. }
  19383. if (parsedVertexData.hasMatricesIndices) {
  19384. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  19385. }
  19386. if (parsedVertexData.hasMatricesWeights) {
  19387. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  19388. }
  19389. geometry._delayLoadingFunction = importVertexData;
  19390. }
  19391. else {
  19392. importVertexData(parsedVertexData, geometry);
  19393. }
  19394. scene.pushGeometry(geometry, true);
  19395. return geometry;
  19396. };
  19397. var parseMesh = function (parsedMesh, scene, rootUrl) {
  19398. var mesh = new BABYLON.Mesh(parsedMesh.name, scene);
  19399. mesh.id = parsedMesh.id;
  19400. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  19401. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  19402. if (parsedMesh.rotationQuaternion) {
  19403. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  19404. }
  19405. else if (parsedMesh.rotation) {
  19406. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  19407. }
  19408. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  19409. if (parsedMesh.localMatrix) {
  19410. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  19411. }
  19412. else if (parsedMesh.pivotMatrix) {
  19413. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  19414. }
  19415. mesh.setEnabled(parsedMesh.isEnabled);
  19416. mesh.isVisible = parsedMesh.isVisible;
  19417. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  19418. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  19419. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  19420. if (parsedMesh.applyFog !== undefined) {
  19421. mesh.applyFog = parsedMesh.applyFog;
  19422. }
  19423. if (parsedMesh.pickable !== undefined) {
  19424. mesh.isPickable = parsedMesh.pickable;
  19425. }
  19426. if (parsedMesh.alphaIndex !== undefined) {
  19427. mesh.alphaIndex = parsedMesh.alphaIndex;
  19428. }
  19429. mesh.receiveShadows = parsedMesh.receiveShadows;
  19430. mesh.billboardMode = parsedMesh.billboardMode;
  19431. if (parsedMesh.visibility !== undefined) {
  19432. mesh.visibility = parsedMesh.visibility;
  19433. }
  19434. mesh.checkCollisions = parsedMesh.checkCollisions;
  19435. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  19436. // Parent
  19437. if (parsedMesh.parentId) {
  19438. mesh._waitingParentId = parsedMesh.parentId;
  19439. }
  19440. // Actions
  19441. if (parsedMesh.actions !== undefined) {
  19442. mesh._waitingActions = parsedMesh.actions;
  19443. }
  19444. // Geometry
  19445. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  19446. if (parsedMesh.delayLoadingFile) {
  19447. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  19448. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  19449. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  19450. if (parsedMesh._binaryInfo) {
  19451. mesh._binaryInfo = parsedMesh._binaryInfo;
  19452. }
  19453. mesh._delayInfo = [];
  19454. if (parsedMesh.hasUVs) {
  19455. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  19456. }
  19457. if (parsedMesh.hasUVs2) {
  19458. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  19459. }
  19460. if (parsedMesh.hasColors) {
  19461. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  19462. }
  19463. if (parsedMesh.hasMatricesIndices) {
  19464. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  19465. }
  19466. if (parsedMesh.hasMatricesWeights) {
  19467. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  19468. }
  19469. mesh._delayLoadingFunction = importGeometry;
  19470. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  19471. mesh._checkDelayState();
  19472. }
  19473. }
  19474. else {
  19475. importGeometry(parsedMesh, mesh);
  19476. }
  19477. // Material
  19478. if (parsedMesh.materialId) {
  19479. mesh.setMaterialByID(parsedMesh.materialId);
  19480. }
  19481. else {
  19482. mesh.material = null;
  19483. }
  19484. // Skeleton
  19485. if (parsedMesh.skeletonId > -1) {
  19486. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  19487. }
  19488. // Physics
  19489. if (parsedMesh.physicsImpostor) {
  19490. if (!scene.isPhysicsEnabled()) {
  19491. scene.enablePhysics();
  19492. }
  19493. mesh.setPhysicsState({ impostor: parsedMesh.physicsImpostor, mass: parsedMesh.physicsMass, friction: parsedMesh.physicsFriction, restitution: parsedMesh.physicsRestitution });
  19494. }
  19495. // Animations
  19496. if (parsedMesh.animations) {
  19497. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  19498. var parsedAnimation = parsedMesh.animations[animationIndex];
  19499. mesh.animations.push(parseAnimation(parsedAnimation));
  19500. }
  19501. }
  19502. if (parsedMesh.autoAnimate) {
  19503. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, 1.0);
  19504. }
  19505. // Layer Mask
  19506. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  19507. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  19508. }
  19509. else {
  19510. mesh.layerMask = 0xFFFFFFFF;
  19511. }
  19512. // Instances
  19513. if (parsedMesh.instances) {
  19514. for (var index = 0; index < parsedMesh.instances.length; index++) {
  19515. var parsedInstance = parsedMesh.instances[index];
  19516. var instance = mesh.createInstance(parsedInstance.name);
  19517. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  19518. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  19519. if (parsedInstance.rotationQuaternion) {
  19520. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  19521. }
  19522. else if (parsedInstance.rotation) {
  19523. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  19524. }
  19525. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  19526. instance.checkCollisions = mesh.checkCollisions;
  19527. if (parsedMesh.animations) {
  19528. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  19529. parsedAnimation = parsedMesh.animations[animationIndex];
  19530. instance.animations.push(parseAnimation(parsedAnimation));
  19531. }
  19532. }
  19533. }
  19534. }
  19535. return mesh;
  19536. };
  19537. var parseActions = function (parsedActions, object, scene) {
  19538. var actionManager = new BABYLON.ActionManager(scene);
  19539. if (object === null)
  19540. scene.actionManager = actionManager;
  19541. else
  19542. object.actionManager = actionManager;
  19543. // instanciate a new object
  19544. var instanciate = function (name, params) {
  19545. var newInstance = Object.create(BABYLON[name].prototype);
  19546. newInstance.constructor.apply(newInstance, params);
  19547. return newInstance;
  19548. };
  19549. var parseParameter = function (name, value, target, propertyPath) {
  19550. if (propertyPath === null) {
  19551. // String, boolean or float
  19552. var floatValue = parseFloat(value);
  19553. if (value === "true" || value === "false")
  19554. return value === "true";
  19555. else
  19556. return isNaN(floatValue) ? value : floatValue;
  19557. }
  19558. var effectiveTarget = propertyPath.split(".");
  19559. var values = value.split(",");
  19560. for (var i = 0; i < effectiveTarget.length; i++) {
  19561. target = target[effectiveTarget[i]];
  19562. }
  19563. // Return appropriate value with its type
  19564. if (target instanceof Boolean)
  19565. return values[0] === "true";
  19566. if (target instanceof String)
  19567. return values[0];
  19568. // Parameters with multiple values such as Vector3 etc.
  19569. var split = new Array();
  19570. for (var i = 0; i < values.length; i++)
  19571. split.push(parseFloat(values[i]));
  19572. if (target instanceof BABYLON.Vector3)
  19573. return BABYLON.Vector3.FromArray(split);
  19574. if (target instanceof BABYLON.Vector4)
  19575. return BABYLON.Vector4.FromArray(split);
  19576. if (target instanceof BABYLON.Color3)
  19577. return BABYLON.Color3.FromArray(split);
  19578. if (target instanceof BABYLON.Color4)
  19579. return BABYLON.Color4.FromArray(split);
  19580. return parseFloat(values[0]);
  19581. };
  19582. // traverse graph per trigger
  19583. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  19584. if (combineArray === void 0) { combineArray = null; }
  19585. if (parsedAction.detached)
  19586. return;
  19587. var parameters = new Array();
  19588. var target = null;
  19589. var propertyPath = null;
  19590. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  19591. // Parameters
  19592. if (parsedAction.type === 2)
  19593. parameters.push(actionManager);
  19594. else
  19595. parameters.push(trigger);
  19596. if (combine) {
  19597. var actions = new Array();
  19598. for (var j = 0; j < parsedAction.combine.length; j++) {
  19599. traverse(parsedAction.combine[j], BABYLON.ActionManager.NothingTrigger, condition, action, actions);
  19600. }
  19601. parameters.push(actions);
  19602. }
  19603. else {
  19604. for (var i = 0; i < parsedAction.properties.length; i++) {
  19605. var value = parsedAction.properties[i].value;
  19606. var name = parsedAction.properties[i].name;
  19607. if (name === "target")
  19608. value = target = scene.getNodeByName(value);
  19609. else if (name === "parent")
  19610. value = scene.getNodeByName(value);
  19611. else if (name === "sound")
  19612. value = scene.getSoundByName(value);
  19613. else if (name !== "propertyPath") {
  19614. if (parsedAction.type === 2 && name === "operator")
  19615. value = BABYLON.ValueCondition[value];
  19616. else
  19617. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  19618. }
  19619. else {
  19620. propertyPath = value;
  19621. }
  19622. parameters.push(value);
  19623. }
  19624. }
  19625. parameters.push(condition);
  19626. // If interpolate value action
  19627. if (parsedAction.name === "InterpolateValueAction") {
  19628. var param = parameters[parameters.length - 2];
  19629. parameters[parameters.length - 1] = param;
  19630. parameters[parameters.length - 2] = condition;
  19631. }
  19632. // Action or condition(s) and not CombineAction
  19633. var newAction = instanciate(parsedAction.name, parameters);
  19634. if (combineArray === null) {
  19635. if (newAction instanceof BABYLON.Condition) {
  19636. condition = newAction;
  19637. newAction = action;
  19638. }
  19639. else {
  19640. condition = null;
  19641. if (action)
  19642. action.then(newAction);
  19643. else
  19644. actionManager.registerAction(newAction);
  19645. }
  19646. }
  19647. else {
  19648. combineArray.push(newAction);
  19649. }
  19650. for (var i = 0; i < parsedAction.children.length; i++)
  19651. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  19652. };
  19653. for (var i = 0; i < parsedActions.children.length; i++) {
  19654. var triggerParams;
  19655. var trigger = parsedActions.children[i];
  19656. if (trigger.properties.length > 0) {
  19657. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: scene.getMeshByName(trigger.properties[0].value) };
  19658. }
  19659. else
  19660. triggerParams = BABYLON.ActionManager[trigger.name];
  19661. for (var j = 0; j < trigger.children.length; j++) {
  19662. if (!trigger.detached)
  19663. traverse(trigger.children[j], triggerParams, null, null);
  19664. }
  19665. }
  19666. };
  19667. var parseSound = function (parsedSound, scene, rootUrl) {
  19668. var soundName = parsedSound.name;
  19669. var soundUrl = rootUrl + soundName;
  19670. var options = {
  19671. autoplay: parsedSound.autoplay,
  19672. loop: parsedSound.loop,
  19673. volume: parsedSound.volume,
  19674. spatialSound: parsedSound.spatialSound,
  19675. maxDistance: parsedSound.maxDistance,
  19676. rolloffFactor: parsedSound.rolloffFactor,
  19677. refDistance: parsedSound.refDistance,
  19678. distanceModel: parsedSound.distanceModel,
  19679. playbackRate: parsedSound.playbackRate
  19680. };
  19681. var newSound = new BABYLON.Sound(soundName, soundUrl, scene, function () {
  19682. scene._removePendingData(newSound);
  19683. }, options);
  19684. scene._addPendingData(newSound);
  19685. if (parsedSound.position) {
  19686. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  19687. newSound.setPosition(soundPosition);
  19688. }
  19689. if (parsedSound.isDirectional) {
  19690. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  19691. if (parsedSound.localDirectionToMesh) {
  19692. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  19693. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  19694. }
  19695. }
  19696. if (parsedSound.connectedMeshId) {
  19697. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  19698. if (connectedMesh) {
  19699. newSound.attachToMesh(connectedMesh);
  19700. }
  19701. }
  19702. };
  19703. var isDescendantOf = function (mesh, names, hierarchyIds) {
  19704. names = (names instanceof Array) ? names : [names];
  19705. for (var i in names) {
  19706. if (mesh.name === names[i]) {
  19707. hierarchyIds.push(mesh.id);
  19708. return true;
  19709. }
  19710. }
  19711. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  19712. hierarchyIds.push(mesh.id);
  19713. return true;
  19714. }
  19715. return false;
  19716. };
  19717. var importVertexData = function (parsedVertexData, geometry) {
  19718. var vertexData = new BABYLON.VertexData();
  19719. // positions
  19720. var positions = parsedVertexData.positions;
  19721. if (positions) {
  19722. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  19723. }
  19724. // normals
  19725. var normals = parsedVertexData.normals;
  19726. if (normals) {
  19727. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  19728. }
  19729. // uvs
  19730. var uvs = parsedVertexData.uvs;
  19731. if (uvs) {
  19732. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  19733. }
  19734. // uv2s
  19735. var uv2s = parsedVertexData.uv2s;
  19736. if (uv2s) {
  19737. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  19738. }
  19739. // colors
  19740. var colors = parsedVertexData.colors;
  19741. if (colors) {
  19742. vertexData.set(checkColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  19743. }
  19744. // matricesIndices
  19745. var matricesIndices = parsedVertexData.matricesIndices;
  19746. if (matricesIndices) {
  19747. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  19748. }
  19749. // matricesWeights
  19750. var matricesWeights = parsedVertexData.matricesWeights;
  19751. if (matricesWeights) {
  19752. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  19753. }
  19754. // indices
  19755. var indices = parsedVertexData.indices;
  19756. if (indices) {
  19757. vertexData.indices = indices;
  19758. }
  19759. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  19760. };
  19761. var importGeometry = function (parsedGeometry, mesh) {
  19762. var scene = mesh.getScene();
  19763. // Geometry
  19764. var geometryId = parsedGeometry.geometryId;
  19765. if (geometryId) {
  19766. var geometry = scene.getGeometryByID(geometryId);
  19767. if (geometry) {
  19768. geometry.applyToMesh(mesh);
  19769. }
  19770. }
  19771. else if (parsedGeometry instanceof ArrayBuffer) {
  19772. var binaryInfo = mesh._binaryInfo;
  19773. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  19774. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  19775. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  19776. }
  19777. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  19778. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  19779. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  19780. }
  19781. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  19782. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  19783. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  19784. }
  19785. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  19786. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  19787. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  19788. }
  19789. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  19790. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  19791. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false);
  19792. }
  19793. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  19794. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  19795. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  19796. }
  19797. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  19798. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  19799. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  19800. }
  19801. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  19802. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  19803. mesh.setIndices(indicesData);
  19804. }
  19805. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  19806. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  19807. mesh.subMeshes = [];
  19808. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  19809. var materialIndex = subMeshesData[(i * 5) + 0];
  19810. var verticesStart = subMeshesData[(i * 5) + 1];
  19811. var verticesCount = subMeshesData[(i * 5) + 2];
  19812. var indexStart = subMeshesData[(i * 5) + 3];
  19813. var indexCount = subMeshesData[(i * 5) + 4];
  19814. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  19815. }
  19816. }
  19817. }
  19818. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  19819. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  19820. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  19821. if (parsedGeometry.uvs) {
  19822. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  19823. }
  19824. if (parsedGeometry.uvs2) {
  19825. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  19826. }
  19827. if (parsedGeometry.colors) {
  19828. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, checkColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  19829. }
  19830. if (parsedGeometry.matricesIndices) {
  19831. if (!parsedGeometry.matricesIndices._isExpanded) {
  19832. var floatIndices = [];
  19833. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  19834. var matricesIndex = parsedGeometry.matricesIndices[i];
  19835. floatIndices.push(matricesIndex & 0x000000FF);
  19836. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  19837. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  19838. floatIndices.push(matricesIndex >> 24);
  19839. }
  19840. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  19841. }
  19842. else {
  19843. delete parsedGeometry.matricesIndices._isExpanded;
  19844. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  19845. }
  19846. }
  19847. if (parsedGeometry.matricesWeights) {
  19848. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  19849. }
  19850. mesh.setIndices(parsedGeometry.indices);
  19851. // SubMeshes
  19852. if (parsedGeometry.subMeshes) {
  19853. mesh.subMeshes = [];
  19854. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  19855. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  19856. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  19857. }
  19858. }
  19859. }
  19860. // Flat shading
  19861. if (mesh._shouldGenerateFlatShading) {
  19862. mesh.convertToFlatShadedMesh();
  19863. delete mesh._shouldGenerateFlatShading;
  19864. }
  19865. // Update
  19866. mesh.computeWorldMatrix(true);
  19867. // Octree
  19868. if (scene._selectionOctree) {
  19869. scene._selectionOctree.addMesh(mesh);
  19870. }
  19871. };
  19872. BABYLON.SceneLoader.RegisterPlugin({
  19873. extensions: ".babylon",
  19874. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  19875. var parsedData = JSON.parse(data);
  19876. var loadedSkeletonsIds = [];
  19877. var loadedMaterialsIds = [];
  19878. var hierarchyIds = [];
  19879. for (var index = 0; index < parsedData.meshes.length; index++) {
  19880. var parsedMesh = parsedData.meshes[index];
  19881. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  19882. if (meshesNames instanceof Array) {
  19883. // Remove found mesh name from list.
  19884. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  19885. }
  19886. // Material ?
  19887. if (parsedMesh.materialId) {
  19888. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  19889. if (!materialFound) {
  19890. for (var multimatIndex = 0; multimatIndex < parsedData.multiMaterials.length; multimatIndex++) {
  19891. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  19892. if (parsedMultiMaterial.id == parsedMesh.materialId) {
  19893. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  19894. var subMatId = parsedMultiMaterial.materials[matIndex];
  19895. loadedMaterialsIds.push(subMatId);
  19896. parseMaterialById(subMatId, parsedData, scene, rootUrl);
  19897. }
  19898. loadedMaterialsIds.push(parsedMultiMaterial.id);
  19899. parseMultiMaterial(parsedMultiMaterial, scene);
  19900. materialFound = true;
  19901. break;
  19902. }
  19903. }
  19904. }
  19905. if (!materialFound) {
  19906. loadedMaterialsIds.push(parsedMesh.materialId);
  19907. parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  19908. }
  19909. }
  19910. // Skeleton ?
  19911. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  19912. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  19913. if (!skeletonAlreadyLoaded) {
  19914. for (var skeletonIndex = 0; skeletonIndex < parsedData.skeletons.length; skeletonIndex++) {
  19915. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  19916. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  19917. skeletons.push(parseSkeleton(parsedSkeleton, scene));
  19918. loadedSkeletonsIds.push(parsedSkeleton.id);
  19919. }
  19920. }
  19921. }
  19922. }
  19923. var mesh = parseMesh(parsedMesh, scene, rootUrl);
  19924. meshes.push(mesh);
  19925. }
  19926. }
  19927. for (index = 0; index < scene.meshes.length; index++) {
  19928. var currentMesh = scene.meshes[index];
  19929. if (currentMesh._waitingParentId) {
  19930. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  19931. currentMesh._waitingParentId = undefined;
  19932. }
  19933. }
  19934. // Particles
  19935. if (parsedData.particleSystems) {
  19936. for (index = 0; index < parsedData.particleSystems.length; index++) {
  19937. var parsedParticleSystem = parsedData.particleSystems[index];
  19938. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  19939. particleSystems.push(parseParticleSystem(parsedParticleSystem, scene, rootUrl));
  19940. }
  19941. }
  19942. }
  19943. return true;
  19944. },
  19945. load: function (scene, data, rootUrl) {
  19946. var parsedData = JSON.parse(data);
  19947. // Scene
  19948. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  19949. scene.autoClear = parsedData.autoClear;
  19950. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  19951. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  19952. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  19953. // Fog
  19954. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  19955. scene.fogMode = parsedData.fogMode;
  19956. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  19957. scene.fogStart = parsedData.fogStart;
  19958. scene.fogEnd = parsedData.fogEnd;
  19959. scene.fogDensity = parsedData.fogDensity;
  19960. }
  19961. for (var index = 0; index < parsedData.lights.length; index++) {
  19962. var parsedLight = parsedData.lights[index];
  19963. parseLight(parsedLight, scene);
  19964. }
  19965. // Materials
  19966. if (parsedData.materials) {
  19967. for (index = 0; index < parsedData.materials.length; index++) {
  19968. var parsedMaterial = parsedData.materials[index];
  19969. parseMaterial(parsedMaterial, scene, rootUrl);
  19970. }
  19971. }
  19972. if (parsedData.multiMaterials) {
  19973. for (index = 0; index < parsedData.multiMaterials.length; index++) {
  19974. var parsedMultiMaterial = parsedData.multiMaterials[index];
  19975. parseMultiMaterial(parsedMultiMaterial, scene);
  19976. }
  19977. }
  19978. // Skeletons
  19979. if (parsedData.skeletons) {
  19980. for (index = 0; index < parsedData.skeletons.length; index++) {
  19981. var parsedSkeleton = parsedData.skeletons[index];
  19982. parseSkeleton(parsedSkeleton, scene);
  19983. }
  19984. }
  19985. // Geometries
  19986. var geometries = parsedData.geometries;
  19987. if (geometries) {
  19988. // Boxes
  19989. var boxes = geometries.boxes;
  19990. if (boxes) {
  19991. for (index = 0; index < boxes.length; index++) {
  19992. var parsedBox = boxes[index];
  19993. parseBox(parsedBox, scene);
  19994. }
  19995. }
  19996. // Spheres
  19997. var spheres = geometries.spheres;
  19998. if (spheres) {
  19999. for (index = 0; index < spheres.length; index++) {
  20000. var parsedSphere = spheres[index];
  20001. parseSphere(parsedSphere, scene);
  20002. }
  20003. }
  20004. // Cylinders
  20005. var cylinders = geometries.cylinders;
  20006. if (cylinders) {
  20007. for (index = 0; index < cylinders.length; index++) {
  20008. var parsedCylinder = cylinders[index];
  20009. parseCylinder(parsedCylinder, scene);
  20010. }
  20011. }
  20012. // Toruses
  20013. var toruses = geometries.toruses;
  20014. if (toruses) {
  20015. for (index = 0; index < toruses.length; index++) {
  20016. var parsedTorus = toruses[index];
  20017. parseTorus(parsedTorus, scene);
  20018. }
  20019. }
  20020. // Grounds
  20021. var grounds = geometries.grounds;
  20022. if (grounds) {
  20023. for (index = 0; index < grounds.length; index++) {
  20024. var parsedGround = grounds[index];
  20025. parseGround(parsedGround, scene);
  20026. }
  20027. }
  20028. // Planes
  20029. var planes = geometries.planes;
  20030. if (planes) {
  20031. for (index = 0; index < planes.length; index++) {
  20032. var parsedPlane = planes[index];
  20033. parsePlane(parsedPlane, scene);
  20034. }
  20035. }
  20036. // TorusKnots
  20037. var torusKnots = geometries.torusKnots;
  20038. if (torusKnots) {
  20039. for (index = 0; index < torusKnots.length; index++) {
  20040. var parsedTorusKnot = torusKnots[index];
  20041. parseTorusKnot(parsedTorusKnot, scene);
  20042. }
  20043. }
  20044. // VertexData
  20045. var vertexData = geometries.vertexData;
  20046. if (vertexData) {
  20047. for (index = 0; index < vertexData.length; index++) {
  20048. var parsedVertexData = vertexData[index];
  20049. parseVertexData(parsedVertexData, scene, rootUrl);
  20050. }
  20051. }
  20052. }
  20053. for (index = 0; index < parsedData.meshes.length; index++) {
  20054. var parsedMesh = parsedData.meshes[index];
  20055. parseMesh(parsedMesh, scene, rootUrl);
  20056. }
  20057. for (index = 0; index < parsedData.cameras.length; index++) {
  20058. var parsedCamera = parsedData.cameras[index];
  20059. parseCamera(parsedCamera, scene);
  20060. }
  20061. if (parsedData.activeCameraID) {
  20062. scene.setActiveCameraByID(parsedData.activeCameraID);
  20063. }
  20064. for (index = 0; index < scene.cameras.length; index++) {
  20065. var camera = scene.cameras[index];
  20066. if (camera._waitingParentId) {
  20067. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  20068. camera._waitingParentId = undefined;
  20069. }
  20070. }
  20071. for (index = 0; index < scene.lights.length; index++) {
  20072. var light = scene.lights[index];
  20073. if (light._waitingParentId) {
  20074. light.parent = scene.getLastEntryByID(light._waitingParentId);
  20075. light._waitingParentId = undefined;
  20076. }
  20077. }
  20078. // Sounds
  20079. if (parsedData.sounds) {
  20080. for (index = 0; index < parsedData.sounds.length; index++) {
  20081. var parsedSound = parsedData.sounds[index];
  20082. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  20083. parseSound(parsedSound, scene, rootUrl);
  20084. }
  20085. else {
  20086. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  20087. }
  20088. }
  20089. }
  20090. for (index = 0; index < scene.meshes.length; index++) {
  20091. var mesh = scene.meshes[index];
  20092. if (mesh._waitingParentId) {
  20093. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  20094. mesh._waitingParentId = undefined;
  20095. }
  20096. if (mesh._waitingActions) {
  20097. parseActions(mesh._waitingActions, mesh, scene);
  20098. mesh._waitingActions = undefined;
  20099. }
  20100. }
  20101. // Particles Systems
  20102. if (parsedData.particleSystems) {
  20103. for (index = 0; index < parsedData.particleSystems.length; index++) {
  20104. var parsedParticleSystem = parsedData.particleSystems[index];
  20105. parseParticleSystem(parsedParticleSystem, scene, rootUrl);
  20106. }
  20107. }
  20108. // Lens flares
  20109. if (parsedData.lensFlareSystems) {
  20110. for (index = 0; index < parsedData.lensFlareSystems.length; index++) {
  20111. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  20112. parseLensFlareSystem(parsedLensFlareSystem, scene, rootUrl);
  20113. }
  20114. }
  20115. // Shadows
  20116. if (parsedData.shadowGenerators) {
  20117. for (index = 0; index < parsedData.shadowGenerators.length; index++) {
  20118. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  20119. parseShadowGenerator(parsedShadowGenerator, scene);
  20120. }
  20121. }
  20122. // Actions (scene)
  20123. if (parsedData.actions) {
  20124. parseActions(parsedData.actions, null, scene);
  20125. }
  20126. // Finish
  20127. return true;
  20128. }
  20129. });
  20130. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  20131. })(BABYLON || (BABYLON = {}));
  20132. //# sourceMappingURL=babylon.babylonFileLoader.js.mapvar BABYLON;
  20133. (function (BABYLON) {
  20134. // Unique ID when we import meshes from Babylon to CSG
  20135. var currentCSGMeshId = 0;
  20136. // # class Vertex
  20137. // Represents a vertex of a polygon. Use your own vertex class instead of this
  20138. // one to provide additional features like texture coordinates and vertex
  20139. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  20140. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  20141. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  20142. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  20143. // is not used anywhere else.
  20144. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  20145. var Vertex = (function () {
  20146. function Vertex(pos, normal, uv) {
  20147. this.pos = pos;
  20148. this.normal = normal;
  20149. this.uv = uv;
  20150. }
  20151. Vertex.prototype.clone = function () {
  20152. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  20153. };
  20154. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  20155. // orientation of a polygon is flipped.
  20156. Vertex.prototype.flip = function () {
  20157. this.normal = this.normal.scale(-1);
  20158. };
  20159. // Create a new vertex between this vertex and `other` by linearly
  20160. // interpolating all properties using a parameter of `t`. Subclasses should
  20161. // override this to interpolate additional properties.
  20162. Vertex.prototype.interpolate = function (other, t) {
  20163. 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));
  20164. };
  20165. return Vertex;
  20166. })();
  20167. // # class Plane
  20168. // Represents a plane in 3D space.
  20169. var Plane = (function () {
  20170. function Plane(normal, w) {
  20171. this.normal = normal;
  20172. this.w = w;
  20173. }
  20174. Plane.FromPoints = function (a, b, c) {
  20175. var v0 = c.subtract(a);
  20176. var v1 = b.subtract(a);
  20177. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  20178. return null;
  20179. }
  20180. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  20181. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  20182. };
  20183. Plane.prototype.clone = function () {
  20184. return new Plane(this.normal.clone(), this.w);
  20185. };
  20186. Plane.prototype.flip = function () {
  20187. this.normal.scaleInPlace(-1);
  20188. this.w = -this.w;
  20189. };
  20190. // Split `polygon` by this plane if needed, then put the polygon or polygon
  20191. // fragments in the appropriate lists. Coplanar polygons go into either
  20192. // `coplanarFront` or `coplanarBack` depending on their orientation with
  20193. // respect to this plane. Polygons in front or in back of this plane go into
  20194. // either `front` or `back`.
  20195. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  20196. var COPLANAR = 0;
  20197. var FRONT = 1;
  20198. var BACK = 2;
  20199. var SPANNING = 3;
  20200. // Classify each point as well as the entire polygon into one of the above
  20201. // four classes.
  20202. var polygonType = 0;
  20203. var types = [];
  20204. for (var i = 0; i < polygon.vertices.length; i++) {
  20205. var t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  20206. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  20207. polygonType |= type;
  20208. types.push(type);
  20209. }
  20210. switch (polygonType) {
  20211. case COPLANAR:
  20212. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  20213. break;
  20214. case FRONT:
  20215. front.push(polygon);
  20216. break;
  20217. case BACK:
  20218. back.push(polygon);
  20219. break;
  20220. case SPANNING:
  20221. var f = [], b = [];
  20222. for (i = 0; i < polygon.vertices.length; i++) {
  20223. var j = (i + 1) % polygon.vertices.length;
  20224. var ti = types[i], tj = types[j];
  20225. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  20226. if (ti != BACK)
  20227. f.push(vi);
  20228. if (ti != FRONT)
  20229. b.push(ti != BACK ? vi.clone() : vi);
  20230. if ((ti | tj) == SPANNING) {
  20231. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  20232. var v = vi.interpolate(vj, t);
  20233. f.push(v);
  20234. b.push(v.clone());
  20235. }
  20236. }
  20237. if (f.length >= 3) {
  20238. var poly = new Polygon(f, polygon.shared);
  20239. if (poly.plane)
  20240. front.push(poly);
  20241. }
  20242. if (b.length >= 3) {
  20243. poly = new Polygon(b, polygon.shared);
  20244. if (poly.plane)
  20245. back.push(poly);
  20246. }
  20247. break;
  20248. }
  20249. };
  20250. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  20251. // point is on the plane.
  20252. Plane.EPSILON = 1e-5;
  20253. return Plane;
  20254. })();
  20255. // # class Polygon
  20256. // Represents a convex polygon. The vertices used to initialize a polygon must
  20257. // be coplanar and form a convex loop.
  20258. //
  20259. // Each convex polygon has a `shared` property, which is shared between all
  20260. // polygons that are clones of each other or were split from the same polygon.
  20261. // This can be used to define per-polygon properties (such as surface color).
  20262. var Polygon = (function () {
  20263. function Polygon(vertices, shared) {
  20264. this.vertices = vertices;
  20265. this.shared = shared;
  20266. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  20267. }
  20268. Polygon.prototype.clone = function () {
  20269. var vertices = this.vertices.map(function (v) { return v.clone(); });
  20270. return new Polygon(vertices, this.shared);
  20271. };
  20272. Polygon.prototype.flip = function () {
  20273. this.vertices.reverse().map(function (v) {
  20274. v.flip();
  20275. });
  20276. this.plane.flip();
  20277. };
  20278. return Polygon;
  20279. })();
  20280. // # class Node
  20281. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  20282. // by picking a polygon to split along. That polygon (and all other coplanar
  20283. // polygons) are added directly to that node and the other polygons are added to
  20284. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  20285. // no distinction between internal and leaf nodes.
  20286. var Node = (function () {
  20287. function Node(polygons) {
  20288. this.plane = null;
  20289. this.front = null;
  20290. this.back = null;
  20291. this.polygons = [];
  20292. if (polygons) {
  20293. this.build(polygons);
  20294. }
  20295. }
  20296. Node.prototype.clone = function () {
  20297. var node = new Node();
  20298. node.plane = this.plane && this.plane.clone();
  20299. node.front = this.front && this.front.clone();
  20300. node.back = this.back && this.back.clone();
  20301. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  20302. return node;
  20303. };
  20304. // Convert solid space to empty space and empty space to solid space.
  20305. Node.prototype.invert = function () {
  20306. for (var i = 0; i < this.polygons.length; i++) {
  20307. this.polygons[i].flip();
  20308. }
  20309. if (this.plane) {
  20310. this.plane.flip();
  20311. }
  20312. if (this.front) {
  20313. this.front.invert();
  20314. }
  20315. if (this.back) {
  20316. this.back.invert();
  20317. }
  20318. var temp = this.front;
  20319. this.front = this.back;
  20320. this.back = temp;
  20321. };
  20322. // Recursively remove all polygons in `polygons` that are inside this BSP
  20323. // tree.
  20324. Node.prototype.clipPolygons = function (polygons) {
  20325. if (!this.plane)
  20326. return polygons.slice();
  20327. var front = [], back = [];
  20328. for (var i = 0; i < polygons.length; i++) {
  20329. this.plane.splitPolygon(polygons[i], front, back, front, back);
  20330. }
  20331. if (this.front) {
  20332. front = this.front.clipPolygons(front);
  20333. }
  20334. if (this.back) {
  20335. back = this.back.clipPolygons(back);
  20336. }
  20337. else {
  20338. back = [];
  20339. }
  20340. return front.concat(back);
  20341. };
  20342. // Remove all polygons in this BSP tree that are inside the other BSP tree
  20343. // `bsp`.
  20344. Node.prototype.clipTo = function (bsp) {
  20345. this.polygons = bsp.clipPolygons(this.polygons);
  20346. if (this.front)
  20347. this.front.clipTo(bsp);
  20348. if (this.back)
  20349. this.back.clipTo(bsp);
  20350. };
  20351. // Return a list of all polygons in this BSP tree.
  20352. Node.prototype.allPolygons = function () {
  20353. var polygons = this.polygons.slice();
  20354. if (this.front)
  20355. polygons = polygons.concat(this.front.allPolygons());
  20356. if (this.back)
  20357. polygons = polygons.concat(this.back.allPolygons());
  20358. return polygons;
  20359. };
  20360. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  20361. // new polygons are filtered down to the bottom of the tree and become new
  20362. // nodes there. Each set of polygons is partitioned using the first polygon
  20363. // (no heuristic is used to pick a good split).
  20364. Node.prototype.build = function (polygons) {
  20365. if (!polygons.length)
  20366. return;
  20367. if (!this.plane)
  20368. this.plane = polygons[0].plane.clone();
  20369. var front = [], back = [];
  20370. for (var i = 0; i < polygons.length; i++) {
  20371. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  20372. }
  20373. if (front.length) {
  20374. if (!this.front)
  20375. this.front = new Node();
  20376. this.front.build(front);
  20377. }
  20378. if (back.length) {
  20379. if (!this.back)
  20380. this.back = new Node();
  20381. this.back.build(back);
  20382. }
  20383. };
  20384. return Node;
  20385. })();
  20386. var CSG = (function () {
  20387. function CSG() {
  20388. this.polygons = new Array();
  20389. }
  20390. // Convert BABYLON.Mesh to BABYLON.CSG
  20391. CSG.FromMesh = function (mesh) {
  20392. var vertex, normal, uv, position, polygon, polygons = [], vertices;
  20393. if (mesh instanceof BABYLON.Mesh) {
  20394. mesh.computeWorldMatrix(true);
  20395. var matrix = mesh.getWorldMatrix();
  20396. var meshPosition = mesh.position.clone();
  20397. var meshRotation = mesh.rotation.clone();
  20398. var meshScaling = mesh.scaling.clone();
  20399. }
  20400. else {
  20401. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  20402. }
  20403. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  20404. var subMeshes = mesh.subMeshes;
  20405. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  20406. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  20407. vertices = [];
  20408. for (var j = 0; j < 3; j++) {
  20409. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  20410. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  20411. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  20412. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  20413. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  20414. vertex = new Vertex(position, normal, uv);
  20415. vertices.push(vertex);
  20416. }
  20417. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  20418. // To handle the case of degenerated triangle
  20419. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  20420. if (polygon.plane)
  20421. polygons.push(polygon);
  20422. }
  20423. }
  20424. var csg = CSG.FromPolygons(polygons);
  20425. csg.matrix = matrix;
  20426. csg.position = meshPosition;
  20427. csg.rotation = meshRotation;
  20428. csg.scaling = meshScaling;
  20429. currentCSGMeshId++;
  20430. return csg;
  20431. };
  20432. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  20433. CSG.FromPolygons = function (polygons) {
  20434. var csg = new BABYLON.CSG();
  20435. csg.polygons = polygons;
  20436. return csg;
  20437. };
  20438. CSG.prototype.clone = function () {
  20439. var csg = new BABYLON.CSG();
  20440. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  20441. csg.copyTransformAttributes(this);
  20442. return csg;
  20443. };
  20444. CSG.prototype.toPolygons = function () {
  20445. return this.polygons;
  20446. };
  20447. CSG.prototype.union = function (csg) {
  20448. var a = new Node(this.clone().polygons);
  20449. var b = new Node(csg.clone().polygons);
  20450. a.clipTo(b);
  20451. b.clipTo(a);
  20452. b.invert();
  20453. b.clipTo(a);
  20454. b.invert();
  20455. a.build(b.allPolygons());
  20456. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  20457. };
  20458. CSG.prototype.unionInPlace = function (csg) {
  20459. var a = new Node(this.polygons);
  20460. var b = new Node(csg.polygons);
  20461. a.clipTo(b);
  20462. b.clipTo(a);
  20463. b.invert();
  20464. b.clipTo(a);
  20465. b.invert();
  20466. a.build(b.allPolygons());
  20467. this.polygons = a.allPolygons();
  20468. };
  20469. CSG.prototype.subtract = function (csg) {
  20470. var a = new Node(this.clone().polygons);
  20471. var b = new Node(csg.clone().polygons);
  20472. a.invert();
  20473. a.clipTo(b);
  20474. b.clipTo(a);
  20475. b.invert();
  20476. b.clipTo(a);
  20477. b.invert();
  20478. a.build(b.allPolygons());
  20479. a.invert();
  20480. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  20481. };
  20482. CSG.prototype.subtractInPlace = function (csg) {
  20483. var a = new Node(this.polygons);
  20484. var b = new Node(csg.polygons);
  20485. a.invert();
  20486. a.clipTo(b);
  20487. b.clipTo(a);
  20488. b.invert();
  20489. b.clipTo(a);
  20490. b.invert();
  20491. a.build(b.allPolygons());
  20492. a.invert();
  20493. this.polygons = a.allPolygons();
  20494. };
  20495. CSG.prototype.intersect = function (csg) {
  20496. var a = new Node(this.clone().polygons);
  20497. var b = new Node(csg.clone().polygons);
  20498. a.invert();
  20499. b.clipTo(a);
  20500. b.invert();
  20501. a.clipTo(b);
  20502. b.clipTo(a);
  20503. a.build(b.allPolygons());
  20504. a.invert();
  20505. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  20506. };
  20507. CSG.prototype.intersectInPlace = function (csg) {
  20508. var a = new Node(this.polygons);
  20509. var b = new Node(csg.polygons);
  20510. a.invert();
  20511. b.clipTo(a);
  20512. b.invert();
  20513. a.clipTo(b);
  20514. b.clipTo(a);
  20515. a.build(b.allPolygons());
  20516. a.invert();
  20517. this.polygons = a.allPolygons();
  20518. };
  20519. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  20520. // not modified.
  20521. CSG.prototype.inverse = function () {
  20522. var csg = this.clone();
  20523. csg.inverseInPlace();
  20524. return csg;
  20525. };
  20526. CSG.prototype.inverseInPlace = function () {
  20527. this.polygons.map(function (p) {
  20528. p.flip();
  20529. });
  20530. };
  20531. // This is used to keep meshes transformations so they can be restored
  20532. // when we build back a Babylon Mesh
  20533. // NB : All CSG operations are performed in world coordinates
  20534. CSG.prototype.copyTransformAttributes = function (csg) {
  20535. this.matrix = csg.matrix;
  20536. this.position = csg.position;
  20537. this.rotation = csg.rotation;
  20538. this.scaling = csg.scaling;
  20539. return this;
  20540. };
  20541. // Build Raw mesh from CSG
  20542. // Coordinates here are in world space
  20543. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  20544. var matrix = this.matrix.clone();
  20545. matrix.invert();
  20546. 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;
  20547. if (keepSubMeshes) {
  20548. // Sort Polygons, since subMeshes are indices range
  20549. polygons.sort(function (a, b) {
  20550. if (a.shared.meshId === b.shared.meshId) {
  20551. return a.shared.subMeshId - b.shared.subMeshId;
  20552. }
  20553. else {
  20554. return a.shared.meshId - b.shared.meshId;
  20555. }
  20556. });
  20557. }
  20558. for (var i = 0, il = polygons.length; i < il; i++) {
  20559. polygon = polygons[i];
  20560. // Building SubMeshes
  20561. if (!subMesh_dict[polygon.shared.meshId]) {
  20562. subMesh_dict[polygon.shared.meshId] = {};
  20563. }
  20564. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  20565. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  20566. indexStart: +Infinity,
  20567. indexEnd: -Infinity,
  20568. materialIndex: polygon.shared.materialIndex
  20569. };
  20570. }
  20571. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  20572. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  20573. polygonIndices[0] = 0;
  20574. polygonIndices[1] = j - 1;
  20575. polygonIndices[2] = j;
  20576. for (var k = 0; k < 3; k++) {
  20577. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  20578. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  20579. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  20580. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  20581. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  20582. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  20583. // Check if 2 points can be merged
  20584. 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)) {
  20585. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  20586. uvs.push(uv.x, uv.y);
  20587. normals.push(normal.x, normal.y, normal.z);
  20588. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  20589. }
  20590. indices.push(vertex_idx);
  20591. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  20592. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  20593. currentIndex++;
  20594. }
  20595. }
  20596. }
  20597. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  20598. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  20599. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  20600. mesh.setIndices(indices);
  20601. if (keepSubMeshes) {
  20602. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  20603. var materialIndexOffset = 0, materialMaxIndex;
  20604. mesh.subMeshes.length = 0;
  20605. for (var m in subMesh_dict) {
  20606. materialMaxIndex = -1;
  20607. for (var sm in subMesh_dict[m]) {
  20608. subMesh_obj = subMesh_dict[m][sm];
  20609. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  20610. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  20611. }
  20612. materialIndexOffset += ++materialMaxIndex;
  20613. }
  20614. }
  20615. return mesh;
  20616. };
  20617. // Build Mesh from CSG taking material and transforms into account
  20618. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  20619. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  20620. mesh.material = material;
  20621. mesh.position.copyFrom(this.position);
  20622. mesh.rotation.copyFrom(this.rotation);
  20623. mesh.scaling.copyFrom(this.scaling);
  20624. mesh.computeWorldMatrix(true);
  20625. return mesh;
  20626. };
  20627. return CSG;
  20628. })();
  20629. BABYLON.CSG = CSG;
  20630. })(BABYLON || (BABYLON = {}));
  20631. //# sourceMappingURL=babylon.csg.js.map
  20632. var BABYLON;
  20633. (function (BABYLON) {
  20634. var OculusDistortionCorrectionPostProcess = (function (_super) {
  20635. __extends(OculusDistortionCorrectionPostProcess, _super);
  20636. //ANY
  20637. function OculusDistortionCorrectionPostProcess(name, camera, isRightEye, cameraSettings) {
  20638. var _this = this;
  20639. _super.call(this, name, "oculusDistortionCorrection", [
  20640. 'LensCenter',
  20641. 'Scale',
  20642. 'ScaleIn',
  20643. 'HmdWarpParam'
  20644. ], null, cameraSettings.PostProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  20645. this._isRightEye = isRightEye;
  20646. this._distortionFactors = cameraSettings.DistortionK;
  20647. this._postProcessScaleFactor = cameraSettings.PostProcessScaleFactor;
  20648. this._lensCenterOffset = cameraSettings.LensCenterOffset;
  20649. this.onSizeChanged = function () {
  20650. _this.aspectRatio = _this.width * .5 / _this.height;
  20651. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  20652. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  20653. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  20654. };
  20655. this.onApply = function (effect) {
  20656. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  20657. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  20658. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  20659. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  20660. };
  20661. }
  20662. return OculusDistortionCorrectionPostProcess;
  20663. })(BABYLON.PostProcess);
  20664. BABYLON.OculusDistortionCorrectionPostProcess = OculusDistortionCorrectionPostProcess;
  20665. })(BABYLON || (BABYLON = {}));
  20666. //# sourceMappingURL=babylon.oculusDistortionCorrectionPostProcess.js.map// Mainly based on these 2 articles :
  20667. // 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
  20668. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  20669. var BABYLON;
  20670. (function (BABYLON) {
  20671. (function (JoystickAxis) {
  20672. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  20673. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  20674. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  20675. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  20676. var JoystickAxis = BABYLON.JoystickAxis;
  20677. var VirtualJoystick = (function () {
  20678. function VirtualJoystick(leftJoystick) {
  20679. var _this = this;
  20680. if (leftJoystick) {
  20681. this._leftJoystick = true;
  20682. }
  20683. else {
  20684. this._leftJoystick = false;
  20685. }
  20686. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  20687. VirtualJoystick._globalJoystickIndex++;
  20688. // By default left & right arrow keys are moving the X
  20689. // and up & down keys are moving the Y
  20690. this._axisTargetedByLeftAndRight = 0 /* X */;
  20691. this._axisTargetedByUpAndDown = 1 /* Y */;
  20692. this.reverseLeftRight = false;
  20693. this.reverseUpDown = false;
  20694. // collections of pointers
  20695. this._touches = new BABYLON.VirtualJoystick.Collection();
  20696. this.deltaPosition = BABYLON.Vector3.Zero();
  20697. this._joystickSensibility = 25;
  20698. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  20699. this._rotationSpeed = 25;
  20700. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  20701. this._rotateOnAxisRelativeToMesh = false;
  20702. // injecting a canvas element on top of the canvas 3D game
  20703. if (!VirtualJoystick.vjCanvas) {
  20704. window.addEventListener("resize", function () {
  20705. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  20706. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  20707. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  20708. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  20709. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  20710. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  20711. }, false);
  20712. VirtualJoystick.vjCanvas = document.createElement("canvas");
  20713. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  20714. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  20715. VirtualJoystick.vjCanvas.width = window.innerWidth;
  20716. VirtualJoystick.vjCanvas.height = window.innerHeight;
  20717. VirtualJoystick.vjCanvas.style.width = "100%";
  20718. VirtualJoystick.vjCanvas.style.height = "100%";
  20719. VirtualJoystick.vjCanvas.style.position = "absolute";
  20720. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  20721. VirtualJoystick.vjCanvas.style.top = "0px";
  20722. VirtualJoystick.vjCanvas.style.left = "0px";
  20723. VirtualJoystick.vjCanvas.style.zIndex = "5";
  20724. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  20725. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  20726. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  20727. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  20728. document.body.appendChild(VirtualJoystick.vjCanvas);
  20729. }
  20730. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  20731. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  20732. this.pressed = false;
  20733. // default joystick color
  20734. this._joystickColor = "cyan";
  20735. this._joystickPointerID = -1;
  20736. // current joystick position
  20737. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  20738. // origin joystick position
  20739. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  20740. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  20741. VirtualJoystick.vjCanvas.addEventListener('pointerdown', function (evt) {
  20742. _this._onPointerDown(evt);
  20743. }, false);
  20744. VirtualJoystick.vjCanvas.addEventListener('pointermove', function (evt) {
  20745. _this._onPointerMove(evt);
  20746. }, false);
  20747. VirtualJoystick.vjCanvas.addEventListener('pointerup', function (evt) {
  20748. _this._onPointerUp(evt);
  20749. }, false);
  20750. VirtualJoystick.vjCanvas.addEventListener('pointerout', function (evt) {
  20751. _this._onPointerUp(evt);
  20752. }, false);
  20753. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  20754. evt.preventDefault(); // Disables system menu
  20755. }, false);
  20756. requestAnimationFrame(function () {
  20757. _this._drawVirtualJoystick();
  20758. });
  20759. }
  20760. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  20761. this._joystickSensibility = newJoystickSensibility;
  20762. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  20763. };
  20764. VirtualJoystick.prototype._onPointerDown = function (e) {
  20765. var positionOnScreenCondition;
  20766. e.preventDefault();
  20767. if (this._leftJoystick === true) {
  20768. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  20769. }
  20770. else {
  20771. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  20772. }
  20773. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  20774. // First contact will be dedicated to the virtual joystick
  20775. this._joystickPointerID = e.pointerId;
  20776. this._joystickPointerStartPos.x = e.clientX;
  20777. this._joystickPointerStartPos.y = e.clientY;
  20778. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  20779. this._deltaJoystickVector.x = 0;
  20780. this._deltaJoystickVector.y = 0;
  20781. this.pressed = true;
  20782. this._touches.add(e.pointerId.toString(), e);
  20783. }
  20784. else {
  20785. // You can only trigger the action buttons with a joystick declared
  20786. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  20787. this._action();
  20788. this._touches.add(e.pointerId.toString(), e);
  20789. }
  20790. }
  20791. };
  20792. VirtualJoystick.prototype._onPointerMove = function (e) {
  20793. // If the current pointer is the one associated to the joystick (first touch contact)
  20794. if (this._joystickPointerID == e.pointerId) {
  20795. this._joystickPointerPos.x = e.clientX;
  20796. this._joystickPointerPos.y = e.clientY;
  20797. this._deltaJoystickVector = this._joystickPointerPos.clone();
  20798. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  20799. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  20800. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  20801. switch (this._axisTargetedByLeftAndRight) {
  20802. case 0 /* X */:
  20803. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  20804. break;
  20805. case 1 /* Y */:
  20806. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  20807. break;
  20808. case 2 /* Z */:
  20809. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  20810. break;
  20811. }
  20812. var directionUpDown = this.reverseUpDown ? 1 : -1;
  20813. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  20814. switch (this._axisTargetedByUpAndDown) {
  20815. case 0 /* X */:
  20816. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  20817. break;
  20818. case 1 /* Y */:
  20819. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  20820. break;
  20821. case 2 /* Z */:
  20822. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  20823. break;
  20824. }
  20825. }
  20826. else {
  20827. if (this._touches.item(e.pointerId.toString())) {
  20828. this._touches.item(e.pointerId.toString()).x = e.clientX;
  20829. this._touches.item(e.pointerId.toString()).y = e.clientY;
  20830. }
  20831. }
  20832. };
  20833. VirtualJoystick.prototype._onPointerUp = function (e) {
  20834. this._clearCanvas();
  20835. if (this._joystickPointerID == e.pointerId) {
  20836. this._joystickPointerID = -1;
  20837. this.pressed = false;
  20838. }
  20839. this._deltaJoystickVector.x = 0;
  20840. this._deltaJoystickVector.y = 0;
  20841. this._touches.remove(e.pointerId.toString());
  20842. };
  20843. /**
  20844. * Change the color of the virtual joystick
  20845. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  20846. */
  20847. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  20848. this._joystickColor = newColor;
  20849. };
  20850. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  20851. this._action = action;
  20852. };
  20853. // Define which axis you'd like to control for left & right
  20854. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  20855. switch (axis) {
  20856. case 0 /* X */:
  20857. case 1 /* Y */:
  20858. case 2 /* Z */:
  20859. this._axisTargetedByLeftAndRight = axis;
  20860. break;
  20861. default:
  20862. this._axisTargetedByLeftAndRight = 0 /* X */;
  20863. break;
  20864. }
  20865. };
  20866. // Define which axis you'd like to control for up & down
  20867. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  20868. switch (axis) {
  20869. case 0 /* X */:
  20870. case 1 /* Y */:
  20871. case 2 /* Z */:
  20872. this._axisTargetedByUpAndDown = axis;
  20873. break;
  20874. default:
  20875. this._axisTargetedByUpAndDown = 1 /* Y */;
  20876. break;
  20877. }
  20878. };
  20879. VirtualJoystick.prototype._clearCanvas = function () {
  20880. if (this._leftJoystick) {
  20881. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  20882. }
  20883. else {
  20884. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  20885. }
  20886. };
  20887. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  20888. var _this = this;
  20889. if (this.pressed) {
  20890. this._clearCanvas();
  20891. this._touches.forEach(function (touch) {
  20892. if (touch.pointerId === _this._joystickPointerID) {
  20893. VirtualJoystick.vjCanvasContext.beginPath();
  20894. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  20895. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  20896. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  20897. VirtualJoystick.vjCanvasContext.stroke();
  20898. VirtualJoystick.vjCanvasContext.beginPath();
  20899. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  20900. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  20901. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  20902. VirtualJoystick.vjCanvasContext.stroke();
  20903. VirtualJoystick.vjCanvasContext.beginPath();
  20904. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  20905. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  20906. VirtualJoystick.vjCanvasContext.stroke();
  20907. }
  20908. else {
  20909. VirtualJoystick.vjCanvasContext.beginPath();
  20910. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  20911. VirtualJoystick.vjCanvasContext.beginPath();
  20912. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  20913. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  20914. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  20915. VirtualJoystick.vjCanvasContext.stroke();
  20916. }
  20917. ;
  20918. });
  20919. }
  20920. requestAnimationFrame(function () {
  20921. _this._drawVirtualJoystick();
  20922. });
  20923. };
  20924. VirtualJoystick.prototype.releaseCanvas = function () {
  20925. if (VirtualJoystick.vjCanvas) {
  20926. document.body.removeChild(VirtualJoystick.vjCanvas);
  20927. VirtualJoystick.vjCanvas = null;
  20928. }
  20929. };
  20930. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  20931. VirtualJoystick._globalJoystickIndex = 0;
  20932. return VirtualJoystick;
  20933. })();
  20934. BABYLON.VirtualJoystick = VirtualJoystick;
  20935. })(BABYLON || (BABYLON = {}));
  20936. var BABYLON;
  20937. (function (BABYLON) {
  20938. var VirtualJoystick;
  20939. (function (VirtualJoystick) {
  20940. var Collection = (function () {
  20941. function Collection() {
  20942. this._count = 0;
  20943. this._collection = new Array();
  20944. }
  20945. Collection.prototype.Count = function () {
  20946. return this._count;
  20947. };
  20948. Collection.prototype.add = function (key, item) {
  20949. if (this._collection[key] != undefined) {
  20950. return undefined;
  20951. }
  20952. this._collection[key] = item;
  20953. return ++this._count;
  20954. };
  20955. Collection.prototype.remove = function (key) {
  20956. if (this._collection[key] == undefined) {
  20957. return undefined;
  20958. }
  20959. delete this._collection[key];
  20960. return --this._count;
  20961. };
  20962. Collection.prototype.item = function (key) {
  20963. return this._collection[key];
  20964. };
  20965. Collection.prototype.forEach = function (block) {
  20966. var key;
  20967. for (key in this._collection) {
  20968. if (this._collection.hasOwnProperty(key)) {
  20969. block(this._collection[key]);
  20970. }
  20971. }
  20972. };
  20973. return Collection;
  20974. })();
  20975. VirtualJoystick.Collection = Collection;
  20976. })(VirtualJoystick = BABYLON.VirtualJoystick || (BABYLON.VirtualJoystick = {}));
  20977. })(BABYLON || (BABYLON = {}));
  20978. //# sourceMappingURL=babylon.virtualJoystick.js.map
  20979. var BABYLON;
  20980. (function (BABYLON) {
  20981. var OculusRiftDevKit2013_Metric = {
  20982. HResolution: 1280,
  20983. VResolution: 800,
  20984. HScreenSize: 0.149759993,
  20985. VScreenSize: 0.0935999975,
  20986. VScreenCenter: 0.0467999987,
  20987. EyeToScreenDistance: 0.0410000011,
  20988. LensSeparationDistance: 0.0635000020,
  20989. InterpupillaryDistance: 0.0640000030,
  20990. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  20991. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  20992. PostProcessScaleFactor: 1.714605507808412,
  20993. LensCenterOffset: 0.151976421
  20994. };
  20995. var _OculusInnerCamera = (function (_super) {
  20996. __extends(_OculusInnerCamera, _super);
  20997. function _OculusInnerCamera(name, position, scene, isLeftEye) {
  20998. _super.call(this, name, position, scene);
  20999. this._workMatrix = new BABYLON.Matrix();
  21000. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  21001. // Constants
  21002. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  21003. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  21004. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  21005. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  21006. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  21007. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  21008. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  21009. // Postprocess
  21010. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  21011. }
  21012. _OculusInnerCamera.prototype.getProjectionMatrix = function () {
  21013. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  21014. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  21015. return this._projectionMatrix;
  21016. };
  21017. _OculusInnerCamera.prototype._getViewMatrix = function () {
  21018. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  21019. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  21020. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  21021. // Computing target and final matrix
  21022. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  21023. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  21024. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  21025. return this._viewMatrix;
  21026. };
  21027. return _OculusInnerCamera;
  21028. })(BABYLON.FreeCamera);
  21029. var OculusCamera = (function (_super) {
  21030. __extends(OculusCamera, _super);
  21031. function OculusCamera(name, position, scene) {
  21032. _super.call(this, name, position, scene);
  21033. this._leftCamera = new _OculusInnerCamera(name + "_left", position.clone(), scene, true);
  21034. this._rightCamera = new _OculusInnerCamera(name + "_right", position.clone(), scene, false);
  21035. this.subCameras.push(this._leftCamera);
  21036. this.subCameras.push(this._rightCamera);
  21037. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  21038. }
  21039. OculusCamera.prototype._update = function () {
  21040. this._leftCamera.position.copyFrom(this.position);
  21041. this._rightCamera.position.copyFrom(this.position);
  21042. this._updateCamera(this._leftCamera);
  21043. this._updateCamera(this._rightCamera);
  21044. _super.prototype._update.call(this);
  21045. };
  21046. OculusCamera.prototype._updateCamera = function (camera) {
  21047. camera.minZ = this.minZ;
  21048. camera.maxZ = this.maxZ;
  21049. camera.rotation.x = this.rotation.x;
  21050. camera.rotation.y = this.rotation.y;
  21051. camera.rotation.z = this.rotation.z;
  21052. };
  21053. // Oculus events
  21054. OculusCamera.prototype._onOrientationEvent = function (evt) {
  21055. var yaw = evt.alpha / 180 * Math.PI;
  21056. var pitch = evt.beta / 180 * Math.PI;
  21057. var roll = evt.gamma / 180 * Math.PI;
  21058. if (!this._offsetOrientation) {
  21059. this._offsetOrientation = {
  21060. yaw: yaw,
  21061. pitch: pitch,
  21062. roll: roll
  21063. };
  21064. return;
  21065. }
  21066. else {
  21067. this.rotation.y += yaw - this._offsetOrientation.yaw;
  21068. this.rotation.x += pitch - this._offsetOrientation.pitch;
  21069. this.rotation.z += this._offsetOrientation.roll - roll;
  21070. this._offsetOrientation.yaw = yaw;
  21071. this._offsetOrientation.pitch = pitch;
  21072. this._offsetOrientation.roll = roll;
  21073. }
  21074. };
  21075. OculusCamera.prototype.attachControl = function (element, noPreventDefault) {
  21076. _super.prototype.attachControl.call(this, element, noPreventDefault);
  21077. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  21078. };
  21079. OculusCamera.prototype.detachControl = function (element) {
  21080. _super.prototype.detachControl.call(this, element);
  21081. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  21082. };
  21083. return OculusCamera;
  21084. })(BABYLON.FreeCamera);
  21085. BABYLON.OculusCamera = OculusCamera;
  21086. })(BABYLON || (BABYLON = {}));
  21087. //# sourceMappingURL=babylon.oculusCamera.js.map
  21088. var BABYLON;
  21089. (function (BABYLON) {
  21090. var OculusRiftDevKit2013_Metric = {
  21091. HResolution: 1280,
  21092. VResolution: 800,
  21093. HScreenSize: 0.149759993,
  21094. VScreenSize: 0.0935999975,
  21095. VScreenCenter: 0.0467999987,
  21096. EyeToScreenDistance: 0.0410000011,
  21097. LensSeparationDistance: 0.0635000020,
  21098. InterpupillaryDistance: 0.0640000030,
  21099. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  21100. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  21101. PostProcessScaleFactor: 1.714605507808412,
  21102. LensCenterOffset: 0.151976421
  21103. };
  21104. var _OculusInnerGamepadCamera = (function (_super) {
  21105. __extends(_OculusInnerGamepadCamera, _super);
  21106. function _OculusInnerGamepadCamera(name, position, scene, isLeftEye) {
  21107. _super.call(this, name, position, scene);
  21108. this._workMatrix = new BABYLON.Matrix();
  21109. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  21110. // Constants
  21111. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  21112. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  21113. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  21114. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  21115. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  21116. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  21117. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  21118. // Postprocess
  21119. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  21120. }
  21121. _OculusInnerGamepadCamera.prototype.getProjectionMatrix = function () {
  21122. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  21123. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  21124. return this._projectionMatrix;
  21125. };
  21126. _OculusInnerGamepadCamera.prototype._getViewMatrix = function () {
  21127. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  21128. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  21129. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  21130. // Computing target and final matrix
  21131. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  21132. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  21133. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  21134. return this._viewMatrix;
  21135. };
  21136. return _OculusInnerGamepadCamera;
  21137. })(BABYLON.FreeCamera);
  21138. var OculusGamepadCamera = (function (_super) {
  21139. __extends(OculusGamepadCamera, _super);
  21140. function OculusGamepadCamera(name, position, scene) {
  21141. var _this = this;
  21142. _super.call(this, name, position, scene);
  21143. this.angularSensibility = 200;
  21144. this.moveSensibility = 75;
  21145. this._leftCamera = new _OculusInnerGamepadCamera(name + "_left", position.clone(), scene, true);
  21146. this._rightCamera = new _OculusInnerGamepadCamera(name + "_right", position.clone(), scene, false);
  21147. this.subCameras.push(this._leftCamera);
  21148. this.subCameras.push(this._rightCamera);
  21149. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  21150. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  21151. _this._onNewGameConnected(gamepad);
  21152. });
  21153. }
  21154. OculusGamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  21155. // Only the first gamepad can control the camera
  21156. if (gamepad.index === 0) {
  21157. this._gamepad = gamepad;
  21158. }
  21159. };
  21160. OculusGamepadCamera.prototype._update = function () {
  21161. this._leftCamera.position.copyFrom(this.position);
  21162. this._rightCamera.position.copyFrom(this.position);
  21163. this._updateCamera(this._leftCamera);
  21164. this._updateCamera(this._rightCamera);
  21165. _super.prototype._update.call(this);
  21166. };
  21167. OculusGamepadCamera.prototype._checkInputs = function () {
  21168. if (!this._gamepad) {
  21169. return;
  21170. }
  21171. var LSValues = this._gamepad.leftStick;
  21172. var normalizedLX = LSValues.x / this.moveSensibility;
  21173. var normalizedLY = LSValues.y / this.moveSensibility;
  21174. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  21175. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  21176. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  21177. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x, 0, -LSValues.y), cameraTransform);
  21178. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  21179. };
  21180. OculusGamepadCamera.prototype._updateCamera = function (camera) {
  21181. camera.minZ = this.minZ;
  21182. camera.maxZ = this.maxZ;
  21183. camera.rotation.x = this.rotation.x;
  21184. camera.rotation.y = this.rotation.y;
  21185. camera.rotation.z = this.rotation.z;
  21186. };
  21187. // Oculus events
  21188. OculusGamepadCamera.prototype._onOrientationEvent = function (evt) {
  21189. var yaw = evt.alpha / 180 * Math.PI;
  21190. var pitch = evt.beta / 180 * Math.PI;
  21191. var roll = evt.gamma / 180 * Math.PI;
  21192. if (!this._offsetOrientation) {
  21193. this._offsetOrientation = {
  21194. yaw: yaw,
  21195. pitch: pitch,
  21196. roll: roll
  21197. };
  21198. return;
  21199. }
  21200. else {
  21201. this.rotation.y += yaw - this._offsetOrientation.yaw;
  21202. this.rotation.x += pitch - this._offsetOrientation.pitch;
  21203. this.rotation.z += this._offsetOrientation.roll - roll;
  21204. this._offsetOrientation.yaw = yaw;
  21205. this._offsetOrientation.pitch = pitch;
  21206. this._offsetOrientation.roll = roll;
  21207. }
  21208. };
  21209. OculusGamepadCamera.prototype.attachControl = function (element, noPreventDefault) {
  21210. _super.prototype.attachControl.call(this, element, noPreventDefault);
  21211. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  21212. };
  21213. OculusGamepadCamera.prototype.detachControl = function (element) {
  21214. _super.prototype.detachControl.call(this, element);
  21215. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  21216. };
  21217. OculusGamepadCamera.prototype.dispose = function () {
  21218. this._gamepads.dispose();
  21219. _super.prototype.dispose.call(this);
  21220. };
  21221. return OculusGamepadCamera;
  21222. })(BABYLON.FreeCamera);
  21223. BABYLON.OculusGamepadCamera = OculusGamepadCamera;
  21224. })(BABYLON || (BABYLON = {}));
  21225. //# sourceMappingURL=babylon.oculusGamepadCamera.js.map
  21226. var BABYLON;
  21227. (function (BABYLON) {
  21228. // We're mainly based on the logic defined into the FreeCamera code
  21229. var VirtualJoysticksCamera = (function (_super) {
  21230. __extends(VirtualJoysticksCamera, _super);
  21231. function VirtualJoysticksCamera(name, position, scene) {
  21232. _super.call(this, name, position, scene);
  21233. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  21234. this._leftjoystick.setAxisForUpDown(2 /* Z */);
  21235. this._leftjoystick.setAxisForLeftRight(0 /* X */);
  21236. this._leftjoystick.setJoystickSensibility(0.15);
  21237. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  21238. this._rightjoystick.setAxisForUpDown(0 /* X */);
  21239. this._rightjoystick.setAxisForLeftRight(1 /* Y */);
  21240. this._rightjoystick.reverseUpDown = true;
  21241. this._rightjoystick.setJoystickSensibility(0.05);
  21242. this._rightjoystick.setJoystickColor("yellow");
  21243. }
  21244. VirtualJoysticksCamera.prototype._checkInputs = function () {
  21245. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  21246. var deltaTransform = BABYLON.Vector3.TransformCoordinates(this._leftjoystick.deltaPosition, cameraTransform);
  21247. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  21248. this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  21249. if (!this._leftjoystick.pressed) {
  21250. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  21251. }
  21252. if (!this._rightjoystick.pressed) {
  21253. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  21254. }
  21255. };
  21256. VirtualJoysticksCamera.prototype.dispose = function () {
  21257. this._leftjoystick.releaseCanvas();
  21258. _super.prototype.dispose.call(this);
  21259. };
  21260. return VirtualJoysticksCamera;
  21261. })(BABYLON.FreeCamera);
  21262. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  21263. })(BABYLON || (BABYLON = {}));
  21264. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  21265. var BABYLON;
  21266. (function (BABYLON) {
  21267. var ShaderMaterial = (function (_super) {
  21268. __extends(ShaderMaterial, _super);
  21269. function ShaderMaterial(name, scene, shaderPath, options) {
  21270. _super.call(this, name, scene);
  21271. this._textures = new Array();
  21272. this._floats = new Array();
  21273. this._floatsArrays = {};
  21274. this._colors3 = new Array();
  21275. this._colors4 = new Array();
  21276. this._vectors2 = new Array();
  21277. this._vectors3 = new Array();
  21278. this._matrices = new Array();
  21279. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  21280. this._shaderPath = shaderPath;
  21281. options.needAlphaBlending = options.needAlphaBlending || false;
  21282. options.needAlphaTesting = options.needAlphaTesting || false;
  21283. options.attributes = options.attributes || ["position", "normal", "uv"];
  21284. options.uniforms = options.uniforms || ["worldViewProjection"];
  21285. options.samplers = options.samplers || [];
  21286. this._options = options;
  21287. }
  21288. ShaderMaterial.prototype.needAlphaBlending = function () {
  21289. return this._options.needAlphaBlending;
  21290. };
  21291. ShaderMaterial.prototype.needAlphaTesting = function () {
  21292. return this._options.needAlphaTesting;
  21293. };
  21294. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  21295. if (this._options.uniforms.indexOf(uniformName) === -1) {
  21296. this._options.uniforms.push(uniformName);
  21297. }
  21298. };
  21299. ShaderMaterial.prototype.setTexture = function (name, texture) {
  21300. if (this._options.samplers.indexOf(name) === -1) {
  21301. this._options.samplers.push(name);
  21302. }
  21303. this._textures[name] = texture;
  21304. return this;
  21305. };
  21306. ShaderMaterial.prototype.setFloat = function (name, value) {
  21307. this._checkUniform(name);
  21308. this._floats[name] = value;
  21309. return this;
  21310. };
  21311. ShaderMaterial.prototype.setFloats = function (name, value) {
  21312. this._checkUniform(name);
  21313. this._floatsArrays[name] = value;
  21314. return this;
  21315. };
  21316. ShaderMaterial.prototype.setColor3 = function (name, value) {
  21317. this._checkUniform(name);
  21318. this._colors3[name] = value;
  21319. return this;
  21320. };
  21321. ShaderMaterial.prototype.setColor4 = function (name, value) {
  21322. this._checkUniform(name);
  21323. this._colors4[name] = value;
  21324. return this;
  21325. };
  21326. ShaderMaterial.prototype.setVector2 = function (name, value) {
  21327. this._checkUniform(name);
  21328. this._vectors2[name] = value;
  21329. return this;
  21330. };
  21331. ShaderMaterial.prototype.setVector3 = function (name, value) {
  21332. this._checkUniform(name);
  21333. this._vectors3[name] = value;
  21334. return this;
  21335. };
  21336. ShaderMaterial.prototype.setMatrix = function (name, value) {
  21337. this._checkUniform(name);
  21338. this._matrices[name] = value;
  21339. return this;
  21340. };
  21341. ShaderMaterial.prototype.isReady = function () {
  21342. var scene = this.getScene();
  21343. var engine = scene.getEngine();
  21344. if (!this.checkReadyOnEveryCall) {
  21345. if (this._renderId === scene.getRenderId()) {
  21346. return true;
  21347. }
  21348. }
  21349. var previousEffect = this._effect;
  21350. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, "", null, this.onCompiled, this.onError);
  21351. if (!this._effect.isReady()) {
  21352. return false;
  21353. }
  21354. if (previousEffect !== this._effect) {
  21355. scene.resetCachedMaterial();
  21356. }
  21357. this._renderId = scene.getRenderId();
  21358. return true;
  21359. };
  21360. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  21361. var scene = this.getScene();
  21362. if (this._options.uniforms.indexOf("world") !== -1) {
  21363. this._effect.setMatrix("world", world);
  21364. }
  21365. if (this._options.uniforms.indexOf("worldView") !== -1) {
  21366. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  21367. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  21368. }
  21369. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  21370. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  21371. }
  21372. };
  21373. ShaderMaterial.prototype.bind = function (world) {
  21374. // Std values
  21375. this.bindOnlyWorldMatrix(world);
  21376. if (this.getScene().getCachedMaterial() !== this) {
  21377. if (this._options.uniforms.indexOf("view") !== -1) {
  21378. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  21379. }
  21380. if (this._options.uniforms.indexOf("projection") !== -1) {
  21381. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  21382. }
  21383. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  21384. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  21385. }
  21386. for (var name in this._textures) {
  21387. this._effect.setTexture(name, this._textures[name]);
  21388. }
  21389. for (name in this._floats) {
  21390. this._effect.setFloat(name, this._floats[name]);
  21391. }
  21392. for (name in this._floatsArrays) {
  21393. this._effect.setArray(name, this._floatsArrays[name]);
  21394. }
  21395. for (name in this._colors3) {
  21396. this._effect.setColor3(name, this._colors3[name]);
  21397. }
  21398. for (name in this._colors4) {
  21399. var color = this._colors4[name];
  21400. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  21401. }
  21402. for (name in this._vectors2) {
  21403. this._effect.setVector2(name, this._vectors2[name]);
  21404. }
  21405. for (name in this._vectors3) {
  21406. this._effect.setVector3(name, this._vectors3[name]);
  21407. }
  21408. for (name in this._matrices) {
  21409. this._effect.setMatrix(name, this._matrices[name]);
  21410. }
  21411. }
  21412. _super.prototype.bind.call(this, world, null);
  21413. };
  21414. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  21415. for (var name in this._textures) {
  21416. this._textures[name].dispose();
  21417. }
  21418. this._textures = [];
  21419. _super.prototype.dispose.call(this, forceDisposeEffect);
  21420. };
  21421. return ShaderMaterial;
  21422. })(BABYLON.Material);
  21423. BABYLON.ShaderMaterial = ShaderMaterial;
  21424. })(BABYLON || (BABYLON = {}));
  21425. //# sourceMappingURL=babylon.shaderMaterial.js.mapvar BABYLON;
  21426. (function (BABYLON) {
  21427. var VertexData = (function () {
  21428. function VertexData() {
  21429. }
  21430. VertexData.prototype.set = function (data, kind) {
  21431. switch (kind) {
  21432. case BABYLON.VertexBuffer.PositionKind:
  21433. this.positions = data;
  21434. break;
  21435. case BABYLON.VertexBuffer.NormalKind:
  21436. this.normals = data;
  21437. break;
  21438. case BABYLON.VertexBuffer.UVKind:
  21439. this.uvs = data;
  21440. break;
  21441. case BABYLON.VertexBuffer.UV2Kind:
  21442. this.uv2s = data;
  21443. break;
  21444. case BABYLON.VertexBuffer.ColorKind:
  21445. this.colors = data;
  21446. break;
  21447. case BABYLON.VertexBuffer.MatricesIndicesKind:
  21448. this.matricesIndices = data;
  21449. break;
  21450. case BABYLON.VertexBuffer.MatricesWeightsKind:
  21451. this.matricesWeights = data;
  21452. break;
  21453. }
  21454. };
  21455. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  21456. this._applyTo(mesh, updatable);
  21457. };
  21458. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  21459. this._applyTo(geometry, updatable);
  21460. };
  21461. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  21462. this._update(mesh);
  21463. };
  21464. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  21465. this._update(geometry);
  21466. };
  21467. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  21468. if (this.positions) {
  21469. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  21470. }
  21471. if (this.normals) {
  21472. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  21473. }
  21474. if (this.uvs) {
  21475. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  21476. }
  21477. if (this.uv2s) {
  21478. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updatable);
  21479. }
  21480. if (this.colors) {
  21481. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  21482. }
  21483. if (this.matricesIndices) {
  21484. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  21485. }
  21486. if (this.matricesWeights) {
  21487. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  21488. }
  21489. if (this.indices) {
  21490. meshOrGeometry.setIndices(this.indices);
  21491. }
  21492. };
  21493. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  21494. if (this.positions) {
  21495. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  21496. }
  21497. if (this.normals) {
  21498. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  21499. }
  21500. if (this.uvs) {
  21501. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  21502. }
  21503. if (this.uv2s) {
  21504. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updateExtends, makeItUnique);
  21505. }
  21506. if (this.colors) {
  21507. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  21508. }
  21509. if (this.matricesIndices) {
  21510. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  21511. }
  21512. if (this.matricesWeights) {
  21513. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  21514. }
  21515. if (this.indices) {
  21516. meshOrGeometry.setIndices(this.indices);
  21517. }
  21518. };
  21519. VertexData.prototype.transform = function (matrix) {
  21520. var transformed = BABYLON.Vector3.Zero();
  21521. if (this.positions) {
  21522. var position = BABYLON.Vector3.Zero();
  21523. for (var index = 0; index < this.positions.length; index += 3) {
  21524. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  21525. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  21526. this.positions[index] = transformed.x;
  21527. this.positions[index + 1] = transformed.y;
  21528. this.positions[index + 2] = transformed.z;
  21529. }
  21530. }
  21531. if (this.normals) {
  21532. var normal = BABYLON.Vector3.Zero();
  21533. for (index = 0; index < this.normals.length; index += 3) {
  21534. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  21535. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  21536. this.normals[index] = transformed.x;
  21537. this.normals[index + 1] = transformed.y;
  21538. this.normals[index + 2] = transformed.z;
  21539. }
  21540. }
  21541. };
  21542. VertexData.prototype.merge = function (other) {
  21543. if (other.indices) {
  21544. if (!this.indices) {
  21545. this.indices = [];
  21546. }
  21547. var offset = this.positions ? this.positions.length / 3 : 0;
  21548. for (var index = 0; index < other.indices.length; index++) {
  21549. this.indices.push(other.indices[index] + offset);
  21550. }
  21551. }
  21552. if (other.positions) {
  21553. if (!this.positions) {
  21554. this.positions = [];
  21555. }
  21556. for (index = 0; index < other.positions.length; index++) {
  21557. this.positions.push(other.positions[index]);
  21558. }
  21559. }
  21560. if (other.normals) {
  21561. if (!this.normals) {
  21562. this.normals = [];
  21563. }
  21564. for (index = 0; index < other.normals.length; index++) {
  21565. this.normals.push(other.normals[index]);
  21566. }
  21567. }
  21568. if (other.uvs) {
  21569. if (!this.uvs) {
  21570. this.uvs = [];
  21571. }
  21572. for (index = 0; index < other.uvs.length; index++) {
  21573. this.uvs.push(other.uvs[index]);
  21574. }
  21575. }
  21576. if (other.uv2s) {
  21577. if (!this.uv2s) {
  21578. this.uv2s = [];
  21579. }
  21580. for (index = 0; index < other.uv2s.length; index++) {
  21581. this.uv2s.push(other.uv2s[index]);
  21582. }
  21583. }
  21584. if (other.matricesIndices) {
  21585. if (!this.matricesIndices) {
  21586. this.matricesIndices = [];
  21587. }
  21588. for (index = 0; index < other.matricesIndices.length; index++) {
  21589. this.matricesIndices.push(other.matricesIndices[index]);
  21590. }
  21591. }
  21592. if (other.matricesWeights) {
  21593. if (!this.matricesWeights) {
  21594. this.matricesWeights = [];
  21595. }
  21596. for (index = 0; index < other.matricesWeights.length; index++) {
  21597. this.matricesWeights.push(other.matricesWeights[index]);
  21598. }
  21599. }
  21600. if (other.colors) {
  21601. if (!this.colors) {
  21602. this.colors = [];
  21603. }
  21604. for (index = 0; index < other.colors.length; index++) {
  21605. this.colors.push(other.colors[index]);
  21606. }
  21607. }
  21608. };
  21609. // Statics
  21610. VertexData.ExtractFromMesh = function (mesh) {
  21611. return VertexData._ExtractFrom(mesh);
  21612. };
  21613. VertexData.ExtractFromGeometry = function (geometry) {
  21614. return VertexData._ExtractFrom(geometry);
  21615. };
  21616. VertexData._ExtractFrom = function (meshOrGeometry) {
  21617. var result = new VertexData();
  21618. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  21619. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21620. }
  21621. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21622. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21623. }
  21624. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  21625. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind);
  21626. }
  21627. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  21628. result.uv2s = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  21629. }
  21630. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  21631. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  21632. }
  21633. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  21634. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  21635. }
  21636. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  21637. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  21638. }
  21639. result.indices = meshOrGeometry.getIndices();
  21640. return result;
  21641. };
  21642. VertexData.CreateRibbon = function (pathArray, closeArray, closePath, offset, sideOrientation) {
  21643. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  21644. closeArray = closeArray || false;
  21645. closePath = closePath || false;
  21646. var defaultOffset = Math.floor(pathArray[0].length / 2);
  21647. offset = offset || defaultOffset;
  21648. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  21649. var positions = [];
  21650. var indices = [];
  21651. var normals = [];
  21652. var uvs = [];
  21653. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  21654. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  21655. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  21656. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  21657. var minlg; // minimal length among all paths from pathArray
  21658. var lg = []; // array of path lengths : nb of vertex per path
  21659. var idx = []; // array of path indexes : index of each path (first vertex) in positions array
  21660. var p; // path iterator
  21661. var i; // point iterator
  21662. var j; // point iterator
  21663. // if single path in pathArray
  21664. if (pathArray.length < 2) {
  21665. var ar1 = [];
  21666. var ar2 = [];
  21667. for (i = 0; i < pathArray[0].length - offset; i++) {
  21668. ar1.push(pathArray[0][i]);
  21669. ar2.push(pathArray[0][i + offset]);
  21670. }
  21671. pathArray = [ar1, ar2];
  21672. }
  21673. // positions and horizontal distances (u)
  21674. var idc = 0;
  21675. minlg = pathArray[0].length;
  21676. for (p = 0; p < pathArray.length; p++) {
  21677. uTotalDistance[p] = 0;
  21678. us[p] = [0];
  21679. var path = pathArray[p];
  21680. var l = path.length;
  21681. minlg = (minlg < l) ? minlg : l;
  21682. lg[p] = l;
  21683. idx[p] = idc;
  21684. j = 0;
  21685. while (j < l) {
  21686. positions.push(path[j].x, path[j].y, path[j].z);
  21687. if (j > 0) {
  21688. var vectlg = path[j].subtract(path[j - 1]).length();
  21689. var dist = vectlg + uTotalDistance[p];
  21690. us[p].push(dist);
  21691. uTotalDistance[p] = dist;
  21692. }
  21693. j++;
  21694. }
  21695. if (closePath) {
  21696. vectlg = path[0].subtract(path[j - 1]).length();
  21697. dist = vectlg + uTotalDistance[p];
  21698. uTotalDistance[p] = dist;
  21699. }
  21700. idc += l;
  21701. }
  21702. for (i = 0; i < minlg; i++) {
  21703. vTotalDistance[i] = 0;
  21704. vs[i] = [0];
  21705. var path1;
  21706. var path2;
  21707. for (p = 0; p < pathArray.length - 1; p++) {
  21708. path1 = pathArray[p];
  21709. path2 = pathArray[p + 1];
  21710. vectlg = path2[i].subtract(path1[i]).length();
  21711. dist = vectlg + vTotalDistance[i];
  21712. vs[i].push(dist);
  21713. vTotalDistance[i] = dist;
  21714. }
  21715. if (closeArray) {
  21716. path1 = pathArray[p];
  21717. path2 = pathArray[0];
  21718. vectlg = path2[i].subtract(path1[i]).length();
  21719. dist = vectlg + vTotalDistance[i];
  21720. vTotalDistance[i] = dist;
  21721. }
  21722. }
  21723. // uvs
  21724. var u;
  21725. var v;
  21726. for (p = 0; p < pathArray.length; p++) {
  21727. for (i = 0; i < minlg; i++) {
  21728. u = us[p][i] / uTotalDistance[p];
  21729. v = vs[i][p] / vTotalDistance[i];
  21730. uvs.push(u, v);
  21731. }
  21732. }
  21733. // indices
  21734. p = 0; // path index
  21735. var pi = 0; // positions array index
  21736. var l1 = lg[p] - 1; // path1 length
  21737. var l2 = lg[p + 1] - 1; // path2 length
  21738. var min = (l1 < l2) ? l1 : l2; // current path stop index
  21739. var shft = idx[1] - idx[0]; // shift
  21740. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate
  21741. var t1; // two consecutive triangles, so 4 points : point1
  21742. var t2; // point2
  21743. var t3; // point3
  21744. var t4; // point4
  21745. while (pi <= min && p < path1nb) {
  21746. // 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
  21747. t1 = pi;
  21748. t2 = pi + shft;
  21749. t3 = pi + 1;
  21750. t4 = pi + shft + 1;
  21751. indices.push(pi, pi + shft, pi + 1);
  21752. indices.push(pi + shft + 1, pi + 1, pi + shft);
  21753. pi += 1;
  21754. if (pi === min) {
  21755. if (closePath) {
  21756. indices.push(pi, pi + shft, idx[p]);
  21757. indices.push(idx[p] + shft, idx[p], pi + shft);
  21758. t3 = idx[p];
  21759. t4 = idx[p] + shft;
  21760. }
  21761. p++;
  21762. if (p === lg.length - 1) {
  21763. shft = idx[0] - idx[p];
  21764. l1 = lg[p] - 1;
  21765. l2 = lg[0] - 1;
  21766. }
  21767. else {
  21768. shft = idx[p + 1] - idx[p];
  21769. l1 = lg[p] - 1;
  21770. l2 = lg[p + 1] - 1;
  21771. }
  21772. pi = idx[p];
  21773. min = (l1 < l2) ? l1 + pi : l2 + pi;
  21774. }
  21775. }
  21776. // normals
  21777. VertexData.ComputeNormals(positions, indices, normals);
  21778. // sides
  21779. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  21780. // Result
  21781. var vertexData = new VertexData();
  21782. vertexData.indices = indices;
  21783. vertexData.positions = positions;
  21784. vertexData.normals = normals;
  21785. vertexData.uvs = uvs;
  21786. return vertexData;
  21787. };
  21788. VertexData.CreateBox = function (size, sideOrientation) {
  21789. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  21790. var normalsSource = [
  21791. new BABYLON.Vector3(0, 0, 1),
  21792. new BABYLON.Vector3(0, 0, -1),
  21793. new BABYLON.Vector3(1, 0, 0),
  21794. new BABYLON.Vector3(-1, 0, 0),
  21795. new BABYLON.Vector3(0, 1, 0),
  21796. new BABYLON.Vector3(0, -1, 0)
  21797. ];
  21798. var indices = [];
  21799. var positions = [];
  21800. var normals = [];
  21801. var uvs = [];
  21802. size = size || 1;
  21803. for (var index = 0; index < normalsSource.length; index++) {
  21804. var normal = normalsSource[index];
  21805. // Get two vectors perpendicular to the face normal and to each other.
  21806. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  21807. var side2 = BABYLON.Vector3.Cross(normal, side1);
  21808. // Six indices (two triangles) per face.
  21809. var verticesLength = positions.length / 3;
  21810. indices.push(verticesLength);
  21811. indices.push(verticesLength + 1);
  21812. indices.push(verticesLength + 2);
  21813. indices.push(verticesLength);
  21814. indices.push(verticesLength + 2);
  21815. indices.push(verticesLength + 3);
  21816. // Four vertices per face.
  21817. var vertex = normal.subtract(side1).subtract(side2).scale(size / 2);
  21818. positions.push(vertex.x, vertex.y, vertex.z);
  21819. normals.push(normal.x, normal.y, normal.z);
  21820. uvs.push(1.0, 1.0);
  21821. vertex = normal.subtract(side1).add(side2).scale(size / 2);
  21822. positions.push(vertex.x, vertex.y, vertex.z);
  21823. normals.push(normal.x, normal.y, normal.z);
  21824. uvs.push(0.0, 1.0);
  21825. vertex = normal.add(side1).add(side2).scale(size / 2);
  21826. positions.push(vertex.x, vertex.y, vertex.z);
  21827. normals.push(normal.x, normal.y, normal.z);
  21828. uvs.push(0.0, 0.0);
  21829. vertex = normal.add(side1).subtract(side2).scale(size / 2);
  21830. positions.push(vertex.x, vertex.y, vertex.z);
  21831. normals.push(normal.x, normal.y, normal.z);
  21832. uvs.push(1.0, 0.0);
  21833. }
  21834. // sides
  21835. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  21836. // Result
  21837. var vertexData = new VertexData();
  21838. vertexData.indices = indices;
  21839. vertexData.positions = positions;
  21840. vertexData.normals = normals;
  21841. vertexData.uvs = uvs;
  21842. return vertexData;
  21843. };
  21844. VertexData.CreateSphere = function (segments, diameter, sideOrientation) {
  21845. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  21846. segments = segments || 32;
  21847. diameter = diameter || 1;
  21848. var radius = diameter / 2;
  21849. var totalZRotationSteps = 2 + segments;
  21850. var totalYRotationSteps = 2 * totalZRotationSteps;
  21851. var indices = [];
  21852. var positions = [];
  21853. var normals = [];
  21854. var uvs = [];
  21855. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  21856. var normalizedZ = zRotationStep / totalZRotationSteps;
  21857. var angleZ = (normalizedZ * Math.PI);
  21858. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  21859. var normalizedY = yRotationStep / totalYRotationSteps;
  21860. var angleY = normalizedY * Math.PI * 2;
  21861. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  21862. var rotationY = BABYLON.Matrix.RotationY(angleY);
  21863. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  21864. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  21865. var vertex = complete.scale(radius);
  21866. var normal = BABYLON.Vector3.Normalize(vertex);
  21867. positions.push(vertex.x, vertex.y, vertex.z);
  21868. normals.push(normal.x, normal.y, normal.z);
  21869. uvs.push(normalizedZ, normalizedY);
  21870. }
  21871. if (zRotationStep > 0) {
  21872. var verticesCount = positions.length / 3;
  21873. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  21874. indices.push((firstIndex));
  21875. indices.push((firstIndex + 1));
  21876. indices.push(firstIndex + totalYRotationSteps + 1);
  21877. indices.push((firstIndex + totalYRotationSteps + 1));
  21878. indices.push((firstIndex + 1));
  21879. indices.push((firstIndex + totalYRotationSteps + 2));
  21880. }
  21881. }
  21882. }
  21883. // Sides
  21884. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  21885. // Result
  21886. var vertexData = new VertexData();
  21887. vertexData.indices = indices;
  21888. vertexData.positions = positions;
  21889. vertexData.normals = normals;
  21890. vertexData.uvs = uvs;
  21891. return vertexData;
  21892. };
  21893. VertexData.CreateCylinder = function (height, diameterTop, diameterBottom, tessellation, subdivisions, sideOrientation) {
  21894. if (subdivisions === void 0) { subdivisions = 1; }
  21895. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  21896. var radiusTop = diameterTop / 2;
  21897. var radiusBottom = diameterBottom / 2;
  21898. var indices = [];
  21899. var positions = [];
  21900. var normals = [];
  21901. var uvs = [];
  21902. height = height || 1;
  21903. diameterTop = diameterTop || 0.5;
  21904. diameterBottom = diameterBottom || 1;
  21905. tessellation = tessellation || 16;
  21906. subdivisions = subdivisions || 1;
  21907. subdivisions = (subdivisions < 1) ? 1 : subdivisions;
  21908. var getCircleVector = function (i) {
  21909. var angle = (i * 2.0 * Math.PI / tessellation);
  21910. var dx = Math.cos(angle);
  21911. var dz = Math.sin(angle);
  21912. return new BABYLON.Vector3(dx, 0, dz);
  21913. };
  21914. var createCylinderCap = function (isTop) {
  21915. var radius = isTop ? radiusTop : radiusBottom;
  21916. if (radius === 0) {
  21917. return;
  21918. }
  21919. var vbase = positions.length / 3;
  21920. var offset = new BABYLON.Vector3(0, height / 2, 0);
  21921. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  21922. if (!isTop) {
  21923. offset.scaleInPlace(-1);
  21924. textureScale.x = -textureScale.x;
  21925. }
  21926. for (var i = 0; i < tessellation; i++) {
  21927. var circleVector = getCircleVector(i);
  21928. var position = circleVector.scale(radius).add(offset);
  21929. var textureCoordinate = new BABYLON.Vector2(circleVector.x * textureScale.x + 0.5, circleVector.z * textureScale.y + 0.5);
  21930. positions.push(position.x, position.y, position.z);
  21931. uvs.push(textureCoordinate.x, textureCoordinate.y);
  21932. }
  21933. for (i = 0; i < tessellation - 2; i++) {
  21934. if (!isTop) {
  21935. indices.push(vbase);
  21936. indices.push(vbase + (i + 2) % tessellation);
  21937. indices.push(vbase + (i + 1) % tessellation);
  21938. }
  21939. else {
  21940. indices.push(vbase);
  21941. indices.push(vbase + (i + 1) % tessellation);
  21942. indices.push(vbase + (i + 2) % tessellation);
  21943. }
  21944. }
  21945. };
  21946. var base = new BABYLON.Vector3(0, -1, 0).scale(height / 2);
  21947. var offset = new BABYLON.Vector3(0, 1, 0).scale(height / subdivisions);
  21948. var stride = tessellation + 1;
  21949. for (var i = 0; i <= tessellation; i++) {
  21950. var circleVector = getCircleVector(i);
  21951. var textureCoordinate = new BABYLON.Vector2(i / tessellation, 0);
  21952. var position, radius = radiusBottom;
  21953. for (var s = 0; s <= subdivisions; s++) {
  21954. // Update variables
  21955. position = circleVector.scale(radius);
  21956. position.addInPlace(base.add(offset.scale(s)));
  21957. textureCoordinate.y += 1 / subdivisions;
  21958. radius += (radiusTop - radiusBottom) / subdivisions;
  21959. // Push in arrays
  21960. positions.push(position.x, position.y, position.z);
  21961. uvs.push(textureCoordinate.x, textureCoordinate.y);
  21962. }
  21963. }
  21964. subdivisions += 1;
  21965. for (s = 0; s < subdivisions - 1; s++) {
  21966. for (i = 0; i <= tessellation; i++) {
  21967. indices.push(i * subdivisions + s);
  21968. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  21969. indices.push(i * subdivisions + (s + 1));
  21970. indices.push(i * subdivisions + (s + 1));
  21971. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  21972. indices.push((i * subdivisions + (s + subdivisions + 1)) % (stride * subdivisions));
  21973. }
  21974. }
  21975. // Create flat triangle fan caps to seal the top and bottom.
  21976. createCylinderCap(true);
  21977. createCylinderCap(false);
  21978. // Normals
  21979. VertexData.ComputeNormals(positions, indices, normals);
  21980. // Sides
  21981. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  21982. // Result
  21983. var vertexData = new VertexData();
  21984. vertexData.indices = indices;
  21985. vertexData.positions = positions;
  21986. vertexData.normals = normals;
  21987. vertexData.uvs = uvs;
  21988. return vertexData;
  21989. };
  21990. VertexData.CreateTorus = function (diameter, thickness, tessellation, sideOrientation) {
  21991. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  21992. var indices = [];
  21993. var positions = [];
  21994. var normals = [];
  21995. var uvs = [];
  21996. diameter = diameter || 1;
  21997. thickness = thickness || 0.5;
  21998. tessellation = tessellation || 16;
  21999. var stride = tessellation + 1;
  22000. for (var i = 0; i <= tessellation; i++) {
  22001. var u = i / tessellation;
  22002. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  22003. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  22004. for (var j = 0; j <= tessellation; j++) {
  22005. var v = 1 - j / tessellation;
  22006. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  22007. var dx = Math.cos(innerAngle);
  22008. var dy = Math.sin(innerAngle);
  22009. // Create a vertex.
  22010. var normal = new BABYLON.Vector3(dx, dy, 0);
  22011. var position = normal.scale(thickness / 2);
  22012. var textureCoordinate = new BABYLON.Vector2(u, v);
  22013. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  22014. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  22015. positions.push(position.x, position.y, position.z);
  22016. normals.push(normal.x, normal.y, normal.z);
  22017. uvs.push(textureCoordinate.x, textureCoordinate.y);
  22018. // And create indices for two triangles.
  22019. var nextI = (i + 1) % stride;
  22020. var nextJ = (j + 1) % stride;
  22021. indices.push(i * stride + j);
  22022. indices.push(i * stride + nextJ);
  22023. indices.push(nextI * stride + j);
  22024. indices.push(i * stride + nextJ);
  22025. indices.push(nextI * stride + nextJ);
  22026. indices.push(nextI * stride + j);
  22027. }
  22028. }
  22029. // Sides
  22030. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  22031. // Result
  22032. var vertexData = new VertexData();
  22033. vertexData.indices = indices;
  22034. vertexData.positions = positions;
  22035. vertexData.normals = normals;
  22036. vertexData.uvs = uvs;
  22037. return vertexData;
  22038. };
  22039. VertexData.CreateLines = function (points) {
  22040. var indices = [];
  22041. var positions = [];
  22042. for (var index = 0; index < points.length; index++) {
  22043. positions.push(points[index].x, points[index].y, points[index].z);
  22044. if (index > 0) {
  22045. indices.push(index - 1);
  22046. indices.push(index);
  22047. }
  22048. }
  22049. // Result
  22050. var vertexData = new VertexData();
  22051. vertexData.indices = indices;
  22052. vertexData.positions = positions;
  22053. return vertexData;
  22054. };
  22055. VertexData.CreateGround = function (width, height, subdivisions) {
  22056. var indices = [];
  22057. var positions = [];
  22058. var normals = [];
  22059. var uvs = [];
  22060. var row, col;
  22061. width = width || 1;
  22062. height = height || 1;
  22063. subdivisions = subdivisions || 1;
  22064. for (row = 0; row <= subdivisions; row++) {
  22065. for (col = 0; col <= subdivisions; col++) {
  22066. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  22067. var normal = new BABYLON.Vector3(0, 1.0, 0);
  22068. positions.push(position.x, position.y, position.z);
  22069. normals.push(normal.x, normal.y, normal.z);
  22070. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  22071. }
  22072. }
  22073. for (row = 0; row < subdivisions; row++) {
  22074. for (col = 0; col < subdivisions; col++) {
  22075. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  22076. indices.push(col + 1 + row * (subdivisions + 1));
  22077. indices.push(col + row * (subdivisions + 1));
  22078. indices.push(col + (row + 1) * (subdivisions + 1));
  22079. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  22080. indices.push(col + row * (subdivisions + 1));
  22081. }
  22082. }
  22083. // Result
  22084. var vertexData = new VertexData();
  22085. vertexData.indices = indices;
  22086. vertexData.positions = positions;
  22087. vertexData.normals = normals;
  22088. vertexData.uvs = uvs;
  22089. return vertexData;
  22090. };
  22091. VertexData.CreateTiledGround = function (xmin, zmin, xmax, zmax, subdivisions, precision) {
  22092. if (subdivisions === void 0) { subdivisions = { w: 1, h: 1 }; }
  22093. if (precision === void 0) { precision = { w: 1, h: 1 }; }
  22094. var indices = [];
  22095. var positions = [];
  22096. var normals = [];
  22097. var uvs = [];
  22098. var row, col, tileRow, tileCol;
  22099. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  22100. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  22101. precision.w = (precision.w < 1) ? 1 : precision.w;
  22102. precision.h = (precision.h < 1) ? 1 : precision.h;
  22103. var tileSize = {
  22104. 'w': (xmax - xmin) / subdivisions.w,
  22105. 'h': (zmax - zmin) / subdivisions.h
  22106. };
  22107. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  22108. // Indices
  22109. var base = positions.length / 3;
  22110. var rowLength = precision.w + 1;
  22111. for (row = 0; row < precision.h; row++) {
  22112. for (col = 0; col < precision.w; col++) {
  22113. var square = [
  22114. base + col + row * rowLength,
  22115. base + (col + 1) + row * rowLength,
  22116. base + (col + 1) + (row + 1) * rowLength,
  22117. base + col + (row + 1) * rowLength
  22118. ];
  22119. indices.push(square[1]);
  22120. indices.push(square[2]);
  22121. indices.push(square[3]);
  22122. indices.push(square[0]);
  22123. indices.push(square[1]);
  22124. indices.push(square[3]);
  22125. }
  22126. }
  22127. // Position, normals and uvs
  22128. var position = BABYLON.Vector3.Zero();
  22129. var normal = new BABYLON.Vector3(0, 1.0, 0);
  22130. for (row = 0; row <= precision.h; row++) {
  22131. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  22132. for (col = 0; col <= precision.w; col++) {
  22133. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  22134. position.y = 0;
  22135. positions.push(position.x, position.y, position.z);
  22136. normals.push(normal.x, normal.y, normal.z);
  22137. uvs.push(col / precision.w, row / precision.h);
  22138. }
  22139. }
  22140. }
  22141. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  22142. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  22143. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  22144. }
  22145. }
  22146. // Result
  22147. var vertexData = new VertexData();
  22148. vertexData.indices = indices;
  22149. vertexData.positions = positions;
  22150. vertexData.normals = normals;
  22151. vertexData.uvs = uvs;
  22152. return vertexData;
  22153. };
  22154. VertexData.CreateGroundFromHeightMap = function (width, height, subdivisions, minHeight, maxHeight, buffer, bufferWidth, bufferHeight) {
  22155. var indices = [];
  22156. var positions = [];
  22157. var normals = [];
  22158. var uvs = [];
  22159. var row, col;
  22160. for (row = 0; row <= subdivisions; row++) {
  22161. for (col = 0; col <= subdivisions; col++) {
  22162. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  22163. // Compute height
  22164. var heightMapX = (((position.x + width / 2) / width) * (bufferWidth - 1)) | 0;
  22165. var heightMapY = ((1.0 - (position.z + height / 2) / height) * (bufferHeight - 1)) | 0;
  22166. var pos = (heightMapX + heightMapY * bufferWidth) * 4;
  22167. var r = buffer[pos] / 255.0;
  22168. var g = buffer[pos + 1] / 255.0;
  22169. var b = buffer[pos + 2] / 255.0;
  22170. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  22171. position.y = minHeight + (maxHeight - minHeight) * gradient;
  22172. // Add vertex
  22173. positions.push(position.x, position.y, position.z);
  22174. normals.push(0, 0, 0);
  22175. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  22176. }
  22177. }
  22178. for (row = 0; row < subdivisions; row++) {
  22179. for (col = 0; col < subdivisions; col++) {
  22180. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  22181. indices.push(col + 1 + row * (subdivisions + 1));
  22182. indices.push(col + row * (subdivisions + 1));
  22183. indices.push(col + (row + 1) * (subdivisions + 1));
  22184. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  22185. indices.push(col + row * (subdivisions + 1));
  22186. }
  22187. }
  22188. // Normals
  22189. VertexData.ComputeNormals(positions, indices, normals);
  22190. // Result
  22191. var vertexData = new VertexData();
  22192. vertexData.indices = indices;
  22193. vertexData.positions = positions;
  22194. vertexData.normals = normals;
  22195. vertexData.uvs = uvs;
  22196. return vertexData;
  22197. };
  22198. VertexData.CreatePlane = function (size, sideOrientation) {
  22199. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  22200. var indices = [];
  22201. var positions = [];
  22202. var normals = [];
  22203. var uvs = [];
  22204. size = size || 1;
  22205. // Vertices
  22206. var halfSize = size / 2.0;
  22207. positions.push(-halfSize, -halfSize, 0);
  22208. normals.push(0, 0, -1.0);
  22209. uvs.push(0.0, 0.0);
  22210. positions.push(halfSize, -halfSize, 0);
  22211. normals.push(0, 0, -1.0);
  22212. uvs.push(1.0, 0.0);
  22213. positions.push(halfSize, halfSize, 0);
  22214. normals.push(0, 0, -1.0);
  22215. uvs.push(1.0, 1.0);
  22216. positions.push(-halfSize, halfSize, 0);
  22217. normals.push(0, 0, -1.0);
  22218. uvs.push(0.0, 1.0);
  22219. // Indices
  22220. indices.push(0);
  22221. indices.push(1);
  22222. indices.push(2);
  22223. indices.push(0);
  22224. indices.push(2);
  22225. indices.push(3);
  22226. // Sides
  22227. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  22228. // Result
  22229. var vertexData = new VertexData();
  22230. vertexData.indices = indices;
  22231. vertexData.positions = positions;
  22232. vertexData.normals = normals;
  22233. vertexData.uvs = uvs;
  22234. return vertexData;
  22235. };
  22236. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  22237. VertexData.CreateTorusKnot = function (radius, tube, radialSegments, tubularSegments, p, q, sideOrientation) {
  22238. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  22239. var indices = [];
  22240. var positions = [];
  22241. var normals = [];
  22242. var uvs = [];
  22243. radius = radius || 2;
  22244. tube = tube || 0.5;
  22245. radialSegments = radialSegments || 32;
  22246. tubularSegments = tubularSegments || 32;
  22247. p = p || 2;
  22248. q = q || 3;
  22249. // Helper
  22250. var getPos = function (angle) {
  22251. var cu = Math.cos(angle);
  22252. var su = Math.sin(angle);
  22253. var quOverP = q / p * angle;
  22254. var cs = Math.cos(quOverP);
  22255. var tx = radius * (2 + cs) * 0.5 * cu;
  22256. var ty = radius * (2 + cs) * su * 0.5;
  22257. var tz = radius * Math.sin(quOverP) * 0.5;
  22258. return new BABYLON.Vector3(tx, ty, tz);
  22259. };
  22260. for (var i = 0; i <= radialSegments; i++) {
  22261. var modI = i % radialSegments;
  22262. var u = modI / radialSegments * 2 * p * Math.PI;
  22263. var p1 = getPos(u);
  22264. var p2 = getPos(u + 0.01);
  22265. var tang = p2.subtract(p1);
  22266. var n = p2.add(p1);
  22267. var bitan = BABYLON.Vector3.Cross(tang, n);
  22268. n = BABYLON.Vector3.Cross(bitan, tang);
  22269. bitan.normalize();
  22270. n.normalize();
  22271. for (var j = 0; j < tubularSegments; j++) {
  22272. var modJ = j % tubularSegments;
  22273. var v = modJ / tubularSegments * 2 * Math.PI;
  22274. var cx = -tube * Math.cos(v);
  22275. var cy = tube * Math.sin(v);
  22276. positions.push(p1.x + cx * n.x + cy * bitan.x);
  22277. positions.push(p1.y + cx * n.y + cy * bitan.y);
  22278. positions.push(p1.z + cx * n.z + cy * bitan.z);
  22279. uvs.push(i / radialSegments);
  22280. uvs.push(j / tubularSegments);
  22281. }
  22282. }
  22283. for (i = 0; i < radialSegments; i++) {
  22284. for (j = 0; j < tubularSegments; j++) {
  22285. var jNext = (j + 1) % tubularSegments;
  22286. var a = i * tubularSegments + j;
  22287. var b = (i + 1) * tubularSegments + j;
  22288. var c = (i + 1) * tubularSegments + jNext;
  22289. var d = i * tubularSegments + jNext;
  22290. indices.push(d);
  22291. indices.push(b);
  22292. indices.push(a);
  22293. indices.push(d);
  22294. indices.push(c);
  22295. indices.push(b);
  22296. }
  22297. }
  22298. // Normals
  22299. VertexData.ComputeNormals(positions, indices, normals);
  22300. // Sides
  22301. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  22302. // Result
  22303. var vertexData = new VertexData();
  22304. vertexData.indices = indices;
  22305. vertexData.positions = positions;
  22306. vertexData.normals = normals;
  22307. vertexData.uvs = uvs;
  22308. return vertexData;
  22309. };
  22310. // Tools
  22311. VertexData.ComputeNormals = function (positions, indices, normals) {
  22312. var positionVectors = [];
  22313. var facesOfVertices = [];
  22314. var index;
  22315. for (index = 0; index < positions.length; index += 3) {
  22316. var vector3 = new BABYLON.Vector3(positions[index], positions[index + 1], positions[index + 2]);
  22317. positionVectors.push(vector3);
  22318. facesOfVertices.push([]);
  22319. }
  22320. // Compute normals
  22321. var facesNormals = [];
  22322. for (index = 0; index < indices.length / 3; index++) {
  22323. var i1 = indices[index * 3];
  22324. var i2 = indices[index * 3 + 1];
  22325. var i3 = indices[index * 3 + 2];
  22326. var p1 = positionVectors[i1];
  22327. var p2 = positionVectors[i2];
  22328. var p3 = positionVectors[i3];
  22329. var p1p2 = p1.subtract(p2);
  22330. var p3p2 = p3.subtract(p2);
  22331. facesNormals[index] = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  22332. facesOfVertices[i1].push(index);
  22333. facesOfVertices[i2].push(index);
  22334. facesOfVertices[i3].push(index);
  22335. }
  22336. for (index = 0; index < positionVectors.length; index++) {
  22337. var faces = facesOfVertices[index];
  22338. var normal = BABYLON.Vector3.Zero();
  22339. for (var faceIndex = 0; faceIndex < faces.length; faceIndex++) {
  22340. normal.addInPlace(facesNormals[faces[faceIndex]]);
  22341. }
  22342. normal = BABYLON.Vector3.Normalize(normal.scale(1.0 / faces.length));
  22343. normals[index * 3] = normal.x;
  22344. normals[index * 3 + 1] = normal.y;
  22345. normals[index * 3 + 2] = normal.z;
  22346. }
  22347. };
  22348. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  22349. var li = indices.length;
  22350. var ln = normals.length;
  22351. var i;
  22352. var n;
  22353. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  22354. switch (sideOrientation) {
  22355. case BABYLON.Mesh.FRONTSIDE:
  22356. break;
  22357. case BABYLON.Mesh.BACKSIDE:
  22358. var tmp;
  22359. for (i = 0; i < li; i += 3) {
  22360. tmp = indices[i];
  22361. indices[i] = indices[i + 2];
  22362. indices[i + 2] = tmp;
  22363. }
  22364. for (n = 0; n < ln; n++) {
  22365. normals[n] = -normals[n];
  22366. }
  22367. break;
  22368. case BABYLON.Mesh.DOUBLESIDE:
  22369. // positions
  22370. var lp = positions.length;
  22371. var l = lp / 3;
  22372. for (var p = 0; p < lp; p++) {
  22373. positions[lp + p] = positions[p];
  22374. }
  22375. for (i = 0; i < li; i += 3) {
  22376. indices[i + li] = indices[i + 2] + l;
  22377. indices[i + 1 + li] = indices[i + 1] + l;
  22378. indices[i + 2 + li] = indices[i] + l;
  22379. }
  22380. for (n = 0; n < ln; n++) {
  22381. normals[ln + n] = -normals[n];
  22382. }
  22383. // uvs
  22384. var lu = uvs.length;
  22385. for (var u = 0; u < lu; u++) {
  22386. uvs[u + lu] = uvs[u];
  22387. }
  22388. break;
  22389. }
  22390. };
  22391. return VertexData;
  22392. })();
  22393. BABYLON.VertexData = VertexData;
  22394. })(BABYLON || (BABYLON = {}));
  22395. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  22396. var BABYLON;
  22397. (function (BABYLON) {
  22398. var buildCamera = function (that, name) {
  22399. that._leftCamera.isIntermediate = true;
  22400. that.subCameras.push(that._leftCamera);
  22401. that.subCameras.push(that._rightCamera);
  22402. that._leftTexture = new BABYLON.PassPostProcess(name + "_leftTexture", 1.0, that._leftCamera);
  22403. that._anaglyphPostProcess = new BABYLON.AnaglyphPostProcess(name + "_anaglyph", 1.0, that._rightCamera);
  22404. that._anaglyphPostProcess.onApply = function (effect) {
  22405. effect.setTextureFromPostProcess("leftSampler", that._leftTexture);
  22406. };
  22407. that._update();
  22408. };
  22409. var AnaglyphArcRotateCamera = (function (_super) {
  22410. __extends(AnaglyphArcRotateCamera, _super);
  22411. // ANY
  22412. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, eyeSpace, scene) {
  22413. _super.call(this, name, alpha, beta, radius, target, scene);
  22414. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  22415. this._leftCamera = new BABYLON.ArcRotateCamera(name + "_left", alpha - this._eyeSpace, beta, radius, target, scene);
  22416. this._rightCamera = new BABYLON.ArcRotateCamera(name + "_right", alpha + this._eyeSpace, beta, radius, target, scene);
  22417. buildCamera(this, name);
  22418. }
  22419. AnaglyphArcRotateCamera.prototype._update = function () {
  22420. this._updateCamera(this._leftCamera);
  22421. this._updateCamera(this._rightCamera);
  22422. this._leftCamera.alpha = this.alpha - this._eyeSpace;
  22423. this._rightCamera.alpha = this.alpha + this._eyeSpace;
  22424. _super.prototype._update.call(this);
  22425. };
  22426. AnaglyphArcRotateCamera.prototype._updateCamera = function (camera) {
  22427. camera.beta = this.beta;
  22428. camera.radius = this.radius;
  22429. camera.minZ = this.minZ;
  22430. camera.maxZ = this.maxZ;
  22431. camera.fov = this.fov;
  22432. camera.target = this.target;
  22433. };
  22434. return AnaglyphArcRotateCamera;
  22435. })(BABYLON.ArcRotateCamera);
  22436. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  22437. var AnaglyphFreeCamera = (function (_super) {
  22438. __extends(AnaglyphFreeCamera, _super);
  22439. function AnaglyphFreeCamera(name, position, eyeSpace, scene) {
  22440. _super.call(this, name, position, scene);
  22441. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  22442. this._transformMatrix = new BABYLON.Matrix();
  22443. this._leftCamera = new BABYLON.FreeCamera(name + "_left", position.clone(), scene);
  22444. this._rightCamera = new BABYLON.FreeCamera(name + "_right", position.clone(), scene);
  22445. buildCamera(this, name);
  22446. }
  22447. AnaglyphFreeCamera.prototype._getSubCameraPosition = function (eyeSpace, result) {
  22448. var target = this.getTarget();
  22449. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(eyeSpace), this._transformMatrix);
  22450. this._transformMatrix = this._transformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  22451. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._transformMatrix, result);
  22452. };
  22453. AnaglyphFreeCamera.prototype._update = function () {
  22454. this._getSubCameraPosition(-this._eyeSpace, this._leftCamera.position);
  22455. this._getSubCameraPosition(this._eyeSpace, this._rightCamera.position);
  22456. this._updateCamera(this._leftCamera);
  22457. this._updateCamera(this._rightCamera);
  22458. _super.prototype._update.call(this);
  22459. };
  22460. AnaglyphFreeCamera.prototype._updateCamera = function (camera) {
  22461. camera.minZ = this.minZ;
  22462. camera.maxZ = this.maxZ;
  22463. camera.fov = this.fov;
  22464. camera.viewport = this.viewport;
  22465. camera.setTarget(this.getTarget());
  22466. };
  22467. return AnaglyphFreeCamera;
  22468. })(BABYLON.FreeCamera);
  22469. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  22470. })(BABYLON || (BABYLON = {}));
  22471. //# sourceMappingURL=babylon.anaglyphCamera.js.map
  22472. var BABYLON;
  22473. (function (BABYLON) {
  22474. var AnaglyphPostProcess = (function (_super) {
  22475. __extends(AnaglyphPostProcess, _super);
  22476. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  22477. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  22478. }
  22479. return AnaglyphPostProcess;
  22480. })(BABYLON.PostProcess);
  22481. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  22482. })(BABYLON || (BABYLON = {}));
  22483. //# sourceMappingURL=babylon.anaglyphPostProcess.js.mapvar BABYLON;
  22484. (function (BABYLON) {
  22485. var Tags = (function () {
  22486. function Tags() {
  22487. }
  22488. Tags.EnableFor = function (obj) {
  22489. obj._tags = obj._tags || {};
  22490. obj.hasTags = function () {
  22491. return Tags.HasTags(obj);
  22492. };
  22493. obj.addTags = function (tagsString) {
  22494. return Tags.AddTagsTo(obj, tagsString);
  22495. };
  22496. obj.removeTags = function (tagsString) {
  22497. return Tags.RemoveTagsFrom(obj, tagsString);
  22498. };
  22499. obj.matchesTagsQuery = function (tagsQuery) {
  22500. return Tags.MatchesQuery(obj, tagsQuery);
  22501. };
  22502. };
  22503. Tags.DisableFor = function (obj) {
  22504. delete obj._tags;
  22505. delete obj.hasTags;
  22506. delete obj.addTags;
  22507. delete obj.removeTags;
  22508. delete obj.matchesTagsQuery;
  22509. };
  22510. Tags.HasTags = function (obj) {
  22511. if (!obj._tags) {
  22512. return false;
  22513. }
  22514. return !BABYLON.Tools.IsEmpty(obj._tags);
  22515. };
  22516. Tags.GetTags = function (obj) {
  22517. if (!obj._tags) {
  22518. return null;
  22519. }
  22520. return obj._tags;
  22521. };
  22522. // the tags 'true' and 'false' are reserved and cannot be used as tags
  22523. // a tag cannot start with '||', '&&', and '!'
  22524. // it cannot contain whitespaces
  22525. Tags.AddTagsTo = function (obj, tagsString) {
  22526. if (!tagsString) {
  22527. return;
  22528. }
  22529. var tags = tagsString.split(" ");
  22530. for (var t in tags) {
  22531. Tags._AddTagTo(obj, tags[t]);
  22532. }
  22533. };
  22534. Tags._AddTagTo = function (obj, tag) {
  22535. tag = tag.trim();
  22536. if (tag === "" || tag === "true" || tag === "false") {
  22537. return;
  22538. }
  22539. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  22540. return;
  22541. }
  22542. Tags.EnableFor(obj);
  22543. obj._tags[tag] = true;
  22544. };
  22545. Tags.RemoveTagsFrom = function (obj, tagsString) {
  22546. if (!Tags.HasTags(obj)) {
  22547. return;
  22548. }
  22549. var tags = tagsString.split(" ");
  22550. for (var t in tags) {
  22551. Tags._RemoveTagFrom(obj, tags[t]);
  22552. }
  22553. };
  22554. Tags._RemoveTagFrom = function (obj, tag) {
  22555. delete obj._tags[tag];
  22556. };
  22557. Tags.MatchesQuery = function (obj, tagsQuery) {
  22558. if (tagsQuery === undefined) {
  22559. return true;
  22560. }
  22561. if (tagsQuery === "") {
  22562. return Tags.HasTags(obj);
  22563. }
  22564. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  22565. };
  22566. return Tags;
  22567. })();
  22568. BABYLON.Tags = Tags;
  22569. })(BABYLON || (BABYLON = {}));
  22570. //# sourceMappingURL=babylon.tags.js.mapvar BABYLON;
  22571. (function (BABYLON) {
  22572. var Internals;
  22573. (function (Internals) {
  22574. var AndOrNotEvaluator = (function () {
  22575. function AndOrNotEvaluator() {
  22576. }
  22577. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  22578. if (!query.match(/\([^\(\)]*\)/g)) {
  22579. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  22580. }
  22581. else {
  22582. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  22583. // remove parenthesis
  22584. r = r.slice(1, r.length - 1);
  22585. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  22586. });
  22587. }
  22588. if (query === "true") {
  22589. return true;
  22590. }
  22591. if (query === "false") {
  22592. return false;
  22593. }
  22594. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  22595. };
  22596. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  22597. evaluateCallback = evaluateCallback || (function (r) {
  22598. return r === "true" ? true : false;
  22599. });
  22600. var result;
  22601. var or = parenthesisContent.split("||");
  22602. for (var i in or) {
  22603. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  22604. var and = ori.split("&&");
  22605. if (and.length > 1) {
  22606. for (var j = 0; j < and.length; ++j) {
  22607. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  22608. if (andj !== "true" && andj !== "false") {
  22609. if (andj[0] === "!") {
  22610. result = !evaluateCallback(andj.substring(1));
  22611. }
  22612. else {
  22613. result = evaluateCallback(andj);
  22614. }
  22615. }
  22616. else {
  22617. result = andj === "true" ? true : false;
  22618. }
  22619. if (!result) {
  22620. ori = "false";
  22621. break;
  22622. }
  22623. }
  22624. }
  22625. if (result || ori === "true") {
  22626. result = true;
  22627. break;
  22628. }
  22629. // result equals false (or undefined)
  22630. if (ori !== "true" && ori !== "false") {
  22631. if (ori[0] === "!") {
  22632. result = !evaluateCallback(ori.substring(1));
  22633. }
  22634. else {
  22635. result = evaluateCallback(ori);
  22636. }
  22637. }
  22638. else {
  22639. result = ori === "true" ? true : false;
  22640. }
  22641. }
  22642. // the whole parenthesis scope is replaced by 'true' or 'false'
  22643. return result ? "true" : "false";
  22644. };
  22645. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  22646. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  22647. // remove whitespaces
  22648. r = r.replace(/[\s]/g, function () { return ""; });
  22649. return r.length % 2 ? "!" : "";
  22650. });
  22651. booleanString = booleanString.trim();
  22652. if (booleanString === "!true") {
  22653. booleanString = "false";
  22654. }
  22655. else if (booleanString === "!false") {
  22656. booleanString = "true";
  22657. }
  22658. return booleanString;
  22659. };
  22660. return AndOrNotEvaluator;
  22661. })();
  22662. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  22663. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  22664. })(BABYLON || (BABYLON = {}));
  22665. //# sourceMappingURL=babylon.andOrNotEvaluator.js.mapvar BABYLON;
  22666. (function (BABYLON) {
  22667. var PostProcessRenderPass = (function () {
  22668. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  22669. this._enabled = true;
  22670. this._refCount = 0;
  22671. this._name = name;
  22672. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  22673. this.setRenderList(renderList);
  22674. this._renderTexture.onBeforeRender = beforeRender;
  22675. this._renderTexture.onAfterRender = afterRender;
  22676. this._scene = scene;
  22677. this._renderList = renderList;
  22678. }
  22679. // private
  22680. PostProcessRenderPass.prototype._incRefCount = function () {
  22681. if (this._refCount === 0) {
  22682. this._scene.customRenderTargets.push(this._renderTexture);
  22683. }
  22684. return ++this._refCount;
  22685. };
  22686. PostProcessRenderPass.prototype._decRefCount = function () {
  22687. this._refCount--;
  22688. if (this._refCount <= 0) {
  22689. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  22690. }
  22691. return this._refCount;
  22692. };
  22693. PostProcessRenderPass.prototype._update = function () {
  22694. this.setRenderList(this._renderList);
  22695. };
  22696. // public
  22697. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  22698. this._renderTexture.renderList = renderList;
  22699. };
  22700. PostProcessRenderPass.prototype.getRenderTexture = function () {
  22701. return this._renderTexture;
  22702. };
  22703. return PostProcessRenderPass;
  22704. })();
  22705. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  22706. })(BABYLON || (BABYLON = {}));
  22707. //# sourceMappingURL=babylon.postProcessRenderPass.js.mapvar BABYLON;
  22708. (function (BABYLON) {
  22709. var PostProcessRenderEffect = (function () {
  22710. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  22711. this._engine = engine;
  22712. this._name = name;
  22713. this._singleInstance = singleInstance || true;
  22714. this._getPostProcess = getPostProcess;
  22715. this._cameras = [];
  22716. this._indicesForCamera = [];
  22717. this._postProcesses = {};
  22718. this._renderPasses = {};
  22719. this._renderEffectAsPasses = {};
  22720. }
  22721. PostProcessRenderEffect.prototype._update = function () {
  22722. for (var renderPassName in this._renderPasses) {
  22723. this._renderPasses[renderPassName]._update();
  22724. }
  22725. };
  22726. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  22727. this._renderPasses[renderPass._name] = renderPass;
  22728. this._linkParameters();
  22729. };
  22730. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  22731. delete this._renderPasses[renderPass._name];
  22732. this._linkParameters();
  22733. };
  22734. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  22735. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  22736. this._linkParameters();
  22737. };
  22738. PostProcessRenderEffect.prototype.getPass = function (passName) {
  22739. for (var renderPassName in this._renderPasses) {
  22740. if (renderPassName === passName) {
  22741. return this._renderPasses[passName];
  22742. }
  22743. }
  22744. };
  22745. PostProcessRenderEffect.prototype.emptyPasses = function () {
  22746. this._renderPasses = {};
  22747. this._linkParameters();
  22748. };
  22749. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  22750. var cameraKey;
  22751. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  22752. for (var i = 0; i < _cam.length; i++) {
  22753. var camera = _cam[i];
  22754. var cameraName = camera.name;
  22755. if (this._singleInstance) {
  22756. cameraKey = 0;
  22757. }
  22758. else {
  22759. cameraKey = cameraName;
  22760. }
  22761. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  22762. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  22763. if (!this._indicesForCamera[cameraName]) {
  22764. this._indicesForCamera[cameraName] = [];
  22765. }
  22766. this._indicesForCamera[cameraName].push(index);
  22767. if (this._cameras.indexOf(camera) === -1) {
  22768. this._cameras[cameraName] = camera;
  22769. }
  22770. for (var passName in this._renderPasses) {
  22771. this._renderPasses[passName]._incRefCount();
  22772. }
  22773. }
  22774. this._linkParameters();
  22775. };
  22776. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  22777. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  22778. for (var i = 0; i < _cam.length; i++) {
  22779. var camera = _cam[i];
  22780. var cameraName = camera.name;
  22781. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  22782. var index = this._cameras.indexOf(cameraName);
  22783. this._indicesForCamera.splice(index, 1);
  22784. this._cameras.splice(index, 1);
  22785. for (var passName in this._renderPasses) {
  22786. this._renderPasses[passName]._decRefCount();
  22787. }
  22788. }
  22789. };
  22790. PostProcessRenderEffect.prototype._enable = function (cameras) {
  22791. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  22792. for (var i = 0; i < _cam.length; i++) {
  22793. var camera = _cam[i];
  22794. var cameraName = camera.name;
  22795. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  22796. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  22797. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  22798. }
  22799. }
  22800. for (var passName in this._renderPasses) {
  22801. this._renderPasses[passName]._incRefCount();
  22802. }
  22803. }
  22804. };
  22805. PostProcessRenderEffect.prototype._disable = function (cameras) {
  22806. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  22807. for (var i = 0; i < _cam.length; i++) {
  22808. var camera = _cam[i];
  22809. var cameraName = camera.Name;
  22810. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  22811. for (var passName in this._renderPasses) {
  22812. this._renderPasses[passName]._decRefCount();
  22813. }
  22814. }
  22815. };
  22816. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  22817. if (this._singleInstance) {
  22818. return this._postProcesses[0];
  22819. }
  22820. else {
  22821. return this._postProcesses[camera.name];
  22822. }
  22823. };
  22824. PostProcessRenderEffect.prototype._linkParameters = function () {
  22825. var _this = this;
  22826. for (var index in this._postProcesses) {
  22827. if (this.applyParameters) {
  22828. this.applyParameters(this._postProcesses[index]);
  22829. }
  22830. this._postProcesses[index].onBeforeRender = function (effect) {
  22831. _this._linkTextures(effect);
  22832. };
  22833. }
  22834. };
  22835. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  22836. for (var renderPassName in this._renderPasses) {
  22837. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  22838. }
  22839. for (var renderEffectName in this._renderEffectAsPasses) {
  22840. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  22841. }
  22842. };
  22843. return PostProcessRenderEffect;
  22844. })();
  22845. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  22846. })(BABYLON || (BABYLON = {}));
  22847. //# sourceMappingURL=babylon.postProcessRenderEffect.js.mapvar BABYLON;
  22848. (function (BABYLON) {
  22849. var PostProcessRenderPipeline = (function () {
  22850. function PostProcessRenderPipeline(engine, name) {
  22851. this._engine = engine;
  22852. this._name = name;
  22853. this._renderEffects = {};
  22854. this._renderEffectsForIsolatedPass = {};
  22855. this._cameras = [];
  22856. }
  22857. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  22858. this._renderEffects[renderEffect._name] = renderEffect;
  22859. };
  22860. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  22861. var renderEffects = this._renderEffects[renderEffectName];
  22862. if (!renderEffects) {
  22863. return;
  22864. }
  22865. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  22866. };
  22867. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  22868. var renderEffects = this._renderEffects[renderEffectName];
  22869. if (!renderEffects) {
  22870. return;
  22871. }
  22872. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  22873. };
  22874. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  22875. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  22876. var indicesToDelete = [];
  22877. for (var i = 0; i < _cam.length; i++) {
  22878. var camera = _cam[i];
  22879. var cameraName = camera.name;
  22880. if (this._cameras.indexOf(camera) === -1) {
  22881. this._cameras[cameraName] = camera;
  22882. }
  22883. else if (unique) {
  22884. indicesToDelete.push(i);
  22885. }
  22886. }
  22887. for (var i = 0; i < indicesToDelete.length; i++) {
  22888. cameras.splice(indicesToDelete[i], 1);
  22889. }
  22890. for (var renderEffectName in this._renderEffects) {
  22891. this._renderEffects[renderEffectName]._attachCameras(_cam);
  22892. }
  22893. };
  22894. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  22895. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  22896. for (var renderEffectName in this._renderEffects) {
  22897. this._renderEffects[renderEffectName]._detachCameras(_cam);
  22898. }
  22899. for (var i = 0; i < _cam.length; i++) {
  22900. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  22901. }
  22902. };
  22903. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  22904. var _this = this;
  22905. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  22906. var pass = null;
  22907. for (var renderEffectName in this._renderEffects) {
  22908. pass = this._renderEffects[renderEffectName].getPass(passName);
  22909. if (pass != null) {
  22910. break;
  22911. }
  22912. }
  22913. if (pass === null) {
  22914. return;
  22915. }
  22916. for (var renderEffectName in this._renderEffects) {
  22917. this._renderEffects[renderEffectName]._disable(_cam);
  22918. }
  22919. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  22920. for (var i = 0; i < _cam.length; i++) {
  22921. var camera = _cam[i];
  22922. var cameraName = camera.name;
  22923. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () {
  22924. return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true);
  22925. });
  22926. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  22927. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  22928. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  22929. }
  22930. };
  22931. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  22932. var _this = this;
  22933. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  22934. for (var i = 0; i < _cam.length; i++) {
  22935. var camera = _cam[i];
  22936. var cameraName = camera.name;
  22937. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () {
  22938. return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true);
  22939. });
  22940. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  22941. }
  22942. for (var renderEffectName in this._renderEffects) {
  22943. this._renderEffects[renderEffectName]._enable(_cam);
  22944. }
  22945. };
  22946. PostProcessRenderPipeline.prototype._update = function () {
  22947. for (var renderEffectName in this._renderEffects) {
  22948. this._renderEffects[renderEffectName]._update();
  22949. }
  22950. for (var i = 0; i < this._cameras.length; i++) {
  22951. var cameraName = this._cameras[i].name;
  22952. if (this._renderEffectsForIsolatedPass[cameraName]) {
  22953. this._renderEffectsForIsolatedPass[cameraName]._update();
  22954. }
  22955. }
  22956. };
  22957. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  22958. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  22959. return PostProcessRenderPipeline;
  22960. })();
  22961. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  22962. })(BABYLON || (BABYLON = {}));
  22963. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.mapvar BABYLON;
  22964. (function (BABYLON) {
  22965. var PostProcessRenderPipelineManager = (function () {
  22966. function PostProcessRenderPipelineManager() {
  22967. this._renderPipelines = {};
  22968. }
  22969. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  22970. this._renderPipelines[renderPipeline._name] = renderPipeline;
  22971. };
  22972. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  22973. var renderPipeline = this._renderPipelines[renderPipelineName];
  22974. if (!renderPipeline) {
  22975. return;
  22976. }
  22977. renderPipeline._attachCameras(cameras, unique);
  22978. };
  22979. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  22980. var renderPipeline = this._renderPipelines[renderPipelineName];
  22981. if (!renderPipeline) {
  22982. return;
  22983. }
  22984. renderPipeline._detachCameras(cameras);
  22985. };
  22986. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  22987. var renderPipeline = this._renderPipelines[renderPipelineName];
  22988. if (!renderPipeline) {
  22989. return;
  22990. }
  22991. renderPipeline._enableEffect(renderEffectName, cameras);
  22992. };
  22993. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  22994. var renderPipeline = this._renderPipelines[renderPipelineName];
  22995. if (!renderPipeline) {
  22996. return;
  22997. }
  22998. renderPipeline._disableEffect(renderEffectName, cameras);
  22999. };
  23000. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  23001. var renderPipeline = this._renderPipelines[renderPipelineName];
  23002. if (!renderPipeline) {
  23003. return;
  23004. }
  23005. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  23006. };
  23007. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  23008. var renderPipeline = this._renderPipelines[renderPipelineName];
  23009. if (!renderPipeline) {
  23010. return;
  23011. }
  23012. renderPipeline._disableDisplayOnlyPass(cameras);
  23013. };
  23014. PostProcessRenderPipelineManager.prototype.update = function () {
  23015. for (var renderPipelineName in this._renderPipelines) {
  23016. this._renderPipelines[renderPipelineName]._update();
  23017. }
  23018. };
  23019. return PostProcessRenderPipelineManager;
  23020. })();
  23021. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  23022. })(BABYLON || (BABYLON = {}));
  23023. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  23024. var BABYLON;
  23025. (function (BABYLON) {
  23026. var DisplayPassPostProcess = (function (_super) {
  23027. __extends(DisplayPassPostProcess, _super);
  23028. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  23029. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  23030. }
  23031. return DisplayPassPostProcess;
  23032. })(BABYLON.PostProcess);
  23033. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  23034. })(BABYLON || (BABYLON = {}));
  23035. //# sourceMappingURL=babylon.displayPassPostProcess.js.mapvar BABYLON;
  23036. (function (BABYLON) {
  23037. var BoundingBoxRenderer = (function () {
  23038. function BoundingBoxRenderer(scene) {
  23039. this.frontColor = new BABYLON.Color3(1, 1, 1);
  23040. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  23041. this.showBackLines = true;
  23042. this.renderList = new BABYLON.SmartArray(32);
  23043. this._scene = scene;
  23044. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  23045. attributes: ["position"],
  23046. uniforms: ["worldViewProjection", "color"]
  23047. });
  23048. var engine = this._scene.getEngine();
  23049. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  23050. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  23051. 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]);
  23052. }
  23053. BoundingBoxRenderer.prototype.reset = function () {
  23054. this.renderList.reset();
  23055. };
  23056. BoundingBoxRenderer.prototype.render = function () {
  23057. if (this.renderList.length === 0 || !this._colorShader.isReady()) {
  23058. return;
  23059. }
  23060. var engine = this._scene.getEngine();
  23061. engine.setDepthWrite(false);
  23062. this._colorShader._preBind();
  23063. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  23064. var boundingBox = this.renderList.data[boundingBoxIndex];
  23065. var min = boundingBox.minimum;
  23066. var max = boundingBox.maximum;
  23067. var diff = max.subtract(min);
  23068. var median = min.add(diff.scale(0.5));
  23069. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z).multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z)).multiply(boundingBox.getWorldMatrix());
  23070. // VBOs
  23071. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  23072. if (this.showBackLines) {
  23073. // Back
  23074. engine.setDepthFunctionToGreaterOrEqual();
  23075. this._scene.resetCachedMaterial();
  23076. this._colorShader.setColor4("color", this.backColor.toColor4());
  23077. this._colorShader.bind(worldMatrix);
  23078. // Draw order
  23079. engine.draw(false, 0, 24);
  23080. }
  23081. // Front
  23082. engine.setDepthFunctionToLess();
  23083. this._scene.resetCachedMaterial();
  23084. this._colorShader.setColor4("color", this.frontColor.toColor4());
  23085. this._colorShader.bind(worldMatrix);
  23086. // Draw order
  23087. engine.draw(false, 0, 24);
  23088. }
  23089. this._colorShader.unbind();
  23090. engine.setDepthFunctionToLessOrEqual();
  23091. engine.setDepthWrite(true);
  23092. };
  23093. BoundingBoxRenderer.prototype.dispose = function () {
  23094. this._colorShader.dispose();
  23095. this._vb.dispose();
  23096. this._scene.getEngine()._releaseBuffer(this._ib);
  23097. };
  23098. return BoundingBoxRenderer;
  23099. })();
  23100. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  23101. })(BABYLON || (BABYLON = {}));
  23102. //# sourceMappingURL=babylon.boundingBoxRenderer.js.mapvar BABYLON;
  23103. (function (BABYLON) {
  23104. var Internals;
  23105. (function (Internals) {
  23106. /*
  23107. * Based on jsTGALoader - Javascript loader for TGA file
  23108. * By Vincent Thibault
  23109. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  23110. */
  23111. var TGATools = (function () {
  23112. function TGATools() {
  23113. }
  23114. TGATools.GetTGAHeader = function (data) {
  23115. var offset = 0;
  23116. var header = {
  23117. id_length: data[offset++],
  23118. colormap_type: data[offset++],
  23119. image_type: data[offset++],
  23120. colormap_index: data[offset++] | data[offset++] << 8,
  23121. colormap_length: data[offset++] | data[offset++] << 8,
  23122. colormap_size: data[offset++],
  23123. origin: [
  23124. data[offset++] | data[offset++] << 8,
  23125. data[offset++] | data[offset++] << 8
  23126. ],
  23127. width: data[offset++] | data[offset++] << 8,
  23128. height: data[offset++] | data[offset++] << 8,
  23129. pixel_size: data[offset++],
  23130. flags: data[offset++]
  23131. };
  23132. return header;
  23133. };
  23134. TGATools.UploadContent = function (gl, data) {
  23135. // Not enough data to contain header ?
  23136. if (data.length < 19) {
  23137. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  23138. return;
  23139. }
  23140. // Read Header
  23141. var offset = 18;
  23142. var header = TGATools.GetTGAHeader(data);
  23143. // Assume it's a valid Targa file.
  23144. if (header.id_length + offset > data.length) {
  23145. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  23146. return;
  23147. }
  23148. // Skip not needed data
  23149. offset += header.id_length;
  23150. var use_rle = false;
  23151. var use_pal = false;
  23152. var use_rgb = false;
  23153. var use_grey = false;
  23154. switch (header.image_type) {
  23155. case TGATools._TYPE_RLE_INDEXED:
  23156. use_rle = true;
  23157. case TGATools._TYPE_INDEXED:
  23158. use_pal = true;
  23159. break;
  23160. case TGATools._TYPE_RLE_RGB:
  23161. use_rle = true;
  23162. case TGATools._TYPE_RGB:
  23163. use_rgb = true;
  23164. break;
  23165. case TGATools._TYPE_RLE_GREY:
  23166. use_rle = true;
  23167. case TGATools._TYPE_GREY:
  23168. use_grey = true;
  23169. break;
  23170. }
  23171. var pixel_data;
  23172. var numAlphaBits = header.flags & 0xf;
  23173. var pixel_size = header.pixel_size >> 3;
  23174. var pixel_total = header.width * header.height * pixel_size;
  23175. // Read palettes
  23176. var palettes;
  23177. if (use_pal) {
  23178. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  23179. }
  23180. // Read LRE
  23181. if (use_rle) {
  23182. pixel_data = new Uint8Array(pixel_total);
  23183. var c, count, i;
  23184. var localOffset = 0;
  23185. var pixels = new Uint8Array(pixel_size);
  23186. while (offset < pixel_total && localOffset < pixel_total) {
  23187. c = data[offset++];
  23188. count = (c & 0x7f) + 1;
  23189. // RLE pixels
  23190. if (c & 0x80) {
  23191. for (i = 0; i < pixel_size; ++i) {
  23192. pixels[i] = data[offset++];
  23193. }
  23194. for (i = 0; i < count; ++i) {
  23195. pixel_data.set(pixels, localOffset + i * pixel_size);
  23196. }
  23197. localOffset += pixel_size * count;
  23198. }
  23199. else {
  23200. count *= pixel_size;
  23201. for (i = 0; i < count; ++i) {
  23202. pixel_data[localOffset + i] = data[offset++];
  23203. }
  23204. localOffset += count;
  23205. }
  23206. }
  23207. }
  23208. else {
  23209. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  23210. }
  23211. // Load to texture
  23212. var x_start, y_start, x_step, y_step, y_end, x_end;
  23213. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  23214. default:
  23215. case TGATools._ORIGIN_UL:
  23216. x_start = 0;
  23217. x_step = 1;
  23218. x_end = header.width;
  23219. y_start = 0;
  23220. y_step = 1;
  23221. y_end = header.height;
  23222. break;
  23223. case TGATools._ORIGIN_BL:
  23224. x_start = 0;
  23225. x_step = 1;
  23226. x_end = header.width;
  23227. y_start = header.height - 1;
  23228. y_step = -1;
  23229. y_end = -1;
  23230. break;
  23231. case TGATools._ORIGIN_UR:
  23232. x_start = header.width - 1;
  23233. x_step = -1;
  23234. x_end = -1;
  23235. y_start = 0;
  23236. y_step = 1;
  23237. y_end = header.height;
  23238. break;
  23239. case TGATools._ORIGIN_BR:
  23240. x_start = header.width - 1;
  23241. x_step = -1;
  23242. x_end = -1;
  23243. y_start = header.height - 1;
  23244. y_step = -1;
  23245. y_end = -1;
  23246. break;
  23247. }
  23248. // Load the specify method
  23249. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  23250. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  23251. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  23252. };
  23253. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  23254. var image = pixel_data, colormap = palettes;
  23255. var width = header.width, height = header.height;
  23256. var color, i = 0, x, y;
  23257. var imageData = new Uint8Array(width * height * 4);
  23258. for (y = y_start; y !== y_end; y += y_step) {
  23259. for (x = x_start; x !== x_end; x += x_step, i++) {
  23260. color = image[i];
  23261. imageData[(x + width * y) * 4 + 3] = 255;
  23262. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  23263. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  23264. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  23265. }
  23266. }
  23267. return imageData;
  23268. };
  23269. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  23270. var image = pixel_data;
  23271. var width = header.width, height = header.height;
  23272. var color, i = 0, x, y;
  23273. var imageData = new Uint8Array(width * height * 4);
  23274. for (y = y_start; y !== y_end; y += y_step) {
  23275. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  23276. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  23277. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  23278. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  23279. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  23280. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  23281. }
  23282. }
  23283. return imageData;
  23284. };
  23285. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  23286. var image = pixel_data;
  23287. var width = header.width, height = header.height;
  23288. var i = 0, x, y;
  23289. var imageData = new Uint8Array(width * height * 4);
  23290. for (y = y_start; y !== y_end; y += y_step) {
  23291. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  23292. imageData[(x + width * y) * 4 + 3] = 255;
  23293. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  23294. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  23295. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  23296. }
  23297. }
  23298. return imageData;
  23299. };
  23300. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  23301. var image = pixel_data;
  23302. var width = header.width, height = header.height;
  23303. var i = 0, x, y;
  23304. var imageData = new Uint8Array(width * height * 4);
  23305. for (y = y_start; y !== y_end; y += y_step) {
  23306. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  23307. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  23308. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  23309. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  23310. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  23311. }
  23312. }
  23313. return imageData;
  23314. };
  23315. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  23316. var image = pixel_data;
  23317. var width = header.width, height = header.height;
  23318. var color, i = 0, x, y;
  23319. var imageData = new Uint8Array(width * height * 4);
  23320. for (y = y_start; y !== y_end; y += y_step) {
  23321. for (x = x_start; x !== x_end; x += x_step, i++) {
  23322. color = image[i];
  23323. imageData[(x + width * y) * 4 + 0] = color;
  23324. imageData[(x + width * y) * 4 + 1] = color;
  23325. imageData[(x + width * y) * 4 + 2] = color;
  23326. imageData[(x + width * y) * 4 + 3] = 255;
  23327. }
  23328. }
  23329. return imageData;
  23330. };
  23331. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  23332. var image = pixel_data;
  23333. var width = header.width, height = header.height;
  23334. var i = 0, x, y;
  23335. var imageData = new Uint8Array(width * height * 4);
  23336. for (y = y_start; y !== y_end; y += y_step) {
  23337. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  23338. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  23339. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  23340. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  23341. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  23342. }
  23343. }
  23344. return imageData;
  23345. };
  23346. TGATools._TYPE_NO_DATA = 0;
  23347. TGATools._TYPE_INDEXED = 1;
  23348. TGATools._TYPE_RGB = 2;
  23349. TGATools._TYPE_GREY = 3;
  23350. TGATools._TYPE_RLE_INDEXED = 9;
  23351. TGATools._TYPE_RLE_RGB = 10;
  23352. TGATools._TYPE_RLE_GREY = 11;
  23353. TGATools._ORIGIN_MASK = 0x30;
  23354. TGATools._ORIGIN_SHIFT = 0x04;
  23355. TGATools._ORIGIN_BL = 0x00;
  23356. TGATools._ORIGIN_BR = 0x01;
  23357. TGATools._ORIGIN_UL = 0x02;
  23358. TGATools._ORIGIN_UR = 0x03;
  23359. return TGATools;
  23360. })();
  23361. Internals.TGATools = TGATools;
  23362. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  23363. })(BABYLON || (BABYLON = {}));
  23364. //# sourceMappingURL=babylon.tools.tga.js.mapvar BABYLON;
  23365. (function (BABYLON) {
  23366. var Internals;
  23367. (function (Internals) {
  23368. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  23369. // All values and structures referenced from:
  23370. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  23371. var DDS_MAGIC = 0x20534444;
  23372. 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;
  23373. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  23374. 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;
  23375. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  23376. function FourCCToInt32(value) {
  23377. return value.charCodeAt(0) + (value.charCodeAt(1) << 8) + (value.charCodeAt(2) << 16) + (value.charCodeAt(3) << 24);
  23378. }
  23379. function Int32ToFourCC(value) {
  23380. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  23381. }
  23382. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  23383. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  23384. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  23385. var headerLengthInt = 31; // The header length in 32 bit ints
  23386. // Offsets into the header array
  23387. var off_magic = 0;
  23388. var off_size = 1;
  23389. var off_flags = 2;
  23390. var off_height = 3;
  23391. var off_width = 4;
  23392. var off_mipmapCount = 7;
  23393. var off_pfFlags = 20;
  23394. var off_pfFourCC = 21;
  23395. var off_RGBbpp = 22;
  23396. var off_RMask = 23;
  23397. var off_GMask = 24;
  23398. var off_BMask = 25;
  23399. var off_AMask = 26;
  23400. var off_caps1 = 27;
  23401. var off_caps2 = 28;
  23402. ;
  23403. var DDSTools = (function () {
  23404. function DDSTools() {
  23405. }
  23406. DDSTools.GetDDSInfo = function (arrayBuffer) {
  23407. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  23408. var mipmapCount = 1;
  23409. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  23410. mipmapCount = Math.max(1, header[off_mipmapCount]);
  23411. }
  23412. return {
  23413. width: header[off_width],
  23414. height: header[off_height],
  23415. mipmapCount: mipmapCount,
  23416. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  23417. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  23418. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  23419. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  23420. };
  23421. };
  23422. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  23423. var byteArray = new Uint8Array(dataLength);
  23424. var srcData = new Uint8Array(arrayBuffer);
  23425. var index = 0;
  23426. for (var y = height - 1; y >= 0; y--) {
  23427. for (var x = 0; x < width; x++) {
  23428. var srcPos = dataOffset + (x + y * width) * 4;
  23429. byteArray[index + 2] = srcData[srcPos];
  23430. byteArray[index + 1] = srcData[srcPos + 1];
  23431. byteArray[index] = srcData[srcPos + 2];
  23432. byteArray[index + 3] = srcData[srcPos + 3];
  23433. index += 4;
  23434. }
  23435. }
  23436. return byteArray;
  23437. };
  23438. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  23439. var byteArray = new Uint8Array(dataLength);
  23440. var srcData = new Uint8Array(arrayBuffer);
  23441. var index = 0;
  23442. for (var y = height - 1; y >= 0; y--) {
  23443. for (var x = 0; x < width; x++) {
  23444. var srcPos = dataOffset + (x + y * width) * 3;
  23445. byteArray[index + 2] = srcData[srcPos];
  23446. byteArray[index + 1] = srcData[srcPos + 1];
  23447. byteArray[index] = srcData[srcPos + 2];
  23448. index += 3;
  23449. }
  23450. }
  23451. return byteArray;
  23452. };
  23453. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  23454. var byteArray = new Uint8Array(dataLength);
  23455. var srcData = new Uint8Array(arrayBuffer);
  23456. var index = 0;
  23457. for (var y = height - 1; y >= 0; y--) {
  23458. for (var x = 0; x < width; x++) {
  23459. var srcPos = dataOffset + (x + y * width);
  23460. byteArray[index] = srcData[srcPos];
  23461. index++;
  23462. }
  23463. }
  23464. return byteArray;
  23465. };
  23466. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  23467. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  23468. if (header[off_magic] != DDS_MAGIC) {
  23469. BABYLON.Tools.Error("Invalid magic number in DDS header");
  23470. return;
  23471. }
  23472. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  23473. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  23474. return;
  23475. }
  23476. if (info.isFourCC) {
  23477. fourCC = header[off_pfFourCC];
  23478. switch (fourCC) {
  23479. case FOURCC_DXT1:
  23480. blockBytes = 8;
  23481. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  23482. break;
  23483. case FOURCC_DXT3:
  23484. blockBytes = 16;
  23485. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  23486. break;
  23487. case FOURCC_DXT5:
  23488. blockBytes = 16;
  23489. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  23490. break;
  23491. default:
  23492. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  23493. return;
  23494. }
  23495. }
  23496. mipmapCount = 1;
  23497. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  23498. mipmapCount = Math.max(1, header[off_mipmapCount]);
  23499. }
  23500. var bpp = header[off_RGBbpp];
  23501. for (var face = 0; face < faces; face++) {
  23502. var sampler = faces == 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  23503. width = header[off_width];
  23504. height = header[off_height];
  23505. dataOffset = header[off_size] + 4;
  23506. for (i = 0; i < mipmapCount; ++i) {
  23507. if (info.isRGB) {
  23508. if (bpp == 24) {
  23509. dataLength = width * height * 3;
  23510. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  23511. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  23512. }
  23513. else {
  23514. dataLength = width * height * 4;
  23515. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  23516. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  23517. }
  23518. }
  23519. else if (info.isLuminance) {
  23520. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  23521. var unpaddedRowSize = width;
  23522. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  23523. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  23524. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  23525. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  23526. }
  23527. else {
  23528. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  23529. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  23530. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  23531. }
  23532. dataOffset += dataLength;
  23533. width *= 0.5;
  23534. height *= 0.5;
  23535. width = Math.max(1.0, width);
  23536. height = Math.max(1.0, height);
  23537. }
  23538. }
  23539. };
  23540. return DDSTools;
  23541. })();
  23542. Internals.DDSTools = DDSTools;
  23543. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  23544. })(BABYLON || (BABYLON = {}));
  23545. //# sourceMappingURL=babylon.tools.dds.js.mapvar BABYLON;
  23546. (function (BABYLON) {
  23547. var SmartArray = (function () {
  23548. function SmartArray(capacity) {
  23549. this.length = 0;
  23550. this._duplicateId = 0;
  23551. this.data = new Array(capacity);
  23552. this._id = SmartArray._GlobalId++;
  23553. }
  23554. SmartArray.prototype.push = function (value) {
  23555. this.data[this.length++] = value;
  23556. if (this.length > this.data.length) {
  23557. this.data.length *= 2;
  23558. }
  23559. if (!value.__smartArrayFlags) {
  23560. value.__smartArrayFlags = {};
  23561. }
  23562. value.__smartArrayFlags[this._id] = this._duplicateId;
  23563. };
  23564. SmartArray.prototype.pushNoDuplicate = function (value) {
  23565. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  23566. return;
  23567. }
  23568. this.push(value);
  23569. };
  23570. SmartArray.prototype.sort = function (compareFn) {
  23571. this.data.sort(compareFn);
  23572. };
  23573. SmartArray.prototype.reset = function () {
  23574. this.length = 0;
  23575. this._duplicateId++;
  23576. };
  23577. SmartArray.prototype.concat = function (array) {
  23578. if (array.length === 0) {
  23579. return;
  23580. }
  23581. if (this.length + array.length > this.data.length) {
  23582. this.data.length = (this.length + array.length) * 2;
  23583. }
  23584. for (var index = 0; index < array.length; index++) {
  23585. this.data[this.length++] = (array.data || array)[index];
  23586. }
  23587. };
  23588. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  23589. if (array.length === 0) {
  23590. return;
  23591. }
  23592. if (this.length + array.length > this.data.length) {
  23593. this.data.length = (this.length + array.length) * 2;
  23594. }
  23595. for (var index = 0; index < array.length; index++) {
  23596. var item = (array.data || array)[index];
  23597. this.pushNoDuplicate(item);
  23598. }
  23599. };
  23600. SmartArray.prototype.indexOf = function (value) {
  23601. var position = this.data.indexOf(value);
  23602. if (position >= this.length) {
  23603. return -1;
  23604. }
  23605. return position;
  23606. };
  23607. // Statics
  23608. SmartArray._GlobalId = 0;
  23609. return SmartArray;
  23610. })();
  23611. BABYLON.SmartArray = SmartArray;
  23612. })(BABYLON || (BABYLON = {}));
  23613. //# sourceMappingURL=babylon.smartArray.js.mapvar BABYLON;
  23614. (function (BABYLON) {
  23615. var CannonJSPlugin = (function () {
  23616. function CannonJSPlugin() {
  23617. this._registeredMeshes = [];
  23618. this._physicsMaterials = [];
  23619. this.updateBodyPosition = function (mesh) {
  23620. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23621. var registeredMesh = this._registeredMeshes[index];
  23622. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  23623. var body = registeredMesh.body;
  23624. var center = mesh.getBoundingInfo().boundingBox.center;
  23625. body.position.set(center.x, center.z, center.y);
  23626. body.quaternion.x = mesh.rotationQuaternion.x;
  23627. body.quaternion.z = mesh.rotationQuaternion.y;
  23628. body.quaternion.y = mesh.rotationQuaternion.z;
  23629. body.quaternion.w = -mesh.rotationQuaternion.w;
  23630. return;
  23631. }
  23632. }
  23633. };
  23634. }
  23635. CannonJSPlugin.prototype.initialize = function (iterations) {
  23636. if (iterations === void 0) { iterations = 10; }
  23637. this._world = new CANNON.World();
  23638. this._world.broadphase = new CANNON.NaiveBroadphase();
  23639. this._world.solver.iterations = iterations;
  23640. };
  23641. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  23642. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  23643. };
  23644. CannonJSPlugin.prototype.runOneStep = function (delta) {
  23645. this._world.step(delta);
  23646. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23647. var registeredMesh = this._registeredMeshes[index];
  23648. if (registeredMesh.isChild) {
  23649. continue;
  23650. }
  23651. // Body position
  23652. var bodyX = registeredMesh.body.position.x, bodyY = registeredMesh.body.position.y, bodyZ = registeredMesh.body.position.z;
  23653. var deltaPos = registeredMesh.delta;
  23654. if (deltaPos) {
  23655. registeredMesh.mesh.position.x = bodyX + deltaPos.x;
  23656. registeredMesh.mesh.position.y = bodyZ + deltaPos.y;
  23657. registeredMesh.mesh.position.z = bodyY + deltaPos.z;
  23658. }
  23659. else {
  23660. registeredMesh.mesh.position.x = bodyX;
  23661. registeredMesh.mesh.position.y = bodyZ;
  23662. registeredMesh.mesh.position.z = bodyY;
  23663. }
  23664. if (!registeredMesh.mesh.rotationQuaternion) {
  23665. registeredMesh.mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  23666. }
  23667. registeredMesh.mesh.rotationQuaternion.x = registeredMesh.body.quaternion.x;
  23668. registeredMesh.mesh.rotationQuaternion.y = registeredMesh.body.quaternion.z;
  23669. registeredMesh.mesh.rotationQuaternion.z = registeredMesh.body.quaternion.y;
  23670. registeredMesh.mesh.rotationQuaternion.w = -registeredMesh.body.quaternion.w;
  23671. }
  23672. };
  23673. CannonJSPlugin.prototype.setGravity = function (gravity) {
  23674. this._world.gravity.set(gravity.x, gravity.z, gravity.y);
  23675. };
  23676. CannonJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  23677. this.unregisterMesh(mesh);
  23678. mesh.computeWorldMatrix(true);
  23679. switch (impostor) {
  23680. case BABYLON.PhysicsEngine.SphereImpostor:
  23681. var bbox = mesh.getBoundingInfo().boundingBox;
  23682. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  23683. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  23684. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  23685. return this._createSphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2, mesh, options);
  23686. case BABYLON.PhysicsEngine.BoxImpostor:
  23687. bbox = mesh.getBoundingInfo().boundingBox;
  23688. var min = bbox.minimumWorld;
  23689. var max = bbox.maximumWorld;
  23690. var box = max.subtract(min).scale(0.5);
  23691. return this._createBox(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z), mesh, options);
  23692. case BABYLON.PhysicsEngine.PlaneImpostor:
  23693. return this._createPlane(mesh, options);
  23694. case BABYLON.PhysicsEngine.MeshImpostor:
  23695. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23696. var rawFaces = mesh.getIndices();
  23697. return this._createConvexPolyhedron(rawVerts, rawFaces, mesh, options);
  23698. }
  23699. return null;
  23700. };
  23701. CannonJSPlugin.prototype._createSphere = function (radius, mesh, options) {
  23702. var shape = new CANNON.Sphere(radius);
  23703. if (!options) {
  23704. return shape;
  23705. }
  23706. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  23707. };
  23708. CannonJSPlugin.prototype._createBox = function (x, y, z, mesh, options) {
  23709. var shape = new CANNON.Box(new CANNON.Vec3(x, z, y));
  23710. if (!options) {
  23711. return shape;
  23712. }
  23713. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  23714. };
  23715. CannonJSPlugin.prototype._createPlane = function (mesh, options) {
  23716. var shape = new CANNON.Plane();
  23717. if (!options) {
  23718. return shape;
  23719. }
  23720. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  23721. };
  23722. CannonJSPlugin.prototype._createConvexPolyhedron = function (rawVerts, rawFaces, mesh, options) {
  23723. var verts = [], faces = [];
  23724. mesh.computeWorldMatrix(true);
  23725. for (var i = 0; i < rawVerts.length; i += 3) {
  23726. var transformed = BABYLON.Vector3.Zero();
  23727. BABYLON.Vector3.TransformNormalFromFloatsToRef(rawVerts[i], rawVerts[i + 1], rawVerts[i + 2], mesh.getWorldMatrix(), transformed);
  23728. verts.push(new CANNON.Vec3(transformed.x, transformed.z, transformed.y));
  23729. }
  23730. for (var j = 0; j < rawFaces.length; j += 3) {
  23731. faces.push([rawFaces[j], rawFaces[j + 2], rawFaces[j + 1]]);
  23732. }
  23733. var shape = new CANNON.ConvexPolyhedron(verts, faces);
  23734. if (!options) {
  23735. return shape;
  23736. }
  23737. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  23738. };
  23739. CannonJSPlugin.prototype._addMaterial = function (friction, restitution) {
  23740. var index;
  23741. var mat;
  23742. for (index = 0; index < this._physicsMaterials.length; index++) {
  23743. mat = this._physicsMaterials[index];
  23744. if (mat.friction === friction && mat.restitution === restitution) {
  23745. return mat;
  23746. }
  23747. }
  23748. var currentMat = new CANNON.Material();
  23749. currentMat.friction = friction;
  23750. currentMat.restitution = restitution;
  23751. this._physicsMaterials.push(currentMat);
  23752. for (index = 0; index < this._physicsMaterials.length; index++) {
  23753. mat = this._physicsMaterials[index];
  23754. var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, mat.friction * currentMat.friction, mat.restitution * currentMat.restitution);
  23755. contactMaterial.contactEquationStiffness = 1e10;
  23756. contactMaterial.contactEquationRegularizationTime = 10;
  23757. this._world.addContactMaterial(contactMaterial);
  23758. }
  23759. return currentMat;
  23760. };
  23761. CannonJSPlugin.prototype._createRigidBodyFromShape = function (shape, mesh, mass, friction, restitution) {
  23762. var initialRotation = null;
  23763. if (mesh.rotationQuaternion) {
  23764. initialRotation = mesh.rotationQuaternion.clone();
  23765. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  23766. }
  23767. // The delta between the mesh position and the mesh bounding box center
  23768. var bbox = mesh.getBoundingInfo().boundingBox;
  23769. var deltaPosition = mesh.position.subtract(bbox.center);
  23770. var material = this._addMaterial(friction, restitution);
  23771. var body = new CANNON.RigidBody(mass, shape, material);
  23772. if (initialRotation) {
  23773. body.quaternion.x = initialRotation.x;
  23774. body.quaternion.z = initialRotation.y;
  23775. body.quaternion.y = initialRotation.z;
  23776. body.quaternion.w = -initialRotation.w;
  23777. }
  23778. body.position.set(bbox.center.x, bbox.center.z, bbox.center.y);
  23779. this._world.add(body);
  23780. this._registeredMeshes.push({ mesh: mesh, body: body, material: material, delta: deltaPosition });
  23781. return body;
  23782. };
  23783. CannonJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  23784. var compoundShape = new CANNON.Compound();
  23785. for (var index = 0; index < parts.length; index++) {
  23786. var mesh = parts[index].mesh;
  23787. var shape = this.registerMesh(mesh, parts[index].impostor);
  23788. if (index == 0) {
  23789. compoundShape.addChild(shape, new CANNON.Vec3(0, 0, 0));
  23790. }
  23791. else {
  23792. compoundShape.addChild(shape, new CANNON.Vec3(mesh.position.x, mesh.position.z, mesh.position.y));
  23793. }
  23794. }
  23795. var initialMesh = parts[0].mesh;
  23796. var body = this._createRigidBodyFromShape(compoundShape, initialMesh, options.mass, options.friction, options.restitution);
  23797. body.parts = parts;
  23798. return body;
  23799. };
  23800. CannonJSPlugin.prototype._unbindBody = function (body) {
  23801. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23802. var registeredMesh = this._registeredMeshes[index];
  23803. if (registeredMesh.body === body) {
  23804. registeredMesh.body = null;
  23805. registeredMesh.delta = 0;
  23806. }
  23807. }
  23808. };
  23809. CannonJSPlugin.prototype.unregisterMesh = function (mesh) {
  23810. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23811. var registeredMesh = this._registeredMeshes[index];
  23812. if (registeredMesh.mesh === mesh) {
  23813. // Remove body
  23814. if (registeredMesh.body) {
  23815. this._world.remove(registeredMesh.body);
  23816. this._unbindBody(registeredMesh.body);
  23817. }
  23818. this._registeredMeshes.splice(index, 1);
  23819. return;
  23820. }
  23821. }
  23822. };
  23823. CannonJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  23824. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.z, contactPoint.y);
  23825. var impulse = new CANNON.Vec3(force.x, force.z, force.y);
  23826. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23827. var registeredMesh = this._registeredMeshes[index];
  23828. if (registeredMesh.mesh === mesh) {
  23829. registeredMesh.body.applyImpulse(impulse, worldPoint);
  23830. return;
  23831. }
  23832. }
  23833. };
  23834. CannonJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2) {
  23835. var body1 = null, body2 = null;
  23836. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23837. var registeredMesh = this._registeredMeshes[index];
  23838. if (registeredMesh.mesh === mesh1) {
  23839. body1 = registeredMesh.body;
  23840. }
  23841. else if (registeredMesh.mesh === mesh2) {
  23842. body2 = registeredMesh.body;
  23843. }
  23844. }
  23845. if (!body1 || !body2) {
  23846. return false;
  23847. }
  23848. 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));
  23849. this._world.addConstraint(constraint);
  23850. return true;
  23851. };
  23852. CannonJSPlugin.prototype.dispose = function () {
  23853. while (this._registeredMeshes.length) {
  23854. this.unregisterMesh(this._registeredMeshes[0].mesh);
  23855. }
  23856. };
  23857. CannonJSPlugin.prototype.isSupported = function () {
  23858. return window.CANNON !== undefined;
  23859. };
  23860. return CannonJSPlugin;
  23861. })();
  23862. BABYLON.CannonJSPlugin = CannonJSPlugin;
  23863. })(BABYLON || (BABYLON = {}));
  23864. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  23865. var BABYLON;
  23866. (function (BABYLON) {
  23867. var Condition = (function () {
  23868. function Condition(actionManager) {
  23869. this._actionManager = actionManager;
  23870. }
  23871. Condition.prototype.isValid = function () {
  23872. return true;
  23873. };
  23874. Condition.prototype._getProperty = function (propertyPath) {
  23875. return this._actionManager._getProperty(propertyPath);
  23876. };
  23877. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  23878. return this._actionManager._getEffectiveTarget(target, propertyPath);
  23879. };
  23880. return Condition;
  23881. })();
  23882. BABYLON.Condition = Condition;
  23883. var ValueCondition = (function (_super) {
  23884. __extends(ValueCondition, _super);
  23885. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  23886. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  23887. _super.call(this, actionManager);
  23888. this.propertyPath = propertyPath;
  23889. this.value = value;
  23890. this.operator = operator;
  23891. this._target = this._getEffectiveTarget(target, this.propertyPath);
  23892. this._property = this._getProperty(this.propertyPath);
  23893. }
  23894. Object.defineProperty(ValueCondition, "IsEqual", {
  23895. get: function () {
  23896. return ValueCondition._IsEqual;
  23897. },
  23898. enumerable: true,
  23899. configurable: true
  23900. });
  23901. Object.defineProperty(ValueCondition, "IsDifferent", {
  23902. get: function () {
  23903. return ValueCondition._IsDifferent;
  23904. },
  23905. enumerable: true,
  23906. configurable: true
  23907. });
  23908. Object.defineProperty(ValueCondition, "IsGreater", {
  23909. get: function () {
  23910. return ValueCondition._IsGreater;
  23911. },
  23912. enumerable: true,
  23913. configurable: true
  23914. });
  23915. Object.defineProperty(ValueCondition, "IsLesser", {
  23916. get: function () {
  23917. return ValueCondition._IsLesser;
  23918. },
  23919. enumerable: true,
  23920. configurable: true
  23921. });
  23922. // Methods
  23923. ValueCondition.prototype.isValid = function () {
  23924. switch (this.operator) {
  23925. case ValueCondition.IsGreater:
  23926. return this._target[this._property] > this.value;
  23927. case ValueCondition.IsLesser:
  23928. return this._target[this._property] < this.value;
  23929. case ValueCondition.IsEqual:
  23930. case ValueCondition.IsDifferent:
  23931. var check;
  23932. if (this.value.equals) {
  23933. check = this.value.equals(this._target[this._property]);
  23934. }
  23935. else {
  23936. check = this.value === this._target[this._property];
  23937. }
  23938. return this.operator === ValueCondition.IsEqual ? check : !check;
  23939. }
  23940. return false;
  23941. };
  23942. // Statics
  23943. ValueCondition._IsEqual = 0;
  23944. ValueCondition._IsDifferent = 1;
  23945. ValueCondition._IsGreater = 2;
  23946. ValueCondition._IsLesser = 3;
  23947. return ValueCondition;
  23948. })(Condition);
  23949. BABYLON.ValueCondition = ValueCondition;
  23950. var PredicateCondition = (function (_super) {
  23951. __extends(PredicateCondition, _super);
  23952. function PredicateCondition(actionManager, predicate) {
  23953. _super.call(this, actionManager);
  23954. this.predicate = predicate;
  23955. }
  23956. PredicateCondition.prototype.isValid = function () {
  23957. return this.predicate();
  23958. };
  23959. return PredicateCondition;
  23960. })(Condition);
  23961. BABYLON.PredicateCondition = PredicateCondition;
  23962. var StateCondition = (function (_super) {
  23963. __extends(StateCondition, _super);
  23964. function StateCondition(actionManager, target, value) {
  23965. _super.call(this, actionManager);
  23966. this.value = value;
  23967. this._target = target;
  23968. }
  23969. // Methods
  23970. StateCondition.prototype.isValid = function () {
  23971. return this._target.state === this.value;
  23972. };
  23973. return StateCondition;
  23974. })(Condition);
  23975. BABYLON.StateCondition = StateCondition;
  23976. })(BABYLON || (BABYLON = {}));
  23977. //# sourceMappingURL=babylon.condition.js.mapvar BABYLON;
  23978. (function (BABYLON) {
  23979. var Action = (function () {
  23980. function Action(triggerOptions, condition) {
  23981. this.triggerOptions = triggerOptions;
  23982. if (triggerOptions.parameter) {
  23983. this.trigger = triggerOptions.trigger;
  23984. this._triggerParameter = triggerOptions.parameter;
  23985. }
  23986. else {
  23987. this.trigger = triggerOptions;
  23988. }
  23989. this._nextActiveAction = this;
  23990. this._condition = condition;
  23991. }
  23992. // Methods
  23993. Action.prototype._prepare = function () {
  23994. };
  23995. Action.prototype.getTriggerParameter = function () {
  23996. return this._triggerParameter;
  23997. };
  23998. Action.prototype._executeCurrent = function (evt) {
  23999. if (this._nextActiveAction._condition) {
  24000. var condition = this._nextActiveAction._condition;
  24001. var currentRenderId = this._actionManager.getScene().getRenderId();
  24002. // We cache the current evaluation for the current frame
  24003. if (condition._evaluationId === currentRenderId) {
  24004. if (!condition._currentResult) {
  24005. return;
  24006. }
  24007. }
  24008. else {
  24009. condition._evaluationId = currentRenderId;
  24010. if (!condition.isValid()) {
  24011. condition._currentResult = false;
  24012. return;
  24013. }
  24014. condition._currentResult = true;
  24015. }
  24016. }
  24017. this._nextActiveAction.execute(evt);
  24018. if (this._nextActiveAction._child) {
  24019. if (!this._nextActiveAction._child._actionManager) {
  24020. this._nextActiveAction._child._actionManager = this._actionManager;
  24021. }
  24022. this._nextActiveAction = this._nextActiveAction._child;
  24023. }
  24024. else {
  24025. this._nextActiveAction = this;
  24026. }
  24027. };
  24028. Action.prototype.execute = function (evt) {
  24029. };
  24030. Action.prototype.then = function (action) {
  24031. this._child = action;
  24032. action._actionManager = this._actionManager;
  24033. action._prepare();
  24034. return action;
  24035. };
  24036. Action.prototype._getProperty = function (propertyPath) {
  24037. return this._actionManager._getProperty(propertyPath);
  24038. };
  24039. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  24040. return this._actionManager._getEffectiveTarget(target, propertyPath);
  24041. };
  24042. return Action;
  24043. })();
  24044. BABYLON.Action = Action;
  24045. })(BABYLON || (BABYLON = {}));
  24046. //# sourceMappingURL=babylon.action.js.mapvar BABYLON;
  24047. (function (BABYLON) {
  24048. /**
  24049. * ActionEvent is the event beint sent when an action is triggered.
  24050. */
  24051. var ActionEvent = (function () {
  24052. /**
  24053. * @constructor
  24054. * @param source The mesh that triggered the action.
  24055. * @param pointerX the X mouse cursor position at the time of the event
  24056. * @param pointerY the Y mouse cursor position at the time of the event
  24057. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  24058. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  24059. */
  24060. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent) {
  24061. this.source = source;
  24062. this.pointerX = pointerX;
  24063. this.pointerY = pointerY;
  24064. this.meshUnderPointer = meshUnderPointer;
  24065. this.sourceEvent = sourceEvent;
  24066. }
  24067. /**
  24068. * Helper function to auto-create an ActionEvent from a source mesh.
  24069. * @param source the source mesh that triggered the event
  24070. * @param evt {Event} The original (browser) event
  24071. */
  24072. ActionEvent.CreateNew = function (source, evt) {
  24073. var scene = source.getScene();
  24074. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  24075. };
  24076. /**
  24077. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  24078. * @param scene the scene where the event occurred
  24079. * @param evt {Event} The original (browser) event
  24080. */
  24081. ActionEvent.CreateNewFromScene = function (scene, evt) {
  24082. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  24083. };
  24084. return ActionEvent;
  24085. })();
  24086. BABYLON.ActionEvent = ActionEvent;
  24087. /**
  24088. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  24089. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  24090. */
  24091. var ActionManager = (function () {
  24092. function ActionManager(scene) {
  24093. // Members
  24094. this.actions = new Array();
  24095. this._scene = scene;
  24096. scene._actionManagers.push(this);
  24097. }
  24098. Object.defineProperty(ActionManager, "NothingTrigger", {
  24099. get: function () {
  24100. return ActionManager._NothingTrigger;
  24101. },
  24102. enumerable: true,
  24103. configurable: true
  24104. });
  24105. Object.defineProperty(ActionManager, "OnPickTrigger", {
  24106. get: function () {
  24107. return ActionManager._OnPickTrigger;
  24108. },
  24109. enumerable: true,
  24110. configurable: true
  24111. });
  24112. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  24113. get: function () {
  24114. return ActionManager._OnLeftPickTrigger;
  24115. },
  24116. enumerable: true,
  24117. configurable: true
  24118. });
  24119. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  24120. get: function () {
  24121. return ActionManager._OnRightPickTrigger;
  24122. },
  24123. enumerable: true,
  24124. configurable: true
  24125. });
  24126. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  24127. get: function () {
  24128. return ActionManager._OnCenterPickTrigger;
  24129. },
  24130. enumerable: true,
  24131. configurable: true
  24132. });
  24133. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  24134. get: function () {
  24135. return ActionManager._OnPointerOverTrigger;
  24136. },
  24137. enumerable: true,
  24138. configurable: true
  24139. });
  24140. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  24141. get: function () {
  24142. return ActionManager._OnPointerOutTrigger;
  24143. },
  24144. enumerable: true,
  24145. configurable: true
  24146. });
  24147. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  24148. get: function () {
  24149. return ActionManager._OnEveryFrameTrigger;
  24150. },
  24151. enumerable: true,
  24152. configurable: true
  24153. });
  24154. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  24155. get: function () {
  24156. return ActionManager._OnIntersectionEnterTrigger;
  24157. },
  24158. enumerable: true,
  24159. configurable: true
  24160. });
  24161. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  24162. get: function () {
  24163. return ActionManager._OnIntersectionExitTrigger;
  24164. },
  24165. enumerable: true,
  24166. configurable: true
  24167. });
  24168. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  24169. get: function () {
  24170. return ActionManager._OnKeyDownTrigger;
  24171. },
  24172. enumerable: true,
  24173. configurable: true
  24174. });
  24175. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  24176. get: function () {
  24177. return ActionManager._OnKeyUpTrigger;
  24178. },
  24179. enumerable: true,
  24180. configurable: true
  24181. });
  24182. // Methods
  24183. ActionManager.prototype.dispose = function () {
  24184. var index = this._scene._actionManagers.indexOf(this);
  24185. if (index > -1) {
  24186. this._scene._actionManagers.splice(index, 1);
  24187. }
  24188. };
  24189. ActionManager.prototype.getScene = function () {
  24190. return this._scene;
  24191. };
  24192. /**
  24193. * Does this action manager handles actions of any of the given triggers
  24194. * @param {number[]} triggers - the triggers to be tested
  24195. * @return {boolean} whether one (or more) of the triggers is handeled
  24196. */
  24197. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  24198. for (var index = 0; index < this.actions.length; index++) {
  24199. var action = this.actions[index];
  24200. if (triggers.indexOf(action.trigger) > -1) {
  24201. return true;
  24202. }
  24203. }
  24204. return false;
  24205. };
  24206. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  24207. /**
  24208. * Does this action manager has pointer triggers
  24209. * @return {boolean} whether or not it has pointer triggers
  24210. */
  24211. get: function () {
  24212. for (var index = 0; index < this.actions.length; index++) {
  24213. var action = this.actions[index];
  24214. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  24215. return true;
  24216. }
  24217. }
  24218. return false;
  24219. },
  24220. enumerable: true,
  24221. configurable: true
  24222. });
  24223. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  24224. /**
  24225. * Does this action manager has pick triggers
  24226. * @return {boolean} whether or not it has pick triggers
  24227. */
  24228. get: function () {
  24229. for (var index = 0; index < this.actions.length; index++) {
  24230. var action = this.actions[index];
  24231. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnCenterPickTrigger) {
  24232. return true;
  24233. }
  24234. }
  24235. return false;
  24236. },
  24237. enumerable: true,
  24238. configurable: true
  24239. });
  24240. /**
  24241. * Registers an action to this action manager
  24242. * @param {BABYLON.Action} action - the action to be registered
  24243. * @return {BABYLON.Action} the action amended (prepared) after registration
  24244. */
  24245. ActionManager.prototype.registerAction = function (action) {
  24246. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  24247. if (this.getScene().actionManager !== this) {
  24248. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  24249. return null;
  24250. }
  24251. }
  24252. this.actions.push(action);
  24253. action._actionManager = this;
  24254. action._prepare();
  24255. return action;
  24256. };
  24257. /**
  24258. * Process a specific trigger
  24259. * @param {number} trigger - the trigger to process
  24260. * @param evt {BABYLON.ActionEvent} the event details to be processed
  24261. */
  24262. ActionManager.prototype.processTrigger = function (trigger, evt) {
  24263. for (var index = 0; index < this.actions.length; index++) {
  24264. var action = this.actions[index];
  24265. if (action.trigger === trigger) {
  24266. if (trigger === ActionManager.OnKeyUpTrigger || trigger === ActionManager.OnKeyDownTrigger) {
  24267. var parameter = action.getTriggerParameter();
  24268. if (parameter) {
  24269. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  24270. var actualkey = String.fromCharCode(unicode).toLowerCase();
  24271. if (actualkey !== parameter.toLowerCase()) {
  24272. continue;
  24273. }
  24274. }
  24275. }
  24276. action._executeCurrent(evt);
  24277. }
  24278. }
  24279. };
  24280. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  24281. var properties = propertyPath.split(".");
  24282. for (var index = 0; index < properties.length - 1; index++) {
  24283. target = target[properties[index]];
  24284. }
  24285. return target;
  24286. };
  24287. ActionManager.prototype._getProperty = function (propertyPath) {
  24288. var properties = propertyPath.split(".");
  24289. return properties[properties.length - 1];
  24290. };
  24291. // Statics
  24292. ActionManager._NothingTrigger = 0;
  24293. ActionManager._OnPickTrigger = 1;
  24294. ActionManager._OnLeftPickTrigger = 2;
  24295. ActionManager._OnRightPickTrigger = 3;
  24296. ActionManager._OnCenterPickTrigger = 4;
  24297. ActionManager._OnPointerOverTrigger = 5;
  24298. ActionManager._OnPointerOutTrigger = 6;
  24299. ActionManager._OnEveryFrameTrigger = 7;
  24300. ActionManager._OnIntersectionEnterTrigger = 8;
  24301. ActionManager._OnIntersectionExitTrigger = 9;
  24302. ActionManager._OnKeyDownTrigger = 10;
  24303. ActionManager._OnKeyUpTrigger = 11;
  24304. return ActionManager;
  24305. })();
  24306. BABYLON.ActionManager = ActionManager;
  24307. })(BABYLON || (BABYLON = {}));
  24308. //# sourceMappingURL=babylon.actionManager.js.map
  24309. var BABYLON;
  24310. (function (BABYLON) {
  24311. var InterpolateValueAction = (function (_super) {
  24312. __extends(InterpolateValueAction, _super);
  24313. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations) {
  24314. if (duration === void 0) { duration = 1000; }
  24315. _super.call(this, triggerOptions, condition);
  24316. this.propertyPath = propertyPath;
  24317. this.value = value;
  24318. this.duration = duration;
  24319. this.stopOtherAnimations = stopOtherAnimations;
  24320. this._target = target;
  24321. }
  24322. InterpolateValueAction.prototype._prepare = function () {
  24323. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  24324. this._property = this._getProperty(this.propertyPath);
  24325. };
  24326. InterpolateValueAction.prototype.execute = function () {
  24327. var scene = this._actionManager.getScene();
  24328. var keys = [
  24329. {
  24330. frame: 0,
  24331. value: this._target[this._property]
  24332. },
  24333. {
  24334. frame: 100,
  24335. value: this.value
  24336. }
  24337. ];
  24338. var dataType;
  24339. if (typeof this.value === "number") {
  24340. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  24341. }
  24342. else if (this.value instanceof BABYLON.Color3) {
  24343. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  24344. }
  24345. else if (this.value instanceof BABYLON.Vector3) {
  24346. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  24347. }
  24348. else if (this.value instanceof BABYLON.Matrix) {
  24349. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  24350. }
  24351. else if (this.value instanceof BABYLON.Quaternion) {
  24352. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  24353. }
  24354. else {
  24355. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  24356. return;
  24357. }
  24358. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  24359. animation.setKeys(keys);
  24360. if (this.stopOtherAnimations) {
  24361. scene.stopAnimation(this._target);
  24362. }
  24363. scene.beginDirectAnimation(this._target, [animation], 0, 100);
  24364. };
  24365. return InterpolateValueAction;
  24366. })(BABYLON.Action);
  24367. BABYLON.InterpolateValueAction = InterpolateValueAction;
  24368. })(BABYLON || (BABYLON = {}));
  24369. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  24370. var BABYLON;
  24371. (function (BABYLON) {
  24372. var SwitchBooleanAction = (function (_super) {
  24373. __extends(SwitchBooleanAction, _super);
  24374. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  24375. _super.call(this, triggerOptions, condition);
  24376. this.propertyPath = propertyPath;
  24377. this._target = target;
  24378. }
  24379. SwitchBooleanAction.prototype._prepare = function () {
  24380. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  24381. this._property = this._getProperty(this.propertyPath);
  24382. };
  24383. SwitchBooleanAction.prototype.execute = function () {
  24384. this._target[this._property] = !this._target[this._property];
  24385. };
  24386. return SwitchBooleanAction;
  24387. })(BABYLON.Action);
  24388. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  24389. var SetStateAction = (function (_super) {
  24390. __extends(SetStateAction, _super);
  24391. function SetStateAction(triggerOptions, target, value, condition) {
  24392. _super.call(this, triggerOptions, condition);
  24393. this.value = value;
  24394. this._target = target;
  24395. }
  24396. SetStateAction.prototype.execute = function () {
  24397. this._target.state = this.value;
  24398. };
  24399. return SetStateAction;
  24400. })(BABYLON.Action);
  24401. BABYLON.SetStateAction = SetStateAction;
  24402. var SetValueAction = (function (_super) {
  24403. __extends(SetValueAction, _super);
  24404. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  24405. _super.call(this, triggerOptions, condition);
  24406. this.propertyPath = propertyPath;
  24407. this.value = value;
  24408. this._target = target;
  24409. }
  24410. SetValueAction.prototype._prepare = function () {
  24411. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  24412. this._property = this._getProperty(this.propertyPath);
  24413. };
  24414. SetValueAction.prototype.execute = function () {
  24415. this._target[this._property] = this.value;
  24416. };
  24417. return SetValueAction;
  24418. })(BABYLON.Action);
  24419. BABYLON.SetValueAction = SetValueAction;
  24420. var IncrementValueAction = (function (_super) {
  24421. __extends(IncrementValueAction, _super);
  24422. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  24423. _super.call(this, triggerOptions, condition);
  24424. this.propertyPath = propertyPath;
  24425. this.value = value;
  24426. this._target = target;
  24427. }
  24428. IncrementValueAction.prototype._prepare = function () {
  24429. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  24430. this._property = this._getProperty(this.propertyPath);
  24431. if (typeof this._target[this._property] !== "number") {
  24432. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  24433. }
  24434. };
  24435. IncrementValueAction.prototype.execute = function () {
  24436. this._target[this._property] += this.value;
  24437. };
  24438. return IncrementValueAction;
  24439. })(BABYLON.Action);
  24440. BABYLON.IncrementValueAction = IncrementValueAction;
  24441. var PlayAnimationAction = (function (_super) {
  24442. __extends(PlayAnimationAction, _super);
  24443. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  24444. _super.call(this, triggerOptions, condition);
  24445. this.from = from;
  24446. this.to = to;
  24447. this.loop = loop;
  24448. this._target = target;
  24449. }
  24450. PlayAnimationAction.prototype._prepare = function () {
  24451. };
  24452. PlayAnimationAction.prototype.execute = function () {
  24453. var scene = this._actionManager.getScene();
  24454. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  24455. };
  24456. return PlayAnimationAction;
  24457. })(BABYLON.Action);
  24458. BABYLON.PlayAnimationAction = PlayAnimationAction;
  24459. var StopAnimationAction = (function (_super) {
  24460. __extends(StopAnimationAction, _super);
  24461. function StopAnimationAction(triggerOptions, target, condition) {
  24462. _super.call(this, triggerOptions, condition);
  24463. this._target = target;
  24464. }
  24465. StopAnimationAction.prototype._prepare = function () {
  24466. };
  24467. StopAnimationAction.prototype.execute = function () {
  24468. var scene = this._actionManager.getScene();
  24469. scene.stopAnimation(this._target);
  24470. };
  24471. return StopAnimationAction;
  24472. })(BABYLON.Action);
  24473. BABYLON.StopAnimationAction = StopAnimationAction;
  24474. var DoNothingAction = (function (_super) {
  24475. __extends(DoNothingAction, _super);
  24476. function DoNothingAction(triggerOptions, condition) {
  24477. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  24478. _super.call(this, triggerOptions, condition);
  24479. }
  24480. DoNothingAction.prototype.execute = function () {
  24481. };
  24482. return DoNothingAction;
  24483. })(BABYLON.Action);
  24484. BABYLON.DoNothingAction = DoNothingAction;
  24485. var CombineAction = (function (_super) {
  24486. __extends(CombineAction, _super);
  24487. function CombineAction(triggerOptions, children, condition) {
  24488. _super.call(this, triggerOptions, condition);
  24489. this.children = children;
  24490. }
  24491. CombineAction.prototype._prepare = function () {
  24492. for (var index = 0; index < this.children.length; index++) {
  24493. this.children[index]._actionManager = this._actionManager;
  24494. this.children[index]._prepare();
  24495. }
  24496. };
  24497. CombineAction.prototype.execute = function (evt) {
  24498. for (var index = 0; index < this.children.length; index++) {
  24499. this.children[index].execute(evt);
  24500. }
  24501. };
  24502. return CombineAction;
  24503. })(BABYLON.Action);
  24504. BABYLON.CombineAction = CombineAction;
  24505. var ExecuteCodeAction = (function (_super) {
  24506. __extends(ExecuteCodeAction, _super);
  24507. function ExecuteCodeAction(triggerOptions, func, condition) {
  24508. _super.call(this, triggerOptions, condition);
  24509. this.func = func;
  24510. }
  24511. ExecuteCodeAction.prototype.execute = function (evt) {
  24512. this.func(evt);
  24513. };
  24514. return ExecuteCodeAction;
  24515. })(BABYLON.Action);
  24516. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  24517. var SetParentAction = (function (_super) {
  24518. __extends(SetParentAction, _super);
  24519. function SetParentAction(triggerOptions, target, parent, condition) {
  24520. _super.call(this, triggerOptions, condition);
  24521. this._target = target;
  24522. this._parent = parent;
  24523. }
  24524. SetParentAction.prototype._prepare = function () {
  24525. };
  24526. SetParentAction.prototype.execute = function () {
  24527. if (this._target.parent === this._parent) {
  24528. return;
  24529. }
  24530. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  24531. invertParentWorldMatrix.invert();
  24532. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  24533. this._target.parent = this._parent;
  24534. };
  24535. return SetParentAction;
  24536. })(BABYLON.Action);
  24537. BABYLON.SetParentAction = SetParentAction;
  24538. var PlaySoundAction = (function (_super) {
  24539. __extends(PlaySoundAction, _super);
  24540. function PlaySoundAction(triggerOptions, sound, condition) {
  24541. _super.call(this, triggerOptions, condition);
  24542. this._sound = sound;
  24543. }
  24544. PlaySoundAction.prototype._prepare = function () {
  24545. };
  24546. PlaySoundAction.prototype.execute = function () {
  24547. if (this._sound !== undefined)
  24548. this._sound.play();
  24549. };
  24550. return PlaySoundAction;
  24551. })(BABYLON.Action);
  24552. BABYLON.PlaySoundAction = PlaySoundAction;
  24553. var StopSoundAction = (function (_super) {
  24554. __extends(StopSoundAction, _super);
  24555. function StopSoundAction(triggerOptions, sound, condition) {
  24556. _super.call(this, triggerOptions, condition);
  24557. this._sound = sound;
  24558. }
  24559. StopSoundAction.prototype._prepare = function () {
  24560. };
  24561. StopSoundAction.prototype.execute = function () {
  24562. if (this._sound !== undefined)
  24563. this._sound.stop();
  24564. };
  24565. return StopSoundAction;
  24566. })(BABYLON.Action);
  24567. BABYLON.StopSoundAction = StopSoundAction;
  24568. })(BABYLON || (BABYLON = {}));
  24569. //# sourceMappingURL=babylon.directActions.js.map
  24570. var BABYLON;
  24571. (function (BABYLON) {
  24572. var Geometry = (function () {
  24573. function Geometry(id, scene, vertexData, updatable, mesh) {
  24574. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  24575. this._totalVertices = 0;
  24576. this._indices = [];
  24577. this.id = id;
  24578. this._engine = scene.getEngine();
  24579. this._meshes = [];
  24580. this._scene = scene;
  24581. // vertexData
  24582. if (vertexData) {
  24583. this.setAllVerticesData(vertexData, updatable);
  24584. }
  24585. else {
  24586. this._totalVertices = 0;
  24587. this._indices = [];
  24588. }
  24589. // applyToMesh
  24590. if (mesh) {
  24591. this.applyToMesh(mesh);
  24592. mesh.computeWorldMatrix(true);
  24593. }
  24594. }
  24595. Geometry.prototype.getScene = function () {
  24596. return this._scene;
  24597. };
  24598. Geometry.prototype.getEngine = function () {
  24599. return this._engine;
  24600. };
  24601. Geometry.prototype.isReady = function () {
  24602. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  24603. };
  24604. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  24605. vertexData.applyToGeometry(this, updatable);
  24606. };
  24607. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  24608. this._vertexBuffers = this._vertexBuffers || {};
  24609. if (this._vertexBuffers[kind]) {
  24610. this._vertexBuffers[kind].dispose();
  24611. }
  24612. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  24613. if (kind === BABYLON.VertexBuffer.PositionKind) {
  24614. stride = this._vertexBuffers[kind].getStrideSize();
  24615. this._totalVertices = data.length / stride;
  24616. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  24617. var meshes = this._meshes;
  24618. var numOfMeshes = meshes.length;
  24619. for (var index = 0; index < numOfMeshes; index++) {
  24620. var mesh = meshes[index];
  24621. mesh._resetPointsArrayCache();
  24622. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  24623. mesh._createGlobalSubMesh();
  24624. mesh.computeWorldMatrix(true);
  24625. }
  24626. }
  24627. };
  24628. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  24629. var vertexBuffer = this.getVertexBuffer(kind);
  24630. if (!vertexBuffer) {
  24631. return;
  24632. }
  24633. vertexBuffer.updateDirectly(data, offset);
  24634. };
  24635. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  24636. var vertexBuffer = this.getVertexBuffer(kind);
  24637. if (!vertexBuffer) {
  24638. return;
  24639. }
  24640. vertexBuffer.update(data);
  24641. if (kind === BABYLON.VertexBuffer.PositionKind) {
  24642. var extend;
  24643. var stride = vertexBuffer.getStrideSize();
  24644. this._totalVertices = data.length / stride;
  24645. if (updateExtends) {
  24646. extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  24647. }
  24648. var meshes = this._meshes;
  24649. var numOfMeshes = meshes.length;
  24650. for (var index = 0; index < numOfMeshes; index++) {
  24651. var mesh = meshes[index];
  24652. mesh._resetPointsArrayCache();
  24653. if (updateExtends) {
  24654. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  24655. }
  24656. }
  24657. }
  24658. };
  24659. Geometry.prototype.getTotalVertices = function () {
  24660. if (!this.isReady()) {
  24661. return 0;
  24662. }
  24663. return this._totalVertices;
  24664. };
  24665. Geometry.prototype.getVerticesData = function (kind) {
  24666. var vertexBuffer = this.getVertexBuffer(kind);
  24667. if (!vertexBuffer) {
  24668. return null;
  24669. }
  24670. return vertexBuffer.getData();
  24671. };
  24672. Geometry.prototype.getVertexBuffer = function (kind) {
  24673. if (!this.isReady()) {
  24674. return null;
  24675. }
  24676. return this._vertexBuffers[kind];
  24677. };
  24678. Geometry.prototype.getVertexBuffers = function () {
  24679. if (!this.isReady()) {
  24680. return null;
  24681. }
  24682. return this._vertexBuffers;
  24683. };
  24684. Geometry.prototype.isVerticesDataPresent = function (kind) {
  24685. if (!this._vertexBuffers) {
  24686. if (this._delayInfo) {
  24687. return this._delayInfo.indexOf(kind) !== -1;
  24688. }
  24689. return false;
  24690. }
  24691. return this._vertexBuffers[kind] !== undefined;
  24692. };
  24693. Geometry.prototype.getVerticesDataKinds = function () {
  24694. var result = [];
  24695. if (!this._vertexBuffers && this._delayInfo) {
  24696. for (var kind in this._delayInfo) {
  24697. result.push(kind);
  24698. }
  24699. }
  24700. else {
  24701. for (kind in this._vertexBuffers) {
  24702. result.push(kind);
  24703. }
  24704. }
  24705. return result;
  24706. };
  24707. Geometry.prototype.setIndices = function (indices, totalVertices) {
  24708. if (this._indexBuffer) {
  24709. this._engine._releaseBuffer(this._indexBuffer);
  24710. }
  24711. this._indices = indices;
  24712. if (this._meshes.length !== 0 && this._indices) {
  24713. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  24714. }
  24715. if (totalVertices !== undefined) {
  24716. this._totalVertices = totalVertices;
  24717. }
  24718. var meshes = this._meshes;
  24719. var numOfMeshes = meshes.length;
  24720. for (var index = 0; index < numOfMeshes; index++) {
  24721. meshes[index]._createGlobalSubMesh();
  24722. }
  24723. };
  24724. Geometry.prototype.getTotalIndices = function () {
  24725. if (!this.isReady()) {
  24726. return 0;
  24727. }
  24728. return this._indices.length;
  24729. };
  24730. Geometry.prototype.getIndices = function () {
  24731. if (!this.isReady()) {
  24732. return null;
  24733. }
  24734. return this._indices;
  24735. };
  24736. Geometry.prototype.getIndexBuffer = function () {
  24737. if (!this.isReady()) {
  24738. return null;
  24739. }
  24740. return this._indexBuffer;
  24741. };
  24742. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  24743. var meshes = this._meshes;
  24744. var index = meshes.indexOf(mesh);
  24745. if (index === -1) {
  24746. return;
  24747. }
  24748. for (var kind in this._vertexBuffers) {
  24749. this._vertexBuffers[kind].dispose();
  24750. }
  24751. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  24752. this._indexBuffer = null;
  24753. }
  24754. meshes.splice(index, 1);
  24755. mesh._geometry = null;
  24756. if (meshes.length === 0 && shouldDispose) {
  24757. this.dispose();
  24758. }
  24759. };
  24760. Geometry.prototype.applyToMesh = function (mesh) {
  24761. if (mesh._geometry === this) {
  24762. return;
  24763. }
  24764. var previousGeometry = mesh._geometry;
  24765. if (previousGeometry) {
  24766. previousGeometry.releaseForMesh(mesh);
  24767. }
  24768. var meshes = this._meshes;
  24769. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  24770. mesh._geometry = this;
  24771. this._scene.pushGeometry(this);
  24772. meshes.push(mesh);
  24773. if (this.isReady()) {
  24774. this._applyToMesh(mesh);
  24775. }
  24776. else {
  24777. mesh._boundingInfo = this._boundingInfo;
  24778. }
  24779. };
  24780. Geometry.prototype._applyToMesh = function (mesh) {
  24781. var numOfMeshes = this._meshes.length;
  24782. for (var kind in this._vertexBuffers) {
  24783. if (numOfMeshes === 1) {
  24784. this._vertexBuffers[kind].create();
  24785. }
  24786. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  24787. if (kind === BABYLON.VertexBuffer.PositionKind) {
  24788. mesh._resetPointsArrayCache();
  24789. var extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  24790. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  24791. mesh._createGlobalSubMesh();
  24792. //bounding info was just created again, world matrix should be applied again.
  24793. mesh._updateBoundingInfo();
  24794. }
  24795. }
  24796. // indexBuffer
  24797. if (numOfMeshes === 1 && this._indices) {
  24798. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  24799. }
  24800. if (this._indexBuffer) {
  24801. this._indexBuffer.references = numOfMeshes;
  24802. }
  24803. };
  24804. Geometry.prototype.load = function (scene, onLoaded) {
  24805. var _this = this;
  24806. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  24807. return;
  24808. }
  24809. if (this.isReady()) {
  24810. if (onLoaded) {
  24811. onLoaded();
  24812. }
  24813. return;
  24814. }
  24815. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  24816. scene._addPendingData(this);
  24817. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  24818. _this._delayLoadingFunction(JSON.parse(data), _this);
  24819. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  24820. _this._delayInfo = [];
  24821. scene._removePendingData(_this);
  24822. var meshes = _this._meshes;
  24823. var numOfMeshes = meshes.length;
  24824. for (var index = 0; index < numOfMeshes; index++) {
  24825. _this._applyToMesh(meshes[index]);
  24826. }
  24827. if (onLoaded) {
  24828. onLoaded();
  24829. }
  24830. }, function () {
  24831. }, scene.database);
  24832. };
  24833. Geometry.prototype.dispose = function () {
  24834. var meshes = this._meshes;
  24835. var numOfMeshes = meshes.length;
  24836. var index;
  24837. for (index = 0; index < numOfMeshes; index++) {
  24838. this.releaseForMesh(meshes[index]);
  24839. }
  24840. this._meshes = [];
  24841. for (var kind in this._vertexBuffers) {
  24842. this._vertexBuffers[kind].dispose();
  24843. }
  24844. this._vertexBuffers = [];
  24845. this._totalVertices = 0;
  24846. if (this._indexBuffer) {
  24847. this._engine._releaseBuffer(this._indexBuffer);
  24848. }
  24849. this._indexBuffer = null;
  24850. this._indices = [];
  24851. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  24852. this.delayLoadingFile = null;
  24853. this._delayLoadingFunction = null;
  24854. this._delayInfo = [];
  24855. this._boundingInfo = null; // todo: .dispose()
  24856. var geometries = this._scene.getGeometries();
  24857. index = geometries.indexOf(this);
  24858. if (index > -1) {
  24859. geometries.splice(index, 1);
  24860. }
  24861. };
  24862. Geometry.prototype.copy = function (id) {
  24863. var vertexData = new BABYLON.VertexData();
  24864. vertexData.indices = [];
  24865. var indices = this.getIndices();
  24866. for (var index = 0; index < indices.length; index++) {
  24867. vertexData.indices.push(indices[index]);
  24868. }
  24869. var updatable = false;
  24870. var stopChecking = false;
  24871. for (var kind in this._vertexBuffers) {
  24872. // using slice() to make a copy of the array and not just reference it
  24873. vertexData.set(this.getVerticesData(kind).slice(0), kind);
  24874. if (!stopChecking) {
  24875. updatable = this.getVertexBuffer(kind).isUpdatable();
  24876. stopChecking = !updatable;
  24877. }
  24878. }
  24879. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  24880. geometry.delayLoadState = this.delayLoadState;
  24881. geometry.delayLoadingFile = this.delayLoadingFile;
  24882. geometry._delayLoadingFunction = this._delayLoadingFunction;
  24883. for (kind in this._delayInfo) {
  24884. geometry._delayInfo = geometry._delayInfo || [];
  24885. geometry._delayInfo.push(kind);
  24886. }
  24887. // Bounding info
  24888. var extend = BABYLON.Tools.ExtractMinAndMax(this.getVerticesData(BABYLON.VertexBuffer.PositionKind), 0, this.getTotalVertices());
  24889. geometry._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  24890. return geometry;
  24891. };
  24892. // Statics
  24893. Geometry.ExtractFromMesh = function (mesh, id) {
  24894. var geometry = mesh._geometry;
  24895. if (!geometry) {
  24896. return null;
  24897. }
  24898. return geometry.copy(id);
  24899. };
  24900. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  24901. // be aware Math.random() could cause collisions
  24902. Geometry.RandomId = function () {
  24903. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  24904. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  24905. return v.toString(16);
  24906. });
  24907. };
  24908. return Geometry;
  24909. })();
  24910. BABYLON.Geometry = Geometry;
  24911. /////// Primitives //////////////////////////////////////////////
  24912. var Geometry;
  24913. (function (Geometry) {
  24914. var Primitives;
  24915. (function (Primitives) {
  24916. /// Abstract class
  24917. var _Primitive = (function (_super) {
  24918. __extends(_Primitive, _super);
  24919. function _Primitive(id, scene, vertexData, canBeRegenerated, mesh) {
  24920. this._beingRegenerated = true;
  24921. this._canBeRegenerated = canBeRegenerated;
  24922. _super.call(this, id, scene, vertexData, false, mesh); // updatable = false to be sure not to update vertices
  24923. this._beingRegenerated = false;
  24924. }
  24925. _Primitive.prototype.canBeRegenerated = function () {
  24926. return this._canBeRegenerated;
  24927. };
  24928. _Primitive.prototype.regenerate = function () {
  24929. if (!this._canBeRegenerated) {
  24930. return;
  24931. }
  24932. this._beingRegenerated = true;
  24933. this.setAllVerticesData(this._regenerateVertexData(), false);
  24934. this._beingRegenerated = false;
  24935. };
  24936. _Primitive.prototype.asNewGeometry = function (id) {
  24937. return _super.prototype.copy.call(this, id);
  24938. };
  24939. // overrides
  24940. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  24941. if (!this._beingRegenerated) {
  24942. return;
  24943. }
  24944. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  24945. };
  24946. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  24947. if (!this._beingRegenerated) {
  24948. return;
  24949. }
  24950. _super.prototype.setVerticesData.call(this, kind, data, false);
  24951. };
  24952. // to override
  24953. // protected
  24954. _Primitive.prototype._regenerateVertexData = function () {
  24955. throw new Error("Abstract method");
  24956. };
  24957. _Primitive.prototype.copy = function (id) {
  24958. throw new Error("Must be overriden in sub-classes.");
  24959. };
  24960. return _Primitive;
  24961. })(Geometry);
  24962. Primitives._Primitive = _Primitive;
  24963. var Ribbon = (function (_super) {
  24964. __extends(Ribbon, _super);
  24965. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  24966. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  24967. this.pathArray = pathArray;
  24968. this.closeArray = closeArray;
  24969. this.closePath = closePath;
  24970. this.offset = offset;
  24971. this.side = side;
  24972. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  24973. }
  24974. Ribbon.prototype._regenerateVertexData = function () {
  24975. return BABYLON.VertexData.CreateRibbon(this.pathArray, this.closeArray, this.closePath, this.offset, this.side);
  24976. };
  24977. Ribbon.prototype.copy = function (id) {
  24978. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  24979. };
  24980. return Ribbon;
  24981. })(_Primitive);
  24982. Primitives.Ribbon = Ribbon;
  24983. var Box = (function (_super) {
  24984. __extends(Box, _super);
  24985. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  24986. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  24987. this.size = size;
  24988. this.side = side;
  24989. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  24990. }
  24991. Box.prototype._regenerateVertexData = function () {
  24992. return BABYLON.VertexData.CreateBox(this.size, this.side);
  24993. };
  24994. Box.prototype.copy = function (id) {
  24995. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  24996. };
  24997. return Box;
  24998. })(_Primitive);
  24999. Primitives.Box = Box;
  25000. var Sphere = (function (_super) {
  25001. __extends(Sphere, _super);
  25002. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  25003. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  25004. this.segments = segments;
  25005. this.diameter = diameter;
  25006. this.side = side;
  25007. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25008. }
  25009. Sphere.prototype._regenerateVertexData = function () {
  25010. return BABYLON.VertexData.CreateSphere(this.segments, this.diameter, this.side);
  25011. };
  25012. Sphere.prototype.copy = function (id) {
  25013. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  25014. };
  25015. return Sphere;
  25016. })(_Primitive);
  25017. Primitives.Sphere = Sphere;
  25018. var Cylinder = (function (_super) {
  25019. __extends(Cylinder, _super);
  25020. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  25021. if (subdivisions === void 0) { subdivisions = 1; }
  25022. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  25023. this.height = height;
  25024. this.diameterTop = diameterTop;
  25025. this.diameterBottom = diameterBottom;
  25026. this.tessellation = tessellation;
  25027. this.subdivisions = subdivisions;
  25028. this.side = side;
  25029. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25030. }
  25031. Cylinder.prototype._regenerateVertexData = function () {
  25032. return BABYLON.VertexData.CreateCylinder(this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.side);
  25033. };
  25034. Cylinder.prototype.copy = function (id) {
  25035. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  25036. };
  25037. return Cylinder;
  25038. })(_Primitive);
  25039. Primitives.Cylinder = Cylinder;
  25040. var Torus = (function (_super) {
  25041. __extends(Torus, _super);
  25042. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  25043. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  25044. this.diameter = diameter;
  25045. this.thickness = thickness;
  25046. this.tessellation = tessellation;
  25047. this.side = side;
  25048. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25049. }
  25050. Torus.prototype._regenerateVertexData = function () {
  25051. return BABYLON.VertexData.CreateTorus(this.diameter, this.thickness, this.tessellation, this.side);
  25052. };
  25053. Torus.prototype.copy = function (id) {
  25054. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  25055. };
  25056. return Torus;
  25057. })(_Primitive);
  25058. Primitives.Torus = Torus;
  25059. var Ground = (function (_super) {
  25060. __extends(Ground, _super);
  25061. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  25062. this.width = width;
  25063. this.height = height;
  25064. this.subdivisions = subdivisions;
  25065. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25066. }
  25067. Ground.prototype._regenerateVertexData = function () {
  25068. return BABYLON.VertexData.CreateGround(this.width, this.height, this.subdivisions);
  25069. };
  25070. Ground.prototype.copy = function (id) {
  25071. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  25072. };
  25073. return Ground;
  25074. })(_Primitive);
  25075. Primitives.Ground = Ground;
  25076. var TiledGround = (function (_super) {
  25077. __extends(TiledGround, _super);
  25078. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  25079. this.xmin = xmin;
  25080. this.zmin = zmin;
  25081. this.xmax = xmax;
  25082. this.zmax = zmax;
  25083. this.subdivisions = subdivisions;
  25084. this.precision = precision;
  25085. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25086. }
  25087. TiledGround.prototype._regenerateVertexData = function () {
  25088. return BABYLON.VertexData.CreateTiledGround(this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision);
  25089. };
  25090. TiledGround.prototype.copy = function (id) {
  25091. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  25092. };
  25093. return TiledGround;
  25094. })(_Primitive);
  25095. Primitives.TiledGround = TiledGround;
  25096. var Plane = (function (_super) {
  25097. __extends(Plane, _super);
  25098. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  25099. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  25100. this.size = size;
  25101. this.side = side;
  25102. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25103. }
  25104. Plane.prototype._regenerateVertexData = function () {
  25105. return BABYLON.VertexData.CreatePlane(this.size, this.side);
  25106. };
  25107. Plane.prototype.copy = function (id) {
  25108. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  25109. };
  25110. return Plane;
  25111. })(_Primitive);
  25112. Primitives.Plane = Plane;
  25113. var TorusKnot = (function (_super) {
  25114. __extends(TorusKnot, _super);
  25115. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  25116. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  25117. this.radius = radius;
  25118. this.tube = tube;
  25119. this.radialSegments = radialSegments;
  25120. this.tubularSegments = tubularSegments;
  25121. this.p = p;
  25122. this.q = q;
  25123. this.side = side;
  25124. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25125. }
  25126. TorusKnot.prototype._regenerateVertexData = function () {
  25127. return BABYLON.VertexData.CreateTorusKnot(this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.side);
  25128. };
  25129. TorusKnot.prototype.copy = function (id) {
  25130. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  25131. };
  25132. return TorusKnot;
  25133. })(_Primitive);
  25134. Primitives.TorusKnot = TorusKnot;
  25135. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  25136. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  25137. })(BABYLON || (BABYLON = {}));
  25138. //# sourceMappingURL=babylon.geometry.js.map
  25139. var BABYLON;
  25140. (function (BABYLON) {
  25141. var Gamepads = (function () {
  25142. function Gamepads(ongamedpadconnected) {
  25143. var _this = this;
  25144. this.babylonGamepads = [];
  25145. this.oneGamepadConnected = false;
  25146. this.isMonitoring = false;
  25147. this.gamepadEventSupported = 'GamepadEvent' in window;
  25148. this.gamepadSupportAvailable = (navigator.getGamepads || !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  25149. 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=";
  25150. this._callbackGamepadConnected = ongamedpadconnected;
  25151. if (this.gamepadSupportAvailable) {
  25152. // Checking if the gamepad connected event is supported (like in Firefox)
  25153. if (this.gamepadEventSupported) {
  25154. window.addEventListener('gamepadconnected', function (evt) {
  25155. _this._onGamepadConnected(evt);
  25156. }, false);
  25157. window.addEventListener('gamepaddisconnected', function (evt) {
  25158. _this._onGamepadDisconnected(evt);
  25159. }, false);
  25160. }
  25161. else {
  25162. this._startMonitoringGamepads();
  25163. }
  25164. if (!this.oneGamepadConnected) {
  25165. this._insertGamepadDOMInstructions();
  25166. }
  25167. }
  25168. else {
  25169. this._insertGamepadDOMNotSupported();
  25170. }
  25171. }
  25172. Gamepads.prototype._insertGamepadDOMInstructions = function () {
  25173. Gamepads.gamepadDOMInfo = document.createElement("div");
  25174. var buttonAImage = document.createElement("img");
  25175. buttonAImage.src = this.buttonADataURL;
  25176. var spanMessage = document.createElement("span");
  25177. spanMessage.innerHTML = "<strong>to activate gamepad</strong>";
  25178. Gamepads.gamepadDOMInfo.appendChild(buttonAImage);
  25179. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  25180. Gamepads.gamepadDOMInfo.style.position = "absolute";
  25181. Gamepads.gamepadDOMInfo.style.width = "100%";
  25182. Gamepads.gamepadDOMInfo.style.height = "48px";
  25183. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  25184. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  25185. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  25186. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  25187. buttonAImage.style.position = "relative";
  25188. buttonAImage.style.bottom = "8px";
  25189. spanMessage.style.position = "relative";
  25190. spanMessage.style.fontSize = "32px";
  25191. spanMessage.style.bottom = "32px";
  25192. spanMessage.style.color = "green";
  25193. document.body.appendChild(Gamepads.gamepadDOMInfo);
  25194. };
  25195. Gamepads.prototype._insertGamepadDOMNotSupported = function () {
  25196. Gamepads.gamepadDOMInfo = document.createElement("div");
  25197. var spanMessage = document.createElement("span");
  25198. spanMessage.innerHTML = "<strong>gamepad not supported</strong>";
  25199. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  25200. Gamepads.gamepadDOMInfo.style.position = "absolute";
  25201. Gamepads.gamepadDOMInfo.style.width = "100%";
  25202. Gamepads.gamepadDOMInfo.style.height = "40px";
  25203. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  25204. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  25205. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  25206. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  25207. spanMessage.style.position = "relative";
  25208. spanMessage.style.fontSize = "32px";
  25209. spanMessage.style.color = "red";
  25210. document.body.appendChild(Gamepads.gamepadDOMInfo);
  25211. };
  25212. Gamepads.prototype.dispose = function () {
  25213. if (Gamepads.gamepadDOMInfo) {
  25214. document.body.removeChild(Gamepads.gamepadDOMInfo);
  25215. }
  25216. };
  25217. Gamepads.prototype._onGamepadConnected = function (evt) {
  25218. var newGamepad = this._addNewGamepad(evt.gamepad);
  25219. if (this._callbackGamepadConnected)
  25220. this._callbackGamepadConnected(newGamepad);
  25221. this._startMonitoringGamepads();
  25222. };
  25223. Gamepads.prototype._addNewGamepad = function (gamepad) {
  25224. if (!this.oneGamepadConnected) {
  25225. this.oneGamepadConnected = true;
  25226. if (Gamepads.gamepadDOMInfo) {
  25227. document.body.removeChild(Gamepads.gamepadDOMInfo);
  25228. Gamepads.gamepadDOMInfo = null;
  25229. }
  25230. }
  25231. var newGamepad;
  25232. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  25233. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  25234. }
  25235. else {
  25236. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  25237. }
  25238. this.babylonGamepads.push(newGamepad);
  25239. return newGamepad;
  25240. };
  25241. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  25242. for (var i in this.babylonGamepads) {
  25243. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  25244. this.babylonGamepads.splice(i, 1);
  25245. break;
  25246. }
  25247. }
  25248. // If no gamepads are left, stop the polling loop.
  25249. if (this.babylonGamepads.length == 0) {
  25250. this._stopMonitoringGamepads();
  25251. }
  25252. };
  25253. Gamepads.prototype._startMonitoringGamepads = function () {
  25254. if (!this.isMonitoring) {
  25255. this.isMonitoring = true;
  25256. this._checkGamepadsStatus();
  25257. }
  25258. };
  25259. Gamepads.prototype._stopMonitoringGamepads = function () {
  25260. this.isMonitoring = false;
  25261. };
  25262. Gamepads.prototype._checkGamepadsStatus = function () {
  25263. var _this = this;
  25264. // updating gamepad objects
  25265. this._updateGamepadObjects();
  25266. for (var i in this.babylonGamepads) {
  25267. this.babylonGamepads[i].update();
  25268. }
  25269. if (this.isMonitoring) {
  25270. if (window.requestAnimationFrame) {
  25271. window.requestAnimationFrame(function () {
  25272. _this._checkGamepadsStatus();
  25273. });
  25274. }
  25275. else if (window.mozRequestAnimationFrame) {
  25276. window.mozRequestAnimationFrame(function () {
  25277. _this._checkGamepadsStatus();
  25278. });
  25279. }
  25280. else if (window.webkitRequestAnimationFrame) {
  25281. window.webkitRequestAnimationFrame(function () {
  25282. _this._checkGamepadsStatus();
  25283. });
  25284. }
  25285. }
  25286. };
  25287. // This function is called only on Chrome, which does not yet support
  25288. // connection/disconnection events, but requires you to monitor
  25289. // an array for changes.
  25290. Gamepads.prototype._updateGamepadObjects = function () {
  25291. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  25292. for (var i = 0; i < gamepads.length; i++) {
  25293. if (gamepads[i]) {
  25294. if (!(gamepads[i].index in this.babylonGamepads)) {
  25295. var newGamepad = this._addNewGamepad(gamepads[i]);
  25296. if (this._callbackGamepadConnected) {
  25297. this._callbackGamepadConnected(newGamepad);
  25298. }
  25299. }
  25300. else {
  25301. this.babylonGamepads[i].browserGamepad = gamepads[i];
  25302. }
  25303. }
  25304. }
  25305. };
  25306. return Gamepads;
  25307. })();
  25308. BABYLON.Gamepads = Gamepads;
  25309. var StickValues = (function () {
  25310. function StickValues(x, y) {
  25311. this.x = x;
  25312. this.y = y;
  25313. }
  25314. return StickValues;
  25315. })();
  25316. BABYLON.StickValues = StickValues;
  25317. var Gamepad = (function () {
  25318. function Gamepad(id, index, browserGamepad) {
  25319. this.id = id;
  25320. this.index = index;
  25321. this.browserGamepad = browserGamepad;
  25322. if (this.browserGamepad.axes.length >= 2) {
  25323. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  25324. }
  25325. if (this.browserGamepad.axes.length >= 4) {
  25326. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  25327. }
  25328. }
  25329. Gamepad.prototype.onleftstickchanged = function (callback) {
  25330. this._onleftstickchanged = callback;
  25331. };
  25332. Gamepad.prototype.onrightstickchanged = function (callback) {
  25333. this._onrightstickchanged = callback;
  25334. };
  25335. Object.defineProperty(Gamepad.prototype, "leftStick", {
  25336. get: function () {
  25337. return this._leftStick;
  25338. },
  25339. set: function (newValues) {
  25340. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  25341. this._onleftstickchanged(newValues);
  25342. }
  25343. this._leftStick = newValues;
  25344. },
  25345. enumerable: true,
  25346. configurable: true
  25347. });
  25348. Object.defineProperty(Gamepad.prototype, "rightStick", {
  25349. get: function () {
  25350. return this._rightStick;
  25351. },
  25352. set: function (newValues) {
  25353. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  25354. this._onrightstickchanged(newValues);
  25355. }
  25356. this._rightStick = newValues;
  25357. },
  25358. enumerable: true,
  25359. configurable: true
  25360. });
  25361. Gamepad.prototype.update = function () {
  25362. if (this._leftStick) {
  25363. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  25364. }
  25365. if (this._rightStick) {
  25366. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  25367. }
  25368. };
  25369. return Gamepad;
  25370. })();
  25371. BABYLON.Gamepad = Gamepad;
  25372. var GenericPad = (function (_super) {
  25373. __extends(GenericPad, _super);
  25374. function GenericPad(id, index, gamepad) {
  25375. _super.call(this, id, index, gamepad);
  25376. this.id = id;
  25377. this.index = index;
  25378. this.gamepad = gamepad;
  25379. this._buttons = new Array(gamepad.buttons.length);
  25380. }
  25381. GenericPad.prototype.onbuttondown = function (callback) {
  25382. this._onbuttondown = callback;
  25383. };
  25384. GenericPad.prototype.onbuttonup = function (callback) {
  25385. this._onbuttonup = callback;
  25386. };
  25387. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  25388. if (newValue !== currentValue) {
  25389. if (this._onbuttondown && newValue === 1) {
  25390. this._onbuttondown(buttonIndex);
  25391. }
  25392. if (this._onbuttonup && newValue === 0) {
  25393. this._onbuttonup(buttonIndex);
  25394. }
  25395. }
  25396. return newValue;
  25397. };
  25398. GenericPad.prototype.update = function () {
  25399. _super.prototype.update.call(this);
  25400. for (var index = 0; index < this._buttons.length; index++) {
  25401. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  25402. }
  25403. };
  25404. return GenericPad;
  25405. })(Gamepad);
  25406. BABYLON.GenericPad = GenericPad;
  25407. (function (Xbox360Button) {
  25408. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  25409. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  25410. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  25411. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  25412. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  25413. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  25414. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  25415. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  25416. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  25417. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  25418. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  25419. var Xbox360Button = BABYLON.Xbox360Button;
  25420. (function (Xbox360Dpad) {
  25421. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  25422. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  25423. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  25424. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  25425. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  25426. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  25427. var Xbox360Pad = (function (_super) {
  25428. __extends(Xbox360Pad, _super);
  25429. function Xbox360Pad() {
  25430. _super.apply(this, arguments);
  25431. this._leftTrigger = 0;
  25432. this._rightTrigger = 0;
  25433. this._buttonA = 0;
  25434. this._buttonB = 0;
  25435. this._buttonX = 0;
  25436. this._buttonY = 0;
  25437. this._buttonBack = 0;
  25438. this._buttonStart = 0;
  25439. this._buttonLB = 0;
  25440. this._buttonRB = 0;
  25441. this._buttonLeftStick = 0;
  25442. this._buttonRightStick = 0;
  25443. this._dPadUp = 0;
  25444. this._dPadDown = 0;
  25445. this._dPadLeft = 0;
  25446. this._dPadRight = 0;
  25447. }
  25448. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  25449. this._onlefttriggerchanged = callback;
  25450. };
  25451. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  25452. this._onrighttriggerchanged = callback;
  25453. };
  25454. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  25455. get: function () {
  25456. return this._leftTrigger;
  25457. },
  25458. set: function (newValue) {
  25459. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  25460. this._onlefttriggerchanged(newValue);
  25461. }
  25462. this._leftTrigger = newValue;
  25463. },
  25464. enumerable: true,
  25465. configurable: true
  25466. });
  25467. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  25468. get: function () {
  25469. return this._rightTrigger;
  25470. },
  25471. set: function (newValue) {
  25472. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  25473. this._onrighttriggerchanged(newValue);
  25474. }
  25475. this._rightTrigger = newValue;
  25476. },
  25477. enumerable: true,
  25478. configurable: true
  25479. });
  25480. Xbox360Pad.prototype.onbuttondown = function (callback) {
  25481. this._onbuttondown = callback;
  25482. };
  25483. Xbox360Pad.prototype.onbuttonup = function (callback) {
  25484. this._onbuttonup = callback;
  25485. };
  25486. Xbox360Pad.prototype.ondpaddown = function (callback) {
  25487. this._ondpaddown = callback;
  25488. };
  25489. Xbox360Pad.prototype.ondpadup = function (callback) {
  25490. this._ondpadup = callback;
  25491. };
  25492. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  25493. if (newValue !== currentValue) {
  25494. if (this._onbuttondown && newValue === 1) {
  25495. this._onbuttondown(buttonType);
  25496. }
  25497. if (this._onbuttonup && newValue === 0) {
  25498. this._onbuttonup(buttonType);
  25499. }
  25500. }
  25501. return newValue;
  25502. };
  25503. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  25504. if (newValue !== currentValue) {
  25505. if (this._ondpaddown && newValue === 1) {
  25506. this._ondpaddown(buttonType);
  25507. }
  25508. if (this._ondpadup && newValue === 0) {
  25509. this._ondpadup(buttonType);
  25510. }
  25511. }
  25512. return newValue;
  25513. };
  25514. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  25515. get: function () {
  25516. return this._buttonA;
  25517. },
  25518. set: function (value) {
  25519. this._buttonA = this._setButtonValue(value, this._buttonA, 0 /* A */);
  25520. },
  25521. enumerable: true,
  25522. configurable: true
  25523. });
  25524. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  25525. get: function () {
  25526. return this._buttonB;
  25527. },
  25528. set: function (value) {
  25529. this._buttonB = this._setButtonValue(value, this._buttonB, 1 /* B */);
  25530. },
  25531. enumerable: true,
  25532. configurable: true
  25533. });
  25534. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  25535. get: function () {
  25536. return this._buttonX;
  25537. },
  25538. set: function (value) {
  25539. this._buttonX = this._setButtonValue(value, this._buttonX, 2 /* X */);
  25540. },
  25541. enumerable: true,
  25542. configurable: true
  25543. });
  25544. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  25545. get: function () {
  25546. return this._buttonY;
  25547. },
  25548. set: function (value) {
  25549. this._buttonY = this._setButtonValue(value, this._buttonY, 3 /* Y */);
  25550. },
  25551. enumerable: true,
  25552. configurable: true
  25553. });
  25554. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  25555. get: function () {
  25556. return this._buttonStart;
  25557. },
  25558. set: function (value) {
  25559. this._buttonStart = this._setButtonValue(value, this._buttonStart, 4 /* Start */);
  25560. },
  25561. enumerable: true,
  25562. configurable: true
  25563. });
  25564. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  25565. get: function () {
  25566. return this._buttonBack;
  25567. },
  25568. set: function (value) {
  25569. this._buttonBack = this._setButtonValue(value, this._buttonBack, 5 /* Back */);
  25570. },
  25571. enumerable: true,
  25572. configurable: true
  25573. });
  25574. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  25575. get: function () {
  25576. return this._buttonLB;
  25577. },
  25578. set: function (value) {
  25579. this._buttonLB = this._setButtonValue(value, this._buttonLB, 6 /* LB */);
  25580. },
  25581. enumerable: true,
  25582. configurable: true
  25583. });
  25584. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  25585. get: function () {
  25586. return this._buttonRB;
  25587. },
  25588. set: function (value) {
  25589. this._buttonRB = this._setButtonValue(value, this._buttonRB, 7 /* RB */);
  25590. },
  25591. enumerable: true,
  25592. configurable: true
  25593. });
  25594. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  25595. get: function () {
  25596. return this._buttonLeftStick;
  25597. },
  25598. set: function (value) {
  25599. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, 8 /* LeftStick */);
  25600. },
  25601. enumerable: true,
  25602. configurable: true
  25603. });
  25604. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  25605. get: function () {
  25606. return this._buttonRightStick;
  25607. },
  25608. set: function (value) {
  25609. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, 9 /* RightStick */);
  25610. },
  25611. enumerable: true,
  25612. configurable: true
  25613. });
  25614. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  25615. get: function () {
  25616. return this._dPadUp;
  25617. },
  25618. set: function (value) {
  25619. this._dPadUp = this._setDPadValue(value, this._dPadUp, 0 /* Up */);
  25620. },
  25621. enumerable: true,
  25622. configurable: true
  25623. });
  25624. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  25625. get: function () {
  25626. return this._dPadDown;
  25627. },
  25628. set: function (value) {
  25629. this._dPadDown = this._setDPadValue(value, this._dPadDown, 1 /* Down */);
  25630. },
  25631. enumerable: true,
  25632. configurable: true
  25633. });
  25634. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  25635. get: function () {
  25636. return this._dPadLeft;
  25637. },
  25638. set: function (value) {
  25639. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, 2 /* Left */);
  25640. },
  25641. enumerable: true,
  25642. configurable: true
  25643. });
  25644. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  25645. get: function () {
  25646. return this._dPadRight;
  25647. },
  25648. set: function (value) {
  25649. this._dPadRight = this._setDPadValue(value, this._dPadRight, 3 /* Right */);
  25650. },
  25651. enumerable: true,
  25652. configurable: true
  25653. });
  25654. Xbox360Pad.prototype.update = function () {
  25655. _super.prototype.update.call(this);
  25656. this.buttonA = this.browserGamepad.buttons[0].value;
  25657. this.buttonB = this.browserGamepad.buttons[1].value;
  25658. this.buttonX = this.browserGamepad.buttons[2].value;
  25659. this.buttonY = this.browserGamepad.buttons[3].value;
  25660. this.buttonLB = this.browserGamepad.buttons[4].value;
  25661. this.buttonRB = this.browserGamepad.buttons[5].value;
  25662. this.leftTrigger = this.browserGamepad.buttons[6].value;
  25663. this.rightTrigger = this.browserGamepad.buttons[7].value;
  25664. this.buttonBack = this.browserGamepad.buttons[8].value;
  25665. this.buttonStart = this.browserGamepad.buttons[9].value;
  25666. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  25667. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  25668. this.dPadUp = this.browserGamepad.buttons[12].value;
  25669. this.dPadDown = this.browserGamepad.buttons[13].value;
  25670. this.dPadLeft = this.browserGamepad.buttons[14].value;
  25671. this.dPadRight = this.browserGamepad.buttons[15].value;
  25672. };
  25673. return Xbox360Pad;
  25674. })(Gamepad);
  25675. BABYLON.Xbox360Pad = Xbox360Pad;
  25676. })(BABYLON || (BABYLON = {}));
  25677. //# sourceMappingURL=babylon.gamepads.js.map
  25678. var BABYLON;
  25679. (function (BABYLON) {
  25680. // We're mainly based on the logic defined into the FreeCamera code
  25681. var GamepadCamera = (function (_super) {
  25682. __extends(GamepadCamera, _super);
  25683. function GamepadCamera(name, position, scene) {
  25684. var _this = this;
  25685. _super.call(this, name, position, scene);
  25686. this.angularSensibility = 200;
  25687. this.moveSensibility = 75;
  25688. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  25689. _this._onNewGameConnected(gamepad);
  25690. });
  25691. }
  25692. GamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  25693. // Only the first gamepad can control the camera
  25694. if (gamepad.index === 0) {
  25695. this._gamepad = gamepad;
  25696. }
  25697. };
  25698. GamepadCamera.prototype._checkInputs = function () {
  25699. if (!this._gamepad) {
  25700. return;
  25701. }
  25702. var LSValues = this._gamepad.leftStick;
  25703. var normalizedLX = LSValues.x / this.moveSensibility;
  25704. var normalizedLY = LSValues.y / this.moveSensibility;
  25705. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  25706. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  25707. var RSValues = this._gamepad.rightStick;
  25708. var normalizedRX = RSValues.x / this.angularSensibility;
  25709. var normalizedRY = RSValues.y / this.angularSensibility;
  25710. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  25711. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  25712. ;
  25713. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  25714. var speed = this._computeLocalCameraSpeed() * 50.0;
  25715. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  25716. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  25717. this.cameraRotation = this.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  25718. };
  25719. GamepadCamera.prototype.dispose = function () {
  25720. this._gamepads.dispose();
  25721. _super.prototype.dispose.call(this);
  25722. };
  25723. return GamepadCamera;
  25724. })(BABYLON.FreeCamera);
  25725. BABYLON.GamepadCamera = GamepadCamera;
  25726. })(BABYLON || (BABYLON = {}));
  25727. //# sourceMappingURL=babylon.gamepadCamera.js.map
  25728. var BABYLON;
  25729. (function (BABYLON) {
  25730. var LinesMesh = (function (_super) {
  25731. __extends(LinesMesh, _super);
  25732. function LinesMesh(name, scene, updatable) {
  25733. if (updatable === void 0) { updatable = false; }
  25734. _super.call(this, name, scene);
  25735. this.color = new BABYLON.Color3(1, 1, 1);
  25736. this.alpha = 1;
  25737. this._indices = new Array();
  25738. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  25739. attributes: ["position"],
  25740. uniforms: ["worldViewProjection", "color"],
  25741. needAlphaBlending: true
  25742. });
  25743. }
  25744. Object.defineProperty(LinesMesh.prototype, "material", {
  25745. get: function () {
  25746. return this._colorShader;
  25747. },
  25748. enumerable: true,
  25749. configurable: true
  25750. });
  25751. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  25752. get: function () {
  25753. return false;
  25754. },
  25755. enumerable: true,
  25756. configurable: true
  25757. });
  25758. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  25759. get: function () {
  25760. return false;
  25761. },
  25762. enumerable: true,
  25763. configurable: true
  25764. });
  25765. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  25766. var engine = this.getScene().getEngine();
  25767. var indexToBind = this._geometry.getIndexBuffer();
  25768. // VBOs
  25769. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  25770. // Color
  25771. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  25772. };
  25773. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  25774. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  25775. return;
  25776. }
  25777. var engine = this.getScene().getEngine();
  25778. // Draw order
  25779. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  25780. };
  25781. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  25782. return null;
  25783. };
  25784. LinesMesh.prototype.dispose = function (doNotRecurse) {
  25785. this._colorShader.dispose();
  25786. _super.prototype.dispose.call(this, doNotRecurse);
  25787. };
  25788. return LinesMesh;
  25789. })(BABYLON.Mesh);
  25790. BABYLON.LinesMesh = LinesMesh;
  25791. })(BABYLON || (BABYLON = {}));
  25792. //# sourceMappingURL=babylon.linesMesh.js.mapvar BABYLON;
  25793. (function (BABYLON) {
  25794. var OutlineRenderer = (function () {
  25795. function OutlineRenderer(scene) {
  25796. this._scene = scene;
  25797. }
  25798. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  25799. var _this = this;
  25800. if (useOverlay === void 0) { useOverlay = false; }
  25801. var scene = this._scene;
  25802. var engine = this._scene.getEngine();
  25803. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  25804. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  25805. return;
  25806. }
  25807. var mesh = subMesh.getRenderingMesh();
  25808. var material = subMesh.getMaterial();
  25809. engine.enableEffect(this._effect);
  25810. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  25811. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  25812. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  25813. // Bones
  25814. if (mesh.useBones) {
  25815. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  25816. }
  25817. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  25818. // Alpha test
  25819. if (material && material.needAlphaTesting()) {
  25820. var alphaTexture = material.getAlphaTestTexture();
  25821. this._effect.setTexture("diffuseSampler", alphaTexture);
  25822. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  25823. }
  25824. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  25825. _this._effect.setMatrix("world", world);
  25826. });
  25827. };
  25828. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  25829. var defines = [];
  25830. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  25831. var mesh = subMesh.getMesh();
  25832. var material = subMesh.getMaterial();
  25833. // Alpha test
  25834. if (material && material.needAlphaTesting()) {
  25835. defines.push("#define ALPHATEST");
  25836. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  25837. attribs.push(BABYLON.VertexBuffer.UVKind);
  25838. defines.push("#define UV1");
  25839. }
  25840. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  25841. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  25842. defines.push("#define UV2");
  25843. }
  25844. }
  25845. // Bones
  25846. if (mesh.useBones) {
  25847. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  25848. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  25849. defines.push("#define BONES");
  25850. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  25851. }
  25852. // Instances
  25853. if (useInstances) {
  25854. defines.push("#define INSTANCES");
  25855. attribs.push("world0");
  25856. attribs.push("world1");
  25857. attribs.push("world2");
  25858. attribs.push("world3");
  25859. }
  25860. // Get correct effect
  25861. var join = defines.join("\n");
  25862. if (this._cachedDefines !== join) {
  25863. this._cachedDefines = join;
  25864. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  25865. }
  25866. return this._effect.isReady();
  25867. };
  25868. return OutlineRenderer;
  25869. })();
  25870. BABYLON.OutlineRenderer = OutlineRenderer;
  25871. })(BABYLON || (BABYLON = {}));
  25872. //# sourceMappingURL=babylon.outlineRenderer.js.mapvar BABYLON;
  25873. (function (BABYLON) {
  25874. var MeshAssetTask = (function () {
  25875. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  25876. this.name = name;
  25877. this.meshesNames = meshesNames;
  25878. this.rootUrl = rootUrl;
  25879. this.sceneFilename = sceneFilename;
  25880. this.isCompleted = false;
  25881. }
  25882. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  25883. var _this = this;
  25884. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  25885. _this.loadedMeshes = meshes;
  25886. _this.loadedParticleSystems = particleSystems;
  25887. _this.loadedSkeletons = skeletons;
  25888. _this.isCompleted = true;
  25889. if (_this.onSuccess) {
  25890. _this.onSuccess(_this);
  25891. }
  25892. onSuccess();
  25893. }, null, function () {
  25894. if (_this.onError) {
  25895. _this.onError(_this);
  25896. }
  25897. onError();
  25898. });
  25899. };
  25900. return MeshAssetTask;
  25901. })();
  25902. BABYLON.MeshAssetTask = MeshAssetTask;
  25903. var TextFileAssetTask = (function () {
  25904. function TextFileAssetTask(name, url) {
  25905. this.name = name;
  25906. this.url = url;
  25907. this.isCompleted = false;
  25908. }
  25909. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  25910. var _this = this;
  25911. BABYLON.Tools.LoadFile(this.url, function (data) {
  25912. _this.text = data;
  25913. _this.isCompleted = true;
  25914. if (_this.onSuccess) {
  25915. _this.onSuccess(_this);
  25916. }
  25917. onSuccess();
  25918. }, null, scene.database, false, function () {
  25919. if (_this.onError) {
  25920. _this.onError(_this);
  25921. }
  25922. onError();
  25923. });
  25924. };
  25925. return TextFileAssetTask;
  25926. })();
  25927. BABYLON.TextFileAssetTask = TextFileAssetTask;
  25928. var BinaryFileAssetTask = (function () {
  25929. function BinaryFileAssetTask(name, url) {
  25930. this.name = name;
  25931. this.url = url;
  25932. this.isCompleted = false;
  25933. }
  25934. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  25935. var _this = this;
  25936. BABYLON.Tools.LoadFile(this.url, function (data) {
  25937. _this.data = data;
  25938. _this.isCompleted = true;
  25939. if (_this.onSuccess) {
  25940. _this.onSuccess(_this);
  25941. }
  25942. onSuccess();
  25943. }, null, scene.database, true, function () {
  25944. if (_this.onError) {
  25945. _this.onError(_this);
  25946. }
  25947. onError();
  25948. });
  25949. };
  25950. return BinaryFileAssetTask;
  25951. })();
  25952. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  25953. var ImageAssetTask = (function () {
  25954. function ImageAssetTask(name, url) {
  25955. this.name = name;
  25956. this.url = url;
  25957. this.isCompleted = false;
  25958. }
  25959. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  25960. var _this = this;
  25961. var img = new Image();
  25962. img.onload = function () {
  25963. _this.image = img;
  25964. _this.isCompleted = true;
  25965. if (_this.onSuccess) {
  25966. _this.onSuccess(_this);
  25967. }
  25968. onSuccess();
  25969. };
  25970. img.onerror = function () {
  25971. if (_this.onError) {
  25972. _this.onError(_this);
  25973. }
  25974. onError();
  25975. };
  25976. img.src = this.url;
  25977. };
  25978. return ImageAssetTask;
  25979. })();
  25980. BABYLON.ImageAssetTask = ImageAssetTask;
  25981. var TextureAssetTask = (function () {
  25982. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  25983. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  25984. this.name = name;
  25985. this.url = url;
  25986. this.noMipmap = noMipmap;
  25987. this.invertY = invertY;
  25988. this.samplingMode = samplingMode;
  25989. this.isCompleted = false;
  25990. }
  25991. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  25992. var _this = this;
  25993. var onload = function () {
  25994. _this.isCompleted = true;
  25995. if (_this.onSuccess) {
  25996. _this.onSuccess(_this);
  25997. }
  25998. onSuccess();
  25999. };
  26000. var onerror = function () {
  26001. if (_this.onError) {
  26002. _this.onError(_this);
  26003. }
  26004. onError();
  26005. };
  26006. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onError);
  26007. };
  26008. return TextureAssetTask;
  26009. })();
  26010. BABYLON.TextureAssetTask = TextureAssetTask;
  26011. var AssetsManager = (function () {
  26012. function AssetsManager(scene) {
  26013. this._tasks = new Array();
  26014. this._waitingTasksCount = 0;
  26015. this.useDefaultLoadingScreen = true;
  26016. this._scene = scene;
  26017. }
  26018. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  26019. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  26020. this._tasks.push(task);
  26021. return task;
  26022. };
  26023. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  26024. var task = new TextFileAssetTask(taskName, url);
  26025. this._tasks.push(task);
  26026. return task;
  26027. };
  26028. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  26029. var task = new BinaryFileAssetTask(taskName, url);
  26030. this._tasks.push(task);
  26031. return task;
  26032. };
  26033. AssetsManager.prototype.addImageTask = function (taskName, url) {
  26034. var task = new ImageAssetTask(taskName, url);
  26035. this._tasks.push(task);
  26036. return task;
  26037. };
  26038. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  26039. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  26040. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  26041. this._tasks.push(task);
  26042. return task;
  26043. };
  26044. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  26045. this._waitingTasksCount--;
  26046. if (this._waitingTasksCount === 0) {
  26047. if (this.onFinish) {
  26048. this.onFinish(this._tasks);
  26049. }
  26050. this._scene.getEngine().hideLoadingUI();
  26051. }
  26052. };
  26053. AssetsManager.prototype._runTask = function (task) {
  26054. var _this = this;
  26055. task.run(this._scene, function () {
  26056. if (_this.onTaskSuccess) {
  26057. _this.onTaskSuccess(task);
  26058. }
  26059. _this._decreaseWaitingTasksCount();
  26060. }, function () {
  26061. if (_this.onTaskError) {
  26062. _this.onTaskError(task);
  26063. }
  26064. _this._decreaseWaitingTasksCount();
  26065. });
  26066. };
  26067. AssetsManager.prototype.reset = function () {
  26068. this._tasks = new Array();
  26069. return this;
  26070. };
  26071. AssetsManager.prototype.load = function () {
  26072. this._waitingTasksCount = this._tasks.length;
  26073. if (this._waitingTasksCount === 0) {
  26074. if (this.onFinish) {
  26075. this.onFinish(this._tasks);
  26076. }
  26077. return this;
  26078. }
  26079. if (this.useDefaultLoadingScreen) {
  26080. this._scene.getEngine().displayLoadingUI();
  26081. }
  26082. for (var index = 0; index < this._tasks.length; index++) {
  26083. var task = this._tasks[index];
  26084. this._runTask(task);
  26085. }
  26086. return this;
  26087. };
  26088. return AssetsManager;
  26089. })();
  26090. BABYLON.AssetsManager = AssetsManager;
  26091. })(BABYLON || (BABYLON = {}));
  26092. //# sourceMappingURL=babylon.assetsManager.js.map
  26093. var BABYLON;
  26094. (function (BABYLON) {
  26095. var VRDeviceOrientationCamera = (function (_super) {
  26096. __extends(VRDeviceOrientationCamera, _super);
  26097. function VRDeviceOrientationCamera(name, position, scene) {
  26098. _super.call(this, name, position, scene);
  26099. this._alpha = 0;
  26100. this._beta = 0;
  26101. this._gamma = 0;
  26102. }
  26103. VRDeviceOrientationCamera.prototype._onOrientationEvent = function (evt) {
  26104. this._alpha = +evt.alpha | 0;
  26105. this._beta = +evt.beta | 0;
  26106. this._gamma = +evt.gamma | 0;
  26107. if (this._gamma < 0) {
  26108. this._gamma = 90 + this._gamma;
  26109. }
  26110. else {
  26111. // Incline it in the correct angle.
  26112. this._gamma = 270 - this._gamma;
  26113. }
  26114. this.rotation.x = this._gamma / 180.0 * Math.PI;
  26115. this.rotation.y = -this._alpha / 180.0 * Math.PI;
  26116. this.rotation.z = this._beta / 180.0 * Math.PI;
  26117. };
  26118. return VRDeviceOrientationCamera;
  26119. })(BABYLON.OculusCamera);
  26120. BABYLON.VRDeviceOrientationCamera = VRDeviceOrientationCamera;
  26121. })(BABYLON || (BABYLON = {}));
  26122. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  26123. var BABYLON;
  26124. (function (BABYLON) {
  26125. var WebVRCamera = (function (_super) {
  26126. __extends(WebVRCamera, _super);
  26127. function WebVRCamera(name, position, scene) {
  26128. _super.call(this, name, position, scene);
  26129. this._hmdDevice = null;
  26130. this._sensorDevice = null;
  26131. this._cacheState = null;
  26132. this._cacheQuaternion = new BABYLON.Quaternion();
  26133. this._cacheRotation = BABYLON.Vector3.Zero();
  26134. this._vrEnabled = false;
  26135. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  26136. }
  26137. WebVRCamera.prototype._getWebVRDevices = function (devices) {
  26138. var size = devices.length;
  26139. var i = 0;
  26140. // Reset devices.
  26141. this._sensorDevice = null;
  26142. this._hmdDevice = null;
  26143. while (i < size && this._hmdDevice === null) {
  26144. if (devices[i] instanceof HMDVRDevice) {
  26145. this._hmdDevice = devices[i];
  26146. }
  26147. i++;
  26148. }
  26149. i = 0;
  26150. while (i < size && this._sensorDevice === null) {
  26151. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  26152. this._sensorDevice = devices[i];
  26153. }
  26154. i++;
  26155. }
  26156. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  26157. };
  26158. WebVRCamera.prototype._update = function () {
  26159. if (this._vrEnabled) {
  26160. this._cacheState = this._sensorDevice.getState();
  26161. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  26162. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  26163. this.rotation.x = -this._cacheRotation.z;
  26164. this.rotation.y = -this._cacheRotation.y;
  26165. this.rotation.z = this._cacheRotation.x;
  26166. }
  26167. _super.prototype._update.call(this);
  26168. };
  26169. WebVRCamera.prototype.attachControl = function (element, noPreventDefault) {
  26170. _super.prototype.attachControl.call(this, element, noPreventDefault);
  26171. if (navigator.getVRDevices) {
  26172. navigator.getVRDevices().then(this._getWebVRDevices);
  26173. }
  26174. else if (navigator.mozGetVRDevices) {
  26175. navigator.mozGetVRDevices(this._getWebVRDevices);
  26176. }
  26177. };
  26178. WebVRCamera.prototype.detachControl = function (element) {
  26179. _super.prototype.detachControl.call(this, element);
  26180. this._vrEnabled = false;
  26181. };
  26182. return WebVRCamera;
  26183. })(BABYLON.OculusCamera);
  26184. BABYLON.WebVRCamera = WebVRCamera;
  26185. })(BABYLON || (BABYLON = {}));
  26186. //# sourceMappingURL=babylon.webVRCamera.js.map
  26187. var BABYLON;
  26188. (function (BABYLON) {
  26189. // Standard optimizations
  26190. var SceneOptimization = (function () {
  26191. function SceneOptimization(priority) {
  26192. if (priority === void 0) { priority = 0; }
  26193. this.priority = priority;
  26194. this.apply = function (scene) {
  26195. return true; // Return true if everything that can be done was applied
  26196. };
  26197. }
  26198. return SceneOptimization;
  26199. })();
  26200. BABYLON.SceneOptimization = SceneOptimization;
  26201. var TextureOptimization = (function (_super) {
  26202. __extends(TextureOptimization, _super);
  26203. function TextureOptimization(priority, maximumSize) {
  26204. var _this = this;
  26205. if (priority === void 0) { priority = 0; }
  26206. if (maximumSize === void 0) { maximumSize = 1024; }
  26207. _super.call(this, priority);
  26208. this.priority = priority;
  26209. this.maximumSize = maximumSize;
  26210. this.apply = function (scene) {
  26211. var allDone = true;
  26212. for (var index = 0; index < scene.textures.length; index++) {
  26213. var texture = scene.textures[index];
  26214. if (!texture.canRescale) {
  26215. continue;
  26216. }
  26217. var currentSize = texture.getSize();
  26218. var maxDimension = Math.max(currentSize.width, currentSize.height);
  26219. if (maxDimension > _this.maximumSize) {
  26220. texture.scale(0.5);
  26221. allDone = false;
  26222. }
  26223. }
  26224. return allDone;
  26225. };
  26226. }
  26227. return TextureOptimization;
  26228. })(SceneOptimization);
  26229. BABYLON.TextureOptimization = TextureOptimization;
  26230. var HardwareScalingOptimization = (function (_super) {
  26231. __extends(HardwareScalingOptimization, _super);
  26232. function HardwareScalingOptimization(priority, maximumScale) {
  26233. var _this = this;
  26234. if (priority === void 0) { priority = 0; }
  26235. if (maximumScale === void 0) { maximumScale = 2; }
  26236. _super.call(this, priority);
  26237. this.priority = priority;
  26238. this.maximumScale = maximumScale;
  26239. this._currentScale = 1;
  26240. this.apply = function (scene) {
  26241. _this._currentScale++;
  26242. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  26243. return _this._currentScale >= _this.maximumScale;
  26244. };
  26245. }
  26246. return HardwareScalingOptimization;
  26247. })(SceneOptimization);
  26248. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  26249. var ShadowsOptimization = (function (_super) {
  26250. __extends(ShadowsOptimization, _super);
  26251. function ShadowsOptimization() {
  26252. _super.apply(this, arguments);
  26253. this.apply = function (scene) {
  26254. scene.shadowsEnabled = false;
  26255. return true;
  26256. };
  26257. }
  26258. return ShadowsOptimization;
  26259. })(SceneOptimization);
  26260. BABYLON.ShadowsOptimization = ShadowsOptimization;
  26261. var PostProcessesOptimization = (function (_super) {
  26262. __extends(PostProcessesOptimization, _super);
  26263. function PostProcessesOptimization() {
  26264. _super.apply(this, arguments);
  26265. this.apply = function (scene) {
  26266. scene.postProcessesEnabled = false;
  26267. return true;
  26268. };
  26269. }
  26270. return PostProcessesOptimization;
  26271. })(SceneOptimization);
  26272. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  26273. var LensFlaresOptimization = (function (_super) {
  26274. __extends(LensFlaresOptimization, _super);
  26275. function LensFlaresOptimization() {
  26276. _super.apply(this, arguments);
  26277. this.apply = function (scene) {
  26278. scene.lensFlaresEnabled = false;
  26279. return true;
  26280. };
  26281. }
  26282. return LensFlaresOptimization;
  26283. })(SceneOptimization);
  26284. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  26285. var ParticlesOptimization = (function (_super) {
  26286. __extends(ParticlesOptimization, _super);
  26287. function ParticlesOptimization() {
  26288. _super.apply(this, arguments);
  26289. this.apply = function (scene) {
  26290. scene.particlesEnabled = false;
  26291. return true;
  26292. };
  26293. }
  26294. return ParticlesOptimization;
  26295. })(SceneOptimization);
  26296. BABYLON.ParticlesOptimization = ParticlesOptimization;
  26297. var RenderTargetsOptimization = (function (_super) {
  26298. __extends(RenderTargetsOptimization, _super);
  26299. function RenderTargetsOptimization() {
  26300. _super.apply(this, arguments);
  26301. this.apply = function (scene) {
  26302. scene.renderTargetsEnabled = false;
  26303. return true;
  26304. };
  26305. }
  26306. return RenderTargetsOptimization;
  26307. })(SceneOptimization);
  26308. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  26309. var MergeMeshesOptimization = (function (_super) {
  26310. __extends(MergeMeshesOptimization, _super);
  26311. function MergeMeshesOptimization() {
  26312. var _this = this;
  26313. _super.apply(this, arguments);
  26314. this._canBeMerged = function (abstractMesh) {
  26315. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  26316. return false;
  26317. }
  26318. var mesh = abstractMesh;
  26319. if (!mesh.isVisible || !mesh.isEnabled()) {
  26320. return false;
  26321. }
  26322. if (mesh.instances.length > 0) {
  26323. return false;
  26324. }
  26325. if (mesh.skeleton || mesh.hasLODLevels) {
  26326. return false;
  26327. }
  26328. return true;
  26329. };
  26330. this.apply = function (scene) {
  26331. var globalPool = scene.meshes.slice(0);
  26332. var globalLength = globalPool.length;
  26333. for (var index = 0; index < globalLength; index++) {
  26334. var currentPool = new Array();
  26335. var current = globalPool[index];
  26336. // Checks
  26337. if (!_this._canBeMerged(current)) {
  26338. continue;
  26339. }
  26340. currentPool.push(current);
  26341. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  26342. var otherMesh = globalPool[subIndex];
  26343. if (!_this._canBeMerged(otherMesh)) {
  26344. continue;
  26345. }
  26346. if (otherMesh.material !== current.material) {
  26347. continue;
  26348. }
  26349. if (otherMesh.checkCollisions !== current.checkCollisions) {
  26350. continue;
  26351. }
  26352. currentPool.push(otherMesh);
  26353. globalLength--;
  26354. globalPool.splice(subIndex, 1);
  26355. subIndex--;
  26356. }
  26357. if (currentPool.length < 2) {
  26358. continue;
  26359. }
  26360. // Merge meshes
  26361. BABYLON.Mesh.MergeMeshes(currentPool);
  26362. }
  26363. return true;
  26364. };
  26365. }
  26366. return MergeMeshesOptimization;
  26367. })(SceneOptimization);
  26368. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  26369. // Options
  26370. var SceneOptimizerOptions = (function () {
  26371. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  26372. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  26373. if (trackerDuration === void 0) { trackerDuration = 2000; }
  26374. this.targetFrameRate = targetFrameRate;
  26375. this.trackerDuration = trackerDuration;
  26376. this.optimizations = new Array();
  26377. }
  26378. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  26379. var result = new SceneOptimizerOptions(targetFrameRate);
  26380. var priority = 0;
  26381. result.optimizations.push(new MergeMeshesOptimization(priority));
  26382. result.optimizations.push(new ShadowsOptimization(priority));
  26383. result.optimizations.push(new LensFlaresOptimization(priority));
  26384. // Next priority
  26385. priority++;
  26386. result.optimizations.push(new PostProcessesOptimization(priority));
  26387. result.optimizations.push(new ParticlesOptimization(priority));
  26388. // Next priority
  26389. priority++;
  26390. result.optimizations.push(new TextureOptimization(priority, 1024));
  26391. return result;
  26392. };
  26393. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  26394. var result = new SceneOptimizerOptions(targetFrameRate);
  26395. var priority = 0;
  26396. result.optimizations.push(new MergeMeshesOptimization(priority));
  26397. result.optimizations.push(new ShadowsOptimization(priority));
  26398. result.optimizations.push(new LensFlaresOptimization(priority));
  26399. // Next priority
  26400. priority++;
  26401. result.optimizations.push(new PostProcessesOptimization(priority));
  26402. result.optimizations.push(new ParticlesOptimization(priority));
  26403. // Next priority
  26404. priority++;
  26405. result.optimizations.push(new TextureOptimization(priority, 512));
  26406. // Next priority
  26407. priority++;
  26408. result.optimizations.push(new RenderTargetsOptimization(priority));
  26409. // Next priority
  26410. priority++;
  26411. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  26412. return result;
  26413. };
  26414. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  26415. var result = new SceneOptimizerOptions(targetFrameRate);
  26416. var priority = 0;
  26417. result.optimizations.push(new MergeMeshesOptimization(priority));
  26418. result.optimizations.push(new ShadowsOptimization(priority));
  26419. result.optimizations.push(new LensFlaresOptimization(priority));
  26420. // Next priority
  26421. priority++;
  26422. result.optimizations.push(new PostProcessesOptimization(priority));
  26423. result.optimizations.push(new ParticlesOptimization(priority));
  26424. // Next priority
  26425. priority++;
  26426. result.optimizations.push(new TextureOptimization(priority, 256));
  26427. // Next priority
  26428. priority++;
  26429. result.optimizations.push(new RenderTargetsOptimization(priority));
  26430. // Next priority
  26431. priority++;
  26432. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  26433. return result;
  26434. };
  26435. return SceneOptimizerOptions;
  26436. })();
  26437. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  26438. // Scene optimizer tool
  26439. var SceneOptimizer = (function () {
  26440. function SceneOptimizer() {
  26441. }
  26442. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  26443. // TODO: add an epsilon
  26444. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  26445. if (onSuccess) {
  26446. onSuccess();
  26447. }
  26448. return;
  26449. }
  26450. // Apply current level of optimizations
  26451. var allDone = true;
  26452. var noOptimizationApplied = true;
  26453. for (var index = 0; index < options.optimizations.length; index++) {
  26454. var optimization = options.optimizations[index];
  26455. if (optimization.priority === currentPriorityLevel) {
  26456. noOptimizationApplied = false;
  26457. allDone = allDone && optimization.apply(scene);
  26458. }
  26459. }
  26460. // If no optimization was applied, this is a failure :(
  26461. if (noOptimizationApplied) {
  26462. if (onFailure) {
  26463. onFailure();
  26464. }
  26465. return;
  26466. }
  26467. // If all optimizations were done, move to next level
  26468. if (allDone) {
  26469. currentPriorityLevel++;
  26470. }
  26471. // Let's the system running for a specific amount of time before checking FPS
  26472. scene.executeWhenReady(function () {
  26473. setTimeout(function () {
  26474. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  26475. }, options.trackerDuration);
  26476. });
  26477. };
  26478. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  26479. if (!options) {
  26480. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  26481. }
  26482. // Let's the system running for a specific amount of time before checking FPS
  26483. scene.executeWhenReady(function () {
  26484. setTimeout(function () {
  26485. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  26486. }, options.trackerDuration);
  26487. });
  26488. };
  26489. return SceneOptimizer;
  26490. })();
  26491. BABYLON.SceneOptimizer = SceneOptimizer;
  26492. })(BABYLON || (BABYLON = {}));
  26493. //# sourceMappingURL=babylon.sceneOptimizer.js.mapvar BABYLON;
  26494. (function (BABYLON) {
  26495. var Internals;
  26496. (function (Internals) {
  26497. var MeshLODLevel = (function () {
  26498. function MeshLODLevel(distance, mesh) {
  26499. this.distance = distance;
  26500. this.mesh = mesh;
  26501. }
  26502. return MeshLODLevel;
  26503. })();
  26504. Internals.MeshLODLevel = MeshLODLevel;
  26505. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  26506. })(BABYLON || (BABYLON = {}));
  26507. //# sourceMappingURL=babylon.meshLODLevel.js.mapvar BABYLON;
  26508. (function (BABYLON) {
  26509. var AudioEngine = (function () {
  26510. function AudioEngine() {
  26511. this.audioContext = null;
  26512. this.canUseWebAudio = false;
  26513. this.WarnedWebAudioUnsupported = false;
  26514. try {
  26515. if (typeof AudioContext !== 'undefined') {
  26516. this.audioContext = new AudioContext();
  26517. this.canUseWebAudio = true;
  26518. }
  26519. else if (typeof webkitAudioContext !== 'undefined') {
  26520. this.audioContext = new webkitAudioContext();
  26521. this.canUseWebAudio = true;
  26522. }
  26523. }
  26524. catch (e) {
  26525. this.canUseWebAudio = false;
  26526. BABYLON.Tools.Error("Web Audio: " + e.message);
  26527. }
  26528. // create a global volume gain node
  26529. if (this.canUseWebAudio) {
  26530. this.masterGain = this.audioContext.createGain();
  26531. this.masterGain.gain.value = 1;
  26532. this.masterGain.connect(this.audioContext.destination);
  26533. }
  26534. }
  26535. AudioEngine.prototype.dispose = function () {
  26536. if (this.canUseWebAudio) {
  26537. if (this._connectedAnalyser) {
  26538. this._connectedAnalyser.stopDebugCanvas();
  26539. this._connectedAnalyser.dispose();
  26540. this.masterGain.disconnect();
  26541. this.masterGain.connect(this.audioContext.destination);
  26542. this._connectedAnalyser = null;
  26543. }
  26544. this.masterGain.gain.value = 1;
  26545. }
  26546. this.WarnedWebAudioUnsupported = false;
  26547. };
  26548. AudioEngine.prototype.getGlobalVolume = function () {
  26549. if (this.canUseWebAudio) {
  26550. return this.masterGain.gain.value;
  26551. }
  26552. else {
  26553. return -1;
  26554. }
  26555. };
  26556. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  26557. if (this.canUseWebAudio) {
  26558. this.masterGain.gain.value = newVolume;
  26559. }
  26560. };
  26561. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  26562. if (this._connectedAnalyser) {
  26563. this._connectedAnalyser.stopDebugCanvas();
  26564. }
  26565. this._connectedAnalyser = analyser;
  26566. if (this.canUseWebAudio) {
  26567. this.masterGain.disconnect();
  26568. this._connectedAnalyser.connectAudioNodes(this.masterGain, this.audioContext.destination);
  26569. }
  26570. };
  26571. return AudioEngine;
  26572. })();
  26573. BABYLON.AudioEngine = AudioEngine;
  26574. })(BABYLON || (BABYLON = {}));
  26575. //# sourceMappingURL=babylon.audioEngine.js.mapvar BABYLON;
  26576. (function (BABYLON) {
  26577. var Sound = (function () {
  26578. /**
  26579. * Create a sound and attach it to a scene
  26580. * @param name Name of your sound
  26581. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  26582. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  26583. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel
  26584. */
  26585. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  26586. var _this = this;
  26587. this.autoplay = false;
  26588. this.loop = false;
  26589. this.useCustomAttenuation = false;
  26590. this.spatialSound = false;
  26591. this.refDistance = 1;
  26592. this.rolloffFactor = 1;
  26593. this.maxDistance = 100;
  26594. this.distanceModel = "linear";
  26595. this._panningModel = "equalpower";
  26596. this._playbackRate = 1;
  26597. this._startTime = 0;
  26598. this._startOffset = 0;
  26599. this._position = BABYLON.Vector3.Zero();
  26600. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  26601. this._volume = 1;
  26602. this._isLoaded = false;
  26603. this._isReadyToPlay = false;
  26604. this.isPlaying = false;
  26605. this.isPaused = false;
  26606. this._isDirectional = false;
  26607. // Used if you'd like to create a directional sound.
  26608. // If not set, the sound will be omnidirectional
  26609. this._coneInnerAngle = 360;
  26610. this._coneOuterAngle = 360;
  26611. this._coneOuterGain = 0;
  26612. this.name = name;
  26613. this._scene = scene;
  26614. this._readyToPlayCallback = readyToPlayCallback;
  26615. // Default custom attenuation function is a linear attenuation
  26616. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  26617. if (currentDistance < maxDistance) {
  26618. return currentVolume * (1 - currentDistance / maxDistance);
  26619. }
  26620. else {
  26621. return 0;
  26622. }
  26623. };
  26624. if (options) {
  26625. this.autoplay = options.autoplay || false;
  26626. this.loop = options.loop || false;
  26627. // if volume === 0, we need another way to check this option
  26628. if (options.volume !== undefined) {
  26629. this._volume = options.volume;
  26630. }
  26631. this.spatialSound = options.spatialSound || false;
  26632. this.maxDistance = options.maxDistance || 100;
  26633. this.useCustomAttenuation = options.useCustomAttenuation || false;
  26634. this.rolloffFactor = options.rolloffFactor || 1;
  26635. this.refDistance = options.refDistance || 1;
  26636. this.distanceModel = options.distanceModel || "linear";
  26637. this._playbackRate = options.playbackRate || 1;
  26638. }
  26639. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  26640. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  26641. this._soundGain.gain.value = this._volume;
  26642. this._inputAudioNode = this._soundGain;
  26643. this._ouputAudioNode = this._soundGain;
  26644. if (this.spatialSound) {
  26645. this._createSpatialParameters();
  26646. }
  26647. this._scene.mainSoundTrack.AddSound(this);
  26648. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  26649. if (urlOrArrayBuffer) {
  26650. // If it's an URL
  26651. if (typeof (urlOrArrayBuffer) === "string") {
  26652. BABYLON.Tools.LoadFile(urlOrArrayBuffer, function (data) {
  26653. _this._soundLoaded(data);
  26654. }, null, null, true);
  26655. }
  26656. else {
  26657. if (urlOrArrayBuffer instanceof ArrayBuffer) {
  26658. this._soundLoaded(urlOrArrayBuffer);
  26659. }
  26660. else {
  26661. BABYLON.Tools.Error("Parameter must be a URL to the sound or an ArrayBuffer of the sound.");
  26662. }
  26663. }
  26664. }
  26665. }
  26666. else {
  26667. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  26668. this._scene.mainSoundTrack.AddSound(this);
  26669. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  26670. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  26671. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  26672. }
  26673. }
  26674. }
  26675. Sound.prototype.dispose = function () {
  26676. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  26677. if (this.isPlaying) {
  26678. this.stop();
  26679. }
  26680. this._isReadyToPlay = false;
  26681. if (this.soundTrackId === -1) {
  26682. this._scene.mainSoundTrack.RemoveSound(this);
  26683. }
  26684. else {
  26685. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  26686. }
  26687. if (this._soundGain) {
  26688. this._soundGain.disconnect();
  26689. this._soundGain = null;
  26690. }
  26691. if (this._soundPanner) {
  26692. this._soundPanner.disconnect();
  26693. this._soundPanner = null;
  26694. }
  26695. if (this._soundSource) {
  26696. this._soundSource.disconnect();
  26697. this._soundSource = null;
  26698. }
  26699. this._audioBuffer = null;
  26700. if (this._connectedMesh) {
  26701. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  26702. this._connectedMesh = null;
  26703. }
  26704. }
  26705. };
  26706. Sound.prototype._soundLoaded = function (audioData) {
  26707. var _this = this;
  26708. this._isLoaded = true;
  26709. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  26710. _this._audioBuffer = buffer;
  26711. _this._isReadyToPlay = true;
  26712. if (_this.autoplay) {
  26713. _this.play();
  26714. }
  26715. if (_this._readyToPlayCallback) {
  26716. _this._readyToPlayCallback();
  26717. }
  26718. }, function (error) {
  26719. BABYLON.Tools.Error("Error while decoding audio data: " + error.err);
  26720. });
  26721. };
  26722. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  26723. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  26724. this._audioBuffer = audioBuffer;
  26725. this._isReadyToPlay = true;
  26726. }
  26727. };
  26728. Sound.prototype.updateOptions = function (options) {
  26729. if (options) {
  26730. this.loop = options.loop || this.loop;
  26731. this.maxDistance = options.maxDistance || this.maxDistance;
  26732. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  26733. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  26734. this.refDistance = options.refDistance || this.refDistance;
  26735. this.distanceModel = options.distanceModel || this.distanceModel;
  26736. this._playbackRate = options.playbackRate || this._playbackRate;
  26737. }
  26738. };
  26739. Sound.prototype._createSpatialParameters = function () {
  26740. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  26741. if (this._scene.headphone) {
  26742. this._panningModel = "HRTF";
  26743. }
  26744. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  26745. if (this.useCustomAttenuation) {
  26746. // Tricks to disable in a way embedded Web Audio attenuation
  26747. this._soundPanner.distanceModel = "linear";
  26748. this._soundPanner.maxDistance = Number.MAX_VALUE;
  26749. this._soundPanner.refDistance = 1;
  26750. this._soundPanner.rolloffFactor = 1;
  26751. this._soundPanner.panningModel = this._panningModel;
  26752. }
  26753. else {
  26754. this._soundPanner.distanceModel = this.distanceModel;
  26755. this._soundPanner.maxDistance = this.maxDistance;
  26756. this._soundPanner.refDistance = this.refDistance;
  26757. this._soundPanner.rolloffFactor = this.rolloffFactor;
  26758. this._soundPanner.panningModel = this._panningModel;
  26759. }
  26760. this._soundPanner.connect(this._ouputAudioNode);
  26761. this._inputAudioNode = this._soundPanner;
  26762. }
  26763. };
  26764. Sound.prototype.switchPanningModelToHRTF = function () {
  26765. this._panningModel = "HRTF";
  26766. this._switchPanningModel();
  26767. };
  26768. Sound.prototype.switchPanningModelToEqualPower = function () {
  26769. this._panningModel = "equalpower";
  26770. this._switchPanningModel();
  26771. };
  26772. Sound.prototype._switchPanningModel = function () {
  26773. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  26774. this._soundPanner.panningModel = this._panningModel;
  26775. }
  26776. };
  26777. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  26778. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  26779. this._ouputAudioNode.disconnect();
  26780. this._ouputAudioNode.connect(soundTrackAudioNode);
  26781. }
  26782. };
  26783. /**
  26784. * Transform this sound into a directional source
  26785. * @param coneInnerAngle Size of the inner cone in degree
  26786. * @param coneOuterAngle Size of the outer cone in degree
  26787. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  26788. */
  26789. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  26790. if (coneOuterAngle < coneInnerAngle) {
  26791. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  26792. return;
  26793. }
  26794. this._coneInnerAngle = coneInnerAngle;
  26795. this._coneOuterAngle = coneOuterAngle;
  26796. this._coneOuterGain = coneOuterGain;
  26797. this._isDirectional = true;
  26798. if (this.isPlaying && this.loop) {
  26799. this.stop();
  26800. this.play();
  26801. }
  26802. };
  26803. Sound.prototype.setPosition = function (newPosition) {
  26804. this._position = newPosition;
  26805. if (this.isPlaying && this.spatialSound) {
  26806. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  26807. }
  26808. };
  26809. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  26810. this._localDirection = newLocalDirection;
  26811. if (this._connectedMesh && this.isPlaying) {
  26812. this._updateDirection();
  26813. }
  26814. };
  26815. Sound.prototype._updateDirection = function () {
  26816. var mat = this._connectedMesh.getWorldMatrix();
  26817. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  26818. direction.normalize();
  26819. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  26820. };
  26821. Sound.prototype.updateDistanceFromListener = function () {
  26822. if (this._connectedMesh && this.useCustomAttenuation) {
  26823. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  26824. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  26825. }
  26826. };
  26827. Sound.prototype.setAttenuationFunction = function (callback) {
  26828. this._customAttenuationFunction = callback;
  26829. };
  26830. /**
  26831. * Play the sound
  26832. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  26833. */
  26834. Sound.prototype.play = function (time) {
  26835. var _this = this;
  26836. if (this._isReadyToPlay && this._scene.audioEnabled) {
  26837. try {
  26838. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  26839. if (!this._soundSource) {
  26840. if (this.spatialSound) {
  26841. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  26842. if (this._isDirectional) {
  26843. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  26844. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  26845. this._soundPanner.coneOuterGain = this._coneOuterGain;
  26846. if (this._connectedMesh) {
  26847. this._updateDirection();
  26848. }
  26849. else {
  26850. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  26851. }
  26852. }
  26853. }
  26854. }
  26855. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  26856. this._soundSource.buffer = this._audioBuffer;
  26857. this._soundSource.connect(this._inputAudioNode);
  26858. this._soundSource.loop = this.loop;
  26859. this._soundSource.playbackRate.value = this._playbackRate;
  26860. this._startTime = startTime;
  26861. this._soundSource.onended = function () {
  26862. _this._onended();
  26863. };
  26864. this._soundSource.start(this._startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : 0);
  26865. this.isPlaying = true;
  26866. this.isPaused = false;
  26867. }
  26868. catch (ex) {
  26869. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  26870. }
  26871. }
  26872. };
  26873. Sound.prototype._onended = function () {
  26874. this.isPlaying = false;
  26875. if (this.onended) {
  26876. this.onended();
  26877. }
  26878. };
  26879. /**
  26880. * Stop the sound
  26881. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  26882. */
  26883. Sound.prototype.stop = function (time) {
  26884. if (this.isPlaying) {
  26885. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  26886. this._soundSource.stop(stopTime);
  26887. this.isPlaying = false;
  26888. }
  26889. };
  26890. Sound.prototype.pause = function () {
  26891. if (this.isPlaying) {
  26892. this.stop(0);
  26893. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  26894. this.isPaused = true;
  26895. }
  26896. };
  26897. Sound.prototype.setVolume = function (newVolume, time) {
  26898. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  26899. if (time) {
  26900. this._soundGain.gain.linearRampToValueAtTime(this._volume, BABYLON.Engine.audioEngine.audioContext.currentTime);
  26901. this._soundGain.gain.linearRampToValueAtTime(newVolume, time);
  26902. }
  26903. else {
  26904. this._soundGain.gain.value = newVolume;
  26905. }
  26906. }
  26907. this._volume = newVolume;
  26908. };
  26909. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  26910. this._playbackRate = newPlaybackRate;
  26911. if (this.isPlaying) {
  26912. this._soundSource.playbackRate.value = this._playbackRate;
  26913. }
  26914. };
  26915. Sound.prototype.getVolume = function () {
  26916. return this._volume;
  26917. };
  26918. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  26919. var _this = this;
  26920. this._connectedMesh = meshToConnectTo;
  26921. if (!this.spatialSound) {
  26922. this._createSpatialParameters();
  26923. this.spatialSound = true;
  26924. if (this.isPlaying && this.loop) {
  26925. this.stop();
  26926. this.play();
  26927. }
  26928. }
  26929. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  26930. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  26931. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  26932. };
  26933. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  26934. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  26935. if (this._isDirectional && this.isPlaying) {
  26936. this._updateDirection();
  26937. }
  26938. };
  26939. return Sound;
  26940. })();
  26941. BABYLON.Sound = Sound;
  26942. })(BABYLON || (BABYLON = {}));
  26943. //# sourceMappingURL=babylon.sound.js.mapvar BABYLON;
  26944. (function (BABYLON) {
  26945. var SoundTrack = (function () {
  26946. function SoundTrack(scene, options) {
  26947. this.id = -1;
  26948. this._isMainTrack = false;
  26949. this._scene = scene;
  26950. this._audioEngine = BABYLON.Engine.audioEngine;
  26951. this.soundCollection = new Array();
  26952. if (this._audioEngine.canUseWebAudio) {
  26953. this._trackGain = this._audioEngine.audioContext.createGain();
  26954. this._trackGain.connect(this._audioEngine.masterGain);
  26955. if (options) {
  26956. if (options.volume) {
  26957. this._trackGain.gain.value = options.volume;
  26958. }
  26959. if (options.mainTrack) {
  26960. this._isMainTrack = options.mainTrack;
  26961. }
  26962. }
  26963. }
  26964. if (!this._isMainTrack) {
  26965. this._scene.soundTracks.push(this);
  26966. this.id = this._scene.soundTracks.length - 1;
  26967. }
  26968. }
  26969. SoundTrack.prototype.dispose = function () {
  26970. if (this._audioEngine.canUseWebAudio) {
  26971. if (this._connectedAnalyser) {
  26972. this._connectedAnalyser.stopDebugCanvas();
  26973. }
  26974. while (this.soundCollection.length) {
  26975. this.soundCollection[0].dispose();
  26976. }
  26977. this._trackGain.disconnect();
  26978. this._trackGain = null;
  26979. }
  26980. };
  26981. SoundTrack.prototype.AddSound = function (sound) {
  26982. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  26983. sound.connectToSoundTrackAudioNode(this._trackGain);
  26984. }
  26985. if (sound.soundTrackId) {
  26986. if (sound.soundTrackId === -1) {
  26987. this._scene.mainSoundTrack.RemoveSound(sound);
  26988. }
  26989. else {
  26990. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  26991. }
  26992. }
  26993. this.soundCollection.push(sound);
  26994. sound.soundTrackId = this.id;
  26995. };
  26996. SoundTrack.prototype.RemoveSound = function (sound) {
  26997. var index = this.soundCollection.indexOf(sound);
  26998. if (index !== -1) {
  26999. this.soundCollection.splice(index, 1);
  27000. }
  27001. };
  27002. SoundTrack.prototype.setVolume = function (newVolume) {
  27003. if (this._audioEngine.canUseWebAudio) {
  27004. this._trackGain.gain.value = newVolume;
  27005. }
  27006. };
  27007. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  27008. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  27009. for (var i = 0; i < this.soundCollection.length; i++) {
  27010. this.soundCollection[i].switchPanningModelToHRTF();
  27011. }
  27012. }
  27013. };
  27014. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  27015. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  27016. for (var i = 0; i < this.soundCollection.length; i++) {
  27017. this.soundCollection[i].switchPanningModelToEqualPower();
  27018. }
  27019. }
  27020. };
  27021. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  27022. if (this._connectedAnalyser) {
  27023. this._connectedAnalyser.stopDebugCanvas();
  27024. }
  27025. this._connectedAnalyser = analyser;
  27026. if (this._audioEngine.canUseWebAudio) {
  27027. this._trackGain.disconnect();
  27028. this._connectedAnalyser.connectAudioNodes(this._trackGain, this._audioEngine.masterGain);
  27029. }
  27030. };
  27031. return SoundTrack;
  27032. })();
  27033. BABYLON.SoundTrack = SoundTrack;
  27034. })(BABYLON || (BABYLON = {}));
  27035. //# sourceMappingURL=babylon.soundtrack.js.mapvar BABYLON;
  27036. (function (BABYLON) {
  27037. var DebugLayer = (function () {
  27038. function DebugLayer(scene) {
  27039. var _this = this;
  27040. this._transformationMatrix = BABYLON.Matrix.Identity();
  27041. this._enabled = false;
  27042. this._labelsEnabled = false;
  27043. this._displayStatistics = true;
  27044. this._displayTree = false;
  27045. this._displayLogs = false;
  27046. this._identityMatrix = BABYLON.Matrix.Identity();
  27047. this.axisRatio = 0.02;
  27048. this.accentColor = "orange";
  27049. this._scene = scene;
  27050. this._syncPositions = function () {
  27051. var engine = _this._scene.getEngine();
  27052. var canvasRect = engine.getRenderingCanvasClientRect();
  27053. if (_this._showUI) {
  27054. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  27055. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  27056. _this._statsDiv.style.width = "400px";
  27057. _this._statsDiv.style.height = "auto";
  27058. _this._statsSubsetDiv.style.maxHeight = "240px";
  27059. _this._optionsDiv.style.left = "0px";
  27060. _this._optionsDiv.style.top = "10px";
  27061. _this._optionsDiv.style.width = "200px";
  27062. _this._optionsDiv.style.height = "auto";
  27063. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  27064. _this._logDiv.style.left = "0px";
  27065. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  27066. _this._logDiv.style.width = "600px";
  27067. _this._logDiv.style.height = "160px";
  27068. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  27069. _this._treeDiv.style.top = "10px";
  27070. _this._treeDiv.style.width = "300px";
  27071. _this._treeDiv.style.height = "auto";
  27072. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  27073. }
  27074. _this._globalDiv.style.left = canvasRect.left + "px";
  27075. _this._globalDiv.style.top = canvasRect.top + "px";
  27076. _this._drawingCanvas.style.left = "0px";
  27077. _this._drawingCanvas.style.top = "0px";
  27078. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  27079. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  27080. var devicePixelRatio = window.devicePixelRatio || 1;
  27081. var context = _this._drawingContext;
  27082. var backingStoreRatio = context.webkitBackingStorePixelRatio || context.mozBackingStorePixelRatio || context.msBackingStorePixelRatio || context.oBackingStorePixelRatio || context.backingStorePixelRatio || 1;
  27083. _this._ratio = devicePixelRatio / backingStoreRatio;
  27084. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  27085. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  27086. };
  27087. this._onCanvasClick = function (evt) {
  27088. _this._clickPosition = {
  27089. x: evt.clientX * _this._ratio,
  27090. y: evt.clientY * _this._ratio
  27091. };
  27092. };
  27093. this._syncUI = function () {
  27094. if (_this._showUI) {
  27095. if (_this._displayStatistics) {
  27096. _this._displayStats();
  27097. _this._statsDiv.style.display = "";
  27098. }
  27099. else {
  27100. _this._statsDiv.style.display = "none";
  27101. }
  27102. if (_this._displayLogs) {
  27103. _this._logDiv.style.display = "";
  27104. }
  27105. else {
  27106. _this._logDiv.style.display = "none";
  27107. }
  27108. if (_this._displayTree) {
  27109. _this._treeDiv.style.display = "";
  27110. if (_this._needToRefreshMeshesTree) {
  27111. _this._needToRefreshMeshesTree = false;
  27112. _this._refreshMeshesTreeContent();
  27113. }
  27114. }
  27115. else {
  27116. _this._treeDiv.style.display = "none";
  27117. }
  27118. }
  27119. };
  27120. this._syncData = function () {
  27121. if (_this._labelsEnabled || !_this._showUI) {
  27122. _this._camera.getViewMatrix().multiplyToRef(_this._camera.getProjectionMatrix(), _this._transformationMatrix);
  27123. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  27124. var engine = _this._scene.getEngine();
  27125. var viewport = _this._camera.viewport;
  27126. var globalViewport = viewport.toGlobal(engine);
  27127. // Meshes
  27128. var meshes = _this._camera.getActiveMeshes();
  27129. for (var index = 0; index < meshes.length; index++) {
  27130. var mesh = meshes.data[index];
  27131. var position = mesh.getBoundingInfo().boundingSphere.center;
  27132. var projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  27133. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  27134. _this._renderAxis(projectedPosition, mesh, globalViewport);
  27135. }
  27136. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  27137. _this._renderLabel(mesh.name, projectedPosition, 12, function () {
  27138. mesh.renderOverlay = !mesh.renderOverlay;
  27139. }, function () {
  27140. return mesh.renderOverlay ? 'red' : 'black';
  27141. });
  27142. }
  27143. }
  27144. // Cameras
  27145. var cameras = _this._scene.cameras;
  27146. for (index = 0; index < cameras.length; index++) {
  27147. var camera = cameras[index];
  27148. if (camera === _this._camera) {
  27149. continue;
  27150. }
  27151. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  27152. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  27153. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  27154. _this._camera.detachControl(engine.getRenderingCanvas());
  27155. _this._camera = camera;
  27156. _this._camera.attachControl(engine.getRenderingCanvas());
  27157. }, function () {
  27158. return "purple";
  27159. });
  27160. }
  27161. }
  27162. // Lights
  27163. var lights = _this._scene.lights;
  27164. for (index = 0; index < lights.length; index++) {
  27165. var light = lights[index];
  27166. if (light.position) {
  27167. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._transformationMatrix, globalViewport);
  27168. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  27169. _this._renderLabel(light.name, projectedPosition, -20, function () {
  27170. light.setEnabled(!light.isEnabled());
  27171. }, function () {
  27172. return light.isEnabled() ? "orange" : "gray";
  27173. });
  27174. }
  27175. }
  27176. }
  27177. }
  27178. _this._clickPosition = undefined;
  27179. };
  27180. }
  27181. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  27182. while (this._treeSubsetDiv.hasChildNodes()) {
  27183. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  27184. }
  27185. // Add meshes
  27186. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  27187. sortedArray.sort(function (a, b) {
  27188. if (a.name === b.name) {
  27189. return 0;
  27190. }
  27191. return (a.name > b.name) ? 1 : -1;
  27192. });
  27193. for (var index = 0; index < sortedArray.length; index++) {
  27194. var mesh = sortedArray[index];
  27195. if (!mesh.isEnabled()) {
  27196. continue;
  27197. }
  27198. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  27199. m.isVisible = element.checked;
  27200. }, mesh);
  27201. }
  27202. };
  27203. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  27204. this._drawingContext.beginPath();
  27205. this._drawingContext.moveTo(zero.x, zero.y);
  27206. this._drawingContext.lineTo(unit.x, unit.y);
  27207. this._drawingContext.strokeStyle = color;
  27208. this._drawingContext.lineWidth = 4;
  27209. this._drawingContext.stroke();
  27210. this._drawingContext.font = "normal 14px Segoe UI";
  27211. this._drawingContext.fillStyle = color;
  27212. this._drawingContext.fillText(label, unitText.x, unitText.y);
  27213. };
  27214. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  27215. var position = mesh.getBoundingInfo().boundingSphere.center;
  27216. var worldMatrix = mesh.getWorldMatrix();
  27217. var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._transformationMatrix);
  27218. var unit = (unprojectedVector.subtract(position)).length();
  27219. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  27220. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  27221. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  27222. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  27223. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  27224. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  27225. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._transformationMatrix, globalViewport);
  27226. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._transformationMatrix, globalViewport);
  27227. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  27228. };
  27229. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  27230. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  27231. this._drawingContext.font = "normal 12px Segoe UI";
  27232. var textMetrics = this._drawingContext.measureText(text);
  27233. var centerX = projectedPosition.x - textMetrics.width / 2;
  27234. var centerY = projectedPosition.y;
  27235. var clientRect = this._drawingCanvas.getBoundingClientRect();
  27236. if (this._showUI && this._isClickInsideRect(clientRect.left * this._ratio + centerX - 5, clientRect.top * this._ratio + centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  27237. onClick();
  27238. }
  27239. this._drawingContext.beginPath();
  27240. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  27241. this._drawingContext.fillStyle = getFillStyle();
  27242. this._drawingContext.globalAlpha = 0.5;
  27243. this._drawingContext.fill();
  27244. this._drawingContext.globalAlpha = 1.0;
  27245. this._drawingContext.strokeStyle = '#FFFFFF';
  27246. this._drawingContext.lineWidth = 1;
  27247. this._drawingContext.stroke();
  27248. this._drawingContext.fillStyle = "#FFFFFF";
  27249. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  27250. this._drawingContext.beginPath();
  27251. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  27252. this._drawingContext.fill();
  27253. }
  27254. };
  27255. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  27256. if (!this._clickPosition) {
  27257. return false;
  27258. }
  27259. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  27260. return false;
  27261. }
  27262. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  27263. return false;
  27264. }
  27265. return true;
  27266. };
  27267. DebugLayer.prototype.isVisible = function () {
  27268. return this._enabled;
  27269. };
  27270. DebugLayer.prototype.hide = function () {
  27271. if (!this._enabled) {
  27272. return;
  27273. }
  27274. this._enabled = false;
  27275. var engine = this._scene.getEngine();
  27276. this._scene.unregisterBeforeRender(this._syncData);
  27277. this._scene.unregisterAfterRender(this._syncUI);
  27278. document.body.removeChild(this._globalDiv);
  27279. window.removeEventListener("resize", this._syncPositions);
  27280. this._scene.forceShowBoundingBoxes = false;
  27281. this._scene.forceWireframe = false;
  27282. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  27283. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  27284. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  27285. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  27286. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  27287. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  27288. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  27289. this._scene.shadowsEnabled = true;
  27290. this._scene.particlesEnabled = true;
  27291. this._scene.postProcessesEnabled = true;
  27292. this._scene.collisionsEnabled = true;
  27293. this._scene.lightsEnabled = true;
  27294. this._scene.texturesEnabled = true;
  27295. this._scene.lensFlaresEnabled = true;
  27296. this._scene.proceduralTexturesEnabled = true;
  27297. this._scene.renderTargetsEnabled = true;
  27298. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  27299. };
  27300. DebugLayer.prototype.show = function (showUI, camera) {
  27301. if (showUI === void 0) { showUI = true; }
  27302. if (camera === void 0) { camera = null; }
  27303. if (this._enabled) {
  27304. return;
  27305. }
  27306. if (camera) {
  27307. this._camera = camera;
  27308. }
  27309. else {
  27310. this._camera = this._scene.activeCamera;
  27311. }
  27312. this._enabled = true;
  27313. this._showUI = showUI;
  27314. var engine = this._scene.getEngine();
  27315. this._globalDiv = document.createElement("div");
  27316. document.body.appendChild(this._globalDiv);
  27317. this._generateDOMelements();
  27318. window.addEventListener("resize", this._syncPositions);
  27319. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  27320. this._syncPositions();
  27321. this._scene.registerBeforeRender(this._syncData);
  27322. this._scene.registerAfterRender(this._syncUI);
  27323. };
  27324. DebugLayer.prototype._clearLabels = function () {
  27325. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  27326. for (var index = 0; index < this._scene.meshes.length; index++) {
  27327. var mesh = this._scene.meshes[index];
  27328. mesh.renderOverlay = false;
  27329. }
  27330. };
  27331. DebugLayer.prototype._generateheader = function (root, text) {
  27332. var header = document.createElement("div");
  27333. header.innerHTML = text + "&nbsp;";
  27334. header.style.textAlign = "right";
  27335. header.style.width = "100%";
  27336. header.style.color = "white";
  27337. header.style.backgroundColor = "Black";
  27338. header.style.padding = "5px 5px 4px 0px";
  27339. header.style.marginLeft = "-5px";
  27340. header.style.fontWeight = "bold";
  27341. root.appendChild(header);
  27342. };
  27343. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  27344. var label = document.createElement("label");
  27345. label.innerHTML = title;
  27346. label.style.color = color;
  27347. root.appendChild(label);
  27348. root.appendChild(document.createElement("br"));
  27349. };
  27350. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  27351. if (tag === void 0) { tag = null; }
  27352. var label = document.createElement("label");
  27353. var boundingBoxesCheckbox = document.createElement("input");
  27354. boundingBoxesCheckbox.type = "checkbox";
  27355. boundingBoxesCheckbox.checked = initialState;
  27356. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  27357. task(evt.target, tag);
  27358. });
  27359. label.appendChild(boundingBoxesCheckbox);
  27360. var container = document.createElement("span");
  27361. var leftPart = document.createElement("span");
  27362. var rightPart = document.createElement("span");
  27363. rightPart.style.cssFloat = "right";
  27364. leftPart.innerHTML = leftTitle;
  27365. rightPart.innerHTML = rightTitle;
  27366. rightPart.style.fontSize = "12px";
  27367. rightPart.style.maxWidth = "200px";
  27368. container.appendChild(leftPart);
  27369. container.appendChild(rightPart);
  27370. label.appendChild(container);
  27371. root.appendChild(label);
  27372. root.appendChild(document.createElement("br"));
  27373. };
  27374. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  27375. if (tag === void 0) { tag = null; }
  27376. var label = document.createElement("label");
  27377. var checkBox = document.createElement("input");
  27378. checkBox.type = "checkbox";
  27379. checkBox.checked = initialState;
  27380. checkBox.addEventListener("change", function (evt) {
  27381. task(evt.target, tag);
  27382. });
  27383. label.appendChild(checkBox);
  27384. label.appendChild(document.createTextNode(title));
  27385. root.appendChild(label);
  27386. root.appendChild(document.createElement("br"));
  27387. };
  27388. DebugLayer.prototype._generateButton = function (root, title, task, tag) {
  27389. if (tag === void 0) { tag = null; }
  27390. var button = document.createElement("button");
  27391. button.innerHTML = title;
  27392. button.style.height = "24px";
  27393. button.style.color = "#444444";
  27394. button.style.border = "1px solid white";
  27395. button.className = "debugLayerButton";
  27396. button.addEventListener("click", function (evt) {
  27397. task(evt.target, tag);
  27398. });
  27399. root.appendChild(button);
  27400. root.appendChild(document.createElement("br"));
  27401. };
  27402. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  27403. if (tag === void 0) { tag = null; }
  27404. var label = document.createElement("label");
  27405. var boundingBoxesRadio = document.createElement("input");
  27406. boundingBoxesRadio.type = "radio";
  27407. boundingBoxesRadio.name = name;
  27408. boundingBoxesRadio.checked = initialState;
  27409. boundingBoxesRadio.addEventListener("change", function (evt) {
  27410. task(evt.target, tag);
  27411. });
  27412. label.appendChild(boundingBoxesRadio);
  27413. label.appendChild(document.createTextNode(title));
  27414. root.appendChild(label);
  27415. root.appendChild(document.createElement("br"));
  27416. };
  27417. DebugLayer.prototype._generateDOMelements = function () {
  27418. var _this = this;
  27419. this._globalDiv.id = "DebugLayer";
  27420. this._globalDiv.style.position = "absolute";
  27421. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  27422. this._globalDiv.style.fontSize = "14px";
  27423. this._globalDiv.style.color = "white";
  27424. // Drawing canvas
  27425. this._drawingCanvas = document.createElement("canvas");
  27426. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  27427. this._drawingCanvas.style.position = "absolute";
  27428. this._drawingCanvas.style.pointerEvents = "none";
  27429. this._drawingContext = this._drawingCanvas.getContext("2d");
  27430. this._globalDiv.appendChild(this._drawingCanvas);
  27431. if (this._showUI) {
  27432. var background = "rgba(128, 128, 128, 0.4)";
  27433. var border = "rgb(180, 180, 180) solid 1px";
  27434. // Stats
  27435. this._statsDiv = document.createElement("div");
  27436. this._statsDiv.id = "DebugLayerStats";
  27437. this._statsDiv.style.border = border;
  27438. this._statsDiv.style.position = "absolute";
  27439. this._statsDiv.style.background = background;
  27440. this._statsDiv.style.padding = "0px 0px 0px 5px";
  27441. this._generateheader(this._statsDiv, "STATISTICS");
  27442. this._statsSubsetDiv = document.createElement("div");
  27443. this._statsSubsetDiv.style.paddingTop = "5px";
  27444. this._statsSubsetDiv.style.paddingBottom = "5px";
  27445. this._statsSubsetDiv.style.overflowY = "auto";
  27446. this._statsDiv.appendChild(this._statsSubsetDiv);
  27447. // Tree
  27448. this._treeDiv = document.createElement("div");
  27449. this._treeDiv.id = "DebugLayerTree";
  27450. this._treeDiv.style.border = border;
  27451. this._treeDiv.style.position = "absolute";
  27452. this._treeDiv.style.background = background;
  27453. this._treeDiv.style.padding = "0px 0px 0px 5px";
  27454. this._treeDiv.style.display = "none";
  27455. this._generateheader(this._treeDiv, "MESHES TREE");
  27456. this._treeSubsetDiv = document.createElement("div");
  27457. this._treeSubsetDiv.style.paddingTop = "5px";
  27458. this._treeSubsetDiv.style.paddingRight = "5px";
  27459. this._treeSubsetDiv.style.overflowY = "auto";
  27460. this._treeSubsetDiv.style.maxHeight = "300px";
  27461. this._treeDiv.appendChild(this._treeSubsetDiv);
  27462. this._needToRefreshMeshesTree = true;
  27463. // Logs
  27464. this._logDiv = document.createElement("div");
  27465. this._logDiv.style.border = border;
  27466. this._logDiv.id = "DebugLayerLogs";
  27467. this._logDiv.style.position = "absolute";
  27468. this._logDiv.style.background = background;
  27469. this._logDiv.style.padding = "0px 0px 0px 5px";
  27470. this._logDiv.style.display = "none";
  27471. this._generateheader(this._logDiv, "LOGS");
  27472. this._logSubsetDiv = document.createElement("div");
  27473. this._logSubsetDiv.style.height = "127px";
  27474. this._logSubsetDiv.style.paddingTop = "5px";
  27475. this._logSubsetDiv.style.overflowY = "auto";
  27476. this._logSubsetDiv.style.fontSize = "12px";
  27477. this._logSubsetDiv.style.fontFamily = "consolas";
  27478. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  27479. this._logDiv.appendChild(this._logSubsetDiv);
  27480. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  27481. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  27482. };
  27483. // Options
  27484. this._optionsDiv = document.createElement("div");
  27485. this._optionsDiv.id = "DebugLayerOptions";
  27486. this._optionsDiv.style.border = border;
  27487. this._optionsDiv.style.position = "absolute";
  27488. this._optionsDiv.style.background = background;
  27489. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  27490. this._optionsDiv.style.overflowY = "auto";
  27491. this._generateheader(this._optionsDiv, "OPTIONS");
  27492. this._optionsSubsetDiv = document.createElement("div");
  27493. this._optionsSubsetDiv.style.paddingTop = "5px";
  27494. this._optionsSubsetDiv.style.paddingBottom = "5px";
  27495. this._optionsSubsetDiv.style.overflowY = "auto";
  27496. this._optionsSubsetDiv.style.maxHeight = "200px";
  27497. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  27498. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  27499. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) {
  27500. _this._displayStatistics = element.checked;
  27501. });
  27502. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) {
  27503. _this._displayLogs = element.checked;
  27504. });
  27505. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  27506. _this._displayTree = element.checked;
  27507. _this._needToRefreshMeshesTree = true;
  27508. });
  27509. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27510. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  27511. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) {
  27512. _this._scene.forceShowBoundingBoxes = element.checked;
  27513. });
  27514. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  27515. _this._labelsEnabled = element.checked;
  27516. if (!_this._labelsEnabled) {
  27517. _this._clearLabels();
  27518. }
  27519. });
  27520. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  27521. if (element.checked) {
  27522. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  27523. }
  27524. else {
  27525. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  27526. }
  27527. });
  27528. ;
  27529. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27530. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  27531. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  27532. if (element.checked) {
  27533. _this._scene.forceWireframe = false;
  27534. _this._scene.forcePointsCloud = false;
  27535. }
  27536. });
  27537. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  27538. if (element.checked) {
  27539. _this._scene.forceWireframe = true;
  27540. _this._scene.forcePointsCloud = false;
  27541. }
  27542. });
  27543. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  27544. if (element.checked) {
  27545. _this._scene.forceWireframe = false;
  27546. _this._scene.forcePointsCloud = true;
  27547. }
  27548. });
  27549. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27550. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  27551. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) {
  27552. BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked;
  27553. });
  27554. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) {
  27555. BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked;
  27556. });
  27557. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) {
  27558. BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked;
  27559. });
  27560. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) {
  27561. BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked;
  27562. });
  27563. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) {
  27564. BABYLON.StandardMaterial.BumpTextureEnabled = element.checked;
  27565. });
  27566. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) {
  27567. BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked;
  27568. });
  27569. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) {
  27570. BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked;
  27571. });
  27572. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) {
  27573. BABYLON.StandardMaterial.FresnelEnabled = element.checked;
  27574. });
  27575. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27576. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  27577. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) {
  27578. _this._scene.animationsEnabled = element.checked;
  27579. });
  27580. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) {
  27581. _this._scene.collisionsEnabled = element.checked;
  27582. });
  27583. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) {
  27584. _this._scene.fogEnabled = element.checked;
  27585. });
  27586. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) {
  27587. _this._scene.lensFlaresEnabled = element.checked;
  27588. });
  27589. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) {
  27590. _this._scene.lightsEnabled = element.checked;
  27591. });
  27592. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) {
  27593. _this._scene.particlesEnabled = element.checked;
  27594. });
  27595. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) {
  27596. _this._scene.postProcessesEnabled = element.checked;
  27597. });
  27598. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) {
  27599. _this._scene.proceduralTexturesEnabled = element.checked;
  27600. });
  27601. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) {
  27602. _this._scene.renderTargetsEnabled = element.checked;
  27603. });
  27604. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) {
  27605. _this._scene.shadowsEnabled = element.checked;
  27606. });
  27607. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) {
  27608. _this._scene.skeletonsEnabled = element.checked;
  27609. });
  27610. this._generateCheckBox(this._optionsSubsetDiv, "Sprites", this._scene.spritesEnabled, function (element) {
  27611. _this._scene.spritesEnabled = element.checked;
  27612. });
  27613. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) {
  27614. _this._scene.texturesEnabled = element.checked;
  27615. });
  27616. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  27617. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27618. this._generateTexBox(this._optionsSubsetDiv, "<b>Audio:</b>", this.accentColor);
  27619. this._generateRadio(this._optionsSubsetDiv, "Headphones", "panningModel", this._scene.headphone, function (element) {
  27620. if (element.checked) {
  27621. _this._scene.headphone = true;
  27622. }
  27623. });
  27624. this._generateRadio(this._optionsSubsetDiv, "Normal Speakers", "panningModel", !this._scene.headphone, function (element) {
  27625. if (element.checked) {
  27626. _this._scene.headphone = false;
  27627. }
  27628. });
  27629. this._generateCheckBox(this._optionsSubsetDiv, "Disable audio", !this._scene.audioEnabled, function (element) {
  27630. _this._scene.audioEnabled = !element.checked;
  27631. });
  27632. }
  27633. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27634. this._generateTexBox(this._optionsSubsetDiv, "<b>Tools:</b>", this.accentColor);
  27635. this._generateButton(this._optionsSubsetDiv, "Dump rendertargets", function (element) {
  27636. _this._scene.dumpNextRenderTargets = true;
  27637. });
  27638. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27639. this._globalDiv.appendChild(this._statsDiv);
  27640. this._globalDiv.appendChild(this._logDiv);
  27641. this._globalDiv.appendChild(this._optionsDiv);
  27642. this._globalDiv.appendChild(this._treeDiv);
  27643. }
  27644. };
  27645. DebugLayer.prototype._displayStats = function () {
  27646. var scene = this._scene;
  27647. var engine = scene.getEngine();
  27648. var glInfo = engine.getGlInfo();
  27649. 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>";
  27650. if (this.customStatsFunction) {
  27651. this._statsSubsetDiv.innerHTML += this._statsSubsetDiv.innerHTML;
  27652. }
  27653. };
  27654. return DebugLayer;
  27655. })();
  27656. BABYLON.DebugLayer = DebugLayer;
  27657. })(BABYLON || (BABYLON = {}));
  27658. //# sourceMappingURL=babylon.debugLayer.js.map
  27659. var BABYLON;
  27660. (function (BABYLON) {
  27661. var RawTexture = (function (_super) {
  27662. __extends(RawTexture, _super);
  27663. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  27664. if (generateMipMaps === void 0) { generateMipMaps = true; }
  27665. if (invertY === void 0) { invertY = false; }
  27666. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  27667. _super.call(this, null, scene, !generateMipMaps, invertY);
  27668. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  27669. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  27670. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  27671. }
  27672. // Statics
  27673. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  27674. if (generateMipMaps === void 0) { generateMipMaps = true; }
  27675. if (invertY === void 0) { invertY = false; }
  27676. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  27677. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  27678. };
  27679. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  27680. if (generateMipMaps === void 0) { generateMipMaps = true; }
  27681. if (invertY === void 0) { invertY = false; }
  27682. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  27683. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  27684. };
  27685. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  27686. if (generateMipMaps === void 0) { generateMipMaps = true; }
  27687. if (invertY === void 0) { invertY = false; }
  27688. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  27689. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  27690. };
  27691. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  27692. if (generateMipMaps === void 0) { generateMipMaps = true; }
  27693. if (invertY === void 0) { invertY = false; }
  27694. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  27695. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  27696. };
  27697. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  27698. if (generateMipMaps === void 0) { generateMipMaps = true; }
  27699. if (invertY === void 0) { invertY = false; }
  27700. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  27701. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  27702. };
  27703. return RawTexture;
  27704. })(BABYLON.Texture);
  27705. BABYLON.RawTexture = RawTexture;
  27706. })(BABYLON || (BABYLON = {}));
  27707. //# sourceMappingURL=babylon.rawTexture.js.map
  27708. var BABYLON;
  27709. (function (BABYLON) {
  27710. var IndexedVector2 = (function (_super) {
  27711. __extends(IndexedVector2, _super);
  27712. function IndexedVector2(original, index) {
  27713. _super.call(this, original.x, original.y);
  27714. this.index = index;
  27715. }
  27716. return IndexedVector2;
  27717. })(BABYLON.Vector2);
  27718. var PolygonPoints = (function () {
  27719. function PolygonPoints() {
  27720. this.elements = new Array();
  27721. }
  27722. PolygonPoints.prototype.add = function (originalPoints) {
  27723. var _this = this;
  27724. var result = new Array();
  27725. originalPoints.forEach(function (point) {
  27726. if (result.length === 0 || !(BABYLON.Tools.WithinEpsilon(point.x, result[0].x, 0.00001) && BABYLON.Tools.WithinEpsilon(point.y, result[0].y, 0.00001))) {
  27727. var newPoint = new IndexedVector2(point, _this.elements.length);
  27728. result.push(newPoint);
  27729. _this.elements.push(newPoint);
  27730. }
  27731. });
  27732. return result;
  27733. };
  27734. PolygonPoints.prototype.computeBounds = function () {
  27735. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  27736. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  27737. this.elements.forEach(function (point) {
  27738. // x
  27739. if (point.x < lmin.x) {
  27740. lmin.x = point.x;
  27741. }
  27742. else if (point.x > lmax.x) {
  27743. lmax.x = point.x;
  27744. }
  27745. // y
  27746. if (point.y < lmin.y) {
  27747. lmin.y = point.y;
  27748. }
  27749. else if (point.y > lmax.y) {
  27750. lmax.y = point.y;
  27751. }
  27752. });
  27753. return {
  27754. min: lmin,
  27755. max: lmax,
  27756. width: lmax.x - lmin.x,
  27757. height: lmax.y - lmin.y
  27758. };
  27759. };
  27760. return PolygonPoints;
  27761. })();
  27762. var Polygon = (function () {
  27763. function Polygon() {
  27764. }
  27765. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  27766. return [
  27767. new BABYLON.Vector2(xmin, ymin),
  27768. new BABYLON.Vector2(xmax, ymin),
  27769. new BABYLON.Vector2(xmax, ymax),
  27770. new BABYLON.Vector2(xmin, ymax)
  27771. ];
  27772. };
  27773. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  27774. if (cx === void 0) { cx = 0; }
  27775. if (cy === void 0) { cy = 0; }
  27776. if (numberOfSides === void 0) { numberOfSides = 32; }
  27777. var result = new Array();
  27778. var angle = 0;
  27779. var increment = (Math.PI * 2) / numberOfSides;
  27780. for (var i = 0; i < numberOfSides; i++) {
  27781. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  27782. angle -= increment;
  27783. }
  27784. return result;
  27785. };
  27786. Polygon.Parse = function (input) {
  27787. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  27788. var i, result = [];
  27789. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  27790. result.push(new poly2tri.Point(floats[i], floats[i + 1]));
  27791. }
  27792. return result;
  27793. };
  27794. Polygon.StartingAt = function (x, y) {
  27795. return BABYLON.Path2.StartingAt(x, y);
  27796. };
  27797. return Polygon;
  27798. })();
  27799. BABYLON.Polygon = Polygon;
  27800. var PolygonMeshBuilder = (function () {
  27801. function PolygonMeshBuilder(name, contours, scene) {
  27802. this._points = new PolygonPoints();
  27803. if (!("poly2tri" in window)) {
  27804. throw "PolygonMeshBuilder cannot be used because poly2tri is not referenced";
  27805. }
  27806. this._name = name;
  27807. this._scene = scene;
  27808. var points;
  27809. if (contours instanceof BABYLON.Path2) {
  27810. points = contours.getPoints();
  27811. }
  27812. else {
  27813. points = contours;
  27814. }
  27815. this._swctx = new poly2tri.SweepContext(this._points.add(points));
  27816. }
  27817. PolygonMeshBuilder.prototype.addHole = function (hole) {
  27818. this._swctx.addHole(this._points.add(hole));
  27819. return this;
  27820. };
  27821. PolygonMeshBuilder.prototype.build = function (updatable) {
  27822. if (updatable === void 0) { updatable = false; }
  27823. var result = new BABYLON.Mesh(this._name, this._scene);
  27824. var normals = [];
  27825. var positions = [];
  27826. var uvs = [];
  27827. var bounds = this._points.computeBounds();
  27828. this._points.elements.forEach(function (p) {
  27829. normals.push(0, 1.0, 0);
  27830. positions.push(p.x, 0, p.y);
  27831. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  27832. });
  27833. var indices = [];
  27834. this._swctx.triangulate();
  27835. this._swctx.getTriangles().forEach(function (triangle) {
  27836. triangle.getPoints().forEach(function (point) {
  27837. indices.push(point.index);
  27838. });
  27839. });
  27840. result.setVerticesData(positions, BABYLON.VertexBuffer.PositionKind, updatable);
  27841. result.setVerticesData(normals, BABYLON.VertexBuffer.NormalKind, updatable);
  27842. result.setVerticesData(uvs, BABYLON.VertexBuffer.UVKind, updatable);
  27843. result.setIndices(indices);
  27844. return result;
  27845. };
  27846. return PolygonMeshBuilder;
  27847. })();
  27848. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  27849. })(BABYLON || (BABYLON = {}));
  27850. //# sourceMappingURL=babylon.polygonMesh.js.mapvar BABYLON;
  27851. (function (BABYLON) {
  27852. var SimplificationSettings = (function () {
  27853. function SimplificationSettings(quality, distance) {
  27854. this.quality = quality;
  27855. this.distance = distance;
  27856. }
  27857. return SimplificationSettings;
  27858. })();
  27859. BABYLON.SimplificationSettings = SimplificationSettings;
  27860. var SimplificationQueue = (function () {
  27861. function SimplificationQueue() {
  27862. this.running = false;
  27863. this._simplificationArray = [];
  27864. }
  27865. SimplificationQueue.prototype.addTask = function (task) {
  27866. this._simplificationArray.push(task);
  27867. };
  27868. SimplificationQueue.prototype.executeNext = function () {
  27869. var task = this._simplificationArray.pop();
  27870. if (task) {
  27871. this.running = true;
  27872. this.runSimplification(task);
  27873. }
  27874. else {
  27875. this.running = false;
  27876. }
  27877. };
  27878. SimplificationQueue.prototype.runSimplification = function (task) {
  27879. var _this = this;
  27880. function setLODLevel(distance, mesh) {
  27881. }
  27882. if (task.parallelProcessing) {
  27883. //parallel simplifier
  27884. task.settings.forEach(function (setting) {
  27885. var simplifier = _this.getSimplifier(task);
  27886. simplifier.simplify(setting, function (newMesh) {
  27887. task.mesh.addLODLevel(setting.distance, newMesh);
  27888. //check if it is the last
  27889. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  27890. //all done, run the success callback.
  27891. task.successCallback();
  27892. }
  27893. _this.executeNext();
  27894. });
  27895. });
  27896. }
  27897. else {
  27898. //single simplifier.
  27899. var simplifier = this.getSimplifier(task);
  27900. var runDecimation = function (setting, callback) {
  27901. simplifier.simplify(setting, function (newMesh) {
  27902. task.mesh.addLODLevel(setting.distance, newMesh);
  27903. //run the next quality level
  27904. callback();
  27905. });
  27906. };
  27907. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  27908. runDecimation(task.settings[loop.index], function () {
  27909. loop.executeNext();
  27910. });
  27911. }, function () {
  27912. //execution ended, run the success callback.
  27913. if (task.successCallback) {
  27914. task.successCallback();
  27915. }
  27916. _this.executeNext();
  27917. });
  27918. }
  27919. };
  27920. SimplificationQueue.prototype.getSimplifier = function (task) {
  27921. switch (task.simplificationType) {
  27922. case 0 /* QUADRATIC */:
  27923. default:
  27924. return new QuadraticErrorSimplification(task.mesh);
  27925. }
  27926. };
  27927. return SimplificationQueue;
  27928. })();
  27929. BABYLON.SimplificationQueue = SimplificationQueue;
  27930. /**
  27931. * The implemented types of simplification.
  27932. * At the moment only Quadratic Error Decimation is implemented.
  27933. */
  27934. (function (SimplificationType) {
  27935. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  27936. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  27937. var SimplificationType = BABYLON.SimplificationType;
  27938. var DecimationTriangle = (function () {
  27939. function DecimationTriangle(vertices) {
  27940. this.vertices = vertices;
  27941. this.error = new Array(4);
  27942. this.deleted = false;
  27943. this.isDirty = false;
  27944. this.borderFactor = 0;
  27945. }
  27946. return DecimationTriangle;
  27947. })();
  27948. BABYLON.DecimationTriangle = DecimationTriangle;
  27949. var DecimationVertex = (function () {
  27950. function DecimationVertex(position, normal, uv, id) {
  27951. this.position = position;
  27952. this.normal = normal;
  27953. this.uv = uv;
  27954. this.id = id;
  27955. this.isBorder = true;
  27956. this.q = new QuadraticMatrix();
  27957. this.triangleCount = 0;
  27958. this.triangleStart = 0;
  27959. }
  27960. return DecimationVertex;
  27961. })();
  27962. BABYLON.DecimationVertex = DecimationVertex;
  27963. var QuadraticMatrix = (function () {
  27964. function QuadraticMatrix(data) {
  27965. this.data = new Array(10);
  27966. for (var i = 0; i < 10; ++i) {
  27967. if (data && data[i]) {
  27968. this.data[i] = data[i];
  27969. }
  27970. else {
  27971. this.data[i] = 0;
  27972. }
  27973. }
  27974. }
  27975. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  27976. 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];
  27977. return det;
  27978. };
  27979. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  27980. for (var i = 0; i < 10; ++i) {
  27981. this.data[i] += matrix.data[i];
  27982. }
  27983. };
  27984. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  27985. for (var i = 0; i < 10; ++i) {
  27986. this.data[i] += data[i];
  27987. }
  27988. };
  27989. QuadraticMatrix.prototype.add = function (matrix) {
  27990. var m = new QuadraticMatrix();
  27991. for (var i = 0; i < 10; ++i) {
  27992. m.data[i] = this.data[i] + matrix.data[i];
  27993. }
  27994. return m;
  27995. };
  27996. QuadraticMatrix.FromData = function (a, b, c, d) {
  27997. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  27998. };
  27999. //returning an array to avoid garbage collection
  28000. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  28001. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  28002. };
  28003. return QuadraticMatrix;
  28004. })();
  28005. BABYLON.QuadraticMatrix = QuadraticMatrix;
  28006. var Reference = (function () {
  28007. function Reference(vertexId, triangleId) {
  28008. this.vertexId = vertexId;
  28009. this.triangleId = triangleId;
  28010. }
  28011. return Reference;
  28012. })();
  28013. BABYLON.Reference = Reference;
  28014. /**
  28015. * An implementation of the Quadratic Error simplification algorithm.
  28016. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  28017. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  28018. * @author RaananW
  28019. */
  28020. var QuadraticErrorSimplification = (function () {
  28021. function QuadraticErrorSimplification(_mesh) {
  28022. this._mesh = _mesh;
  28023. this.initialised = false;
  28024. this.syncIterations = 5000;
  28025. this.aggressiveness = 7;
  28026. this.decimationIterations = 100;
  28027. this.boundingBoxEpsilon = BABYLON.Engine.Epsilon;
  28028. }
  28029. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  28030. var _this = this;
  28031. this.initDecimatedMesh();
  28032. //iterating through the submeshes array, one after the other.
  28033. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  28034. _this.initWithMesh(_this._mesh, loop.index, function () {
  28035. _this.runDecimation(settings, loop.index, function () {
  28036. loop.executeNext();
  28037. });
  28038. });
  28039. }, function () {
  28040. setTimeout(function () {
  28041. _this._reconstructedMesh.isVisible = true;
  28042. successCallback(_this._reconstructedMesh);
  28043. }, 0);
  28044. });
  28045. };
  28046. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  28047. var _this = this;
  28048. var gCount = 0;
  28049. triangle.vertices.forEach(function (vId) {
  28050. var count = 0;
  28051. var vPos = _this.vertices[vId].position;
  28052. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  28053. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  28054. ++count;
  28055. if (bbox.maximum.y == vPos.y || vPos.y == bbox.minimum.y)
  28056. ++count;
  28057. if (bbox.maximum.z == vPos.z || vPos.z == bbox.minimum.z)
  28058. ++count;
  28059. if (count > 1) {
  28060. ++gCount;
  28061. }
  28062. ;
  28063. });
  28064. if (gCount > 1) {
  28065. console.log(triangle, gCount);
  28066. }
  28067. return gCount > 1;
  28068. };
  28069. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  28070. var _this = this;
  28071. var targetCount = ~~(this.triangles.length * settings.quality);
  28072. var deletedTriangles = 0;
  28073. var triangleCount = this.triangles.length;
  28074. var iterationFunction = function (iteration, callback) {
  28075. setTimeout(function () {
  28076. if (iteration % 5 === 0) {
  28077. _this.updateMesh(iteration === 0);
  28078. }
  28079. for (var i = 0; i < _this.triangles.length; ++i) {
  28080. _this.triangles[i].isDirty = false;
  28081. }
  28082. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  28083. var trianglesIterator = function (i) {
  28084. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  28085. var t = _this.triangles[tIdx];
  28086. if (!t)
  28087. return;
  28088. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  28089. return;
  28090. }
  28091. for (var j = 0; j < 3; ++j) {
  28092. if (t.error[j] < threshold) {
  28093. var deleted0 = [];
  28094. var deleted1 = [];
  28095. var i0 = t.vertices[j];
  28096. var i1 = t.vertices[(j + 1) % 3];
  28097. var v0 = _this.vertices[i0];
  28098. var v1 = _this.vertices[i1];
  28099. if (v0.isBorder !== v1.isBorder)
  28100. continue;
  28101. var p = BABYLON.Vector3.Zero();
  28102. var n = BABYLON.Vector3.Zero();
  28103. var uv = BABYLON.Vector2.Zero();
  28104. var color = new BABYLON.Color4(0, 0, 0, 1);
  28105. _this.calculateError(v0, v1, p, n, uv, color);
  28106. var delTr = [];
  28107. if (_this.isFlipped(v0, i1, p, deleted0, t.borderFactor, delTr))
  28108. continue;
  28109. if (_this.isFlipped(v1, i0, p, deleted1, t.borderFactor, delTr))
  28110. continue;
  28111. if (delTr.length == 2 || delTr[0] === delTr[1]) {
  28112. continue;
  28113. }
  28114. v0.normal = n;
  28115. if (v0.uv)
  28116. v0.uv = uv;
  28117. else if (v0.color)
  28118. v0.color = color;
  28119. v0.q = v1.q.add(v0.q);
  28120. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  28121. continue;
  28122. if (p.equals(v0.position))
  28123. continue;
  28124. v0.position = p;
  28125. var tStart = _this.references.length;
  28126. deletedTriangles = _this.updateTriangles(v0.id, v0, deleted0, deletedTriangles);
  28127. deletedTriangles = _this.updateTriangles(v0.id, v1, deleted1, deletedTriangles);
  28128. var tCount = _this.references.length - tStart;
  28129. if (tCount <= v0.triangleCount) {
  28130. if (tCount) {
  28131. for (var c = 0; c < tCount; c++) {
  28132. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  28133. }
  28134. }
  28135. }
  28136. else {
  28137. v0.triangleStart = tStart;
  28138. }
  28139. v0.triangleCount = tCount;
  28140. break;
  28141. }
  28142. }
  28143. };
  28144. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () {
  28145. return (triangleCount - deletedTriangles <= targetCount);
  28146. });
  28147. }, 0);
  28148. };
  28149. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  28150. if (triangleCount - deletedTriangles <= targetCount)
  28151. loop.breakLoop();
  28152. else {
  28153. iterationFunction(loop.index, function () {
  28154. loop.executeNext();
  28155. });
  28156. }
  28157. }, function () {
  28158. setTimeout(function () {
  28159. //reconstruct this part of the mesh
  28160. _this.reconstructMesh(submeshIndex);
  28161. successCallback();
  28162. }, 0);
  28163. });
  28164. };
  28165. QuadraticErrorSimplification.prototype.initWithMesh = function (mesh, submeshIndex, callback) {
  28166. var _this = this;
  28167. if (!mesh)
  28168. return;
  28169. this.vertices = [];
  28170. this.triangles = [];
  28171. this._mesh = mesh;
  28172. //It is assumed that a mesh has positions, normals and either uvs or colors.
  28173. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28174. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28175. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  28176. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  28177. var indices = mesh.getIndices();
  28178. var submesh = mesh.subMeshes[submeshIndex];
  28179. var vertexInit = function (i) {
  28180. var offset = i + submesh.verticesStart;
  28181. var vertex = new DecimationVertex(BABYLON.Vector3.FromArray(positionData, offset * 3), BABYLON.Vector3.FromArray(normalData, offset * 3), null, i);
  28182. if (_this._mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  28183. vertex.uv = BABYLON.Vector2.FromArray(uvs, offset * 2);
  28184. }
  28185. else if (_this._mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  28186. vertex.color = BABYLON.Color4.FromArray(colorsData, offset * 4);
  28187. }
  28188. _this.vertices.push(vertex);
  28189. };
  28190. //var totalVertices = mesh.getTotalVertices();
  28191. var totalVertices = submesh.verticesCount;
  28192. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, this.syncIterations, vertexInit, function () {
  28193. var indicesInit = function (i) {
  28194. var offset = (submesh.indexStart / 3) + i;
  28195. var pos = (offset * 3);
  28196. var i0 = indices[pos + 0] - submesh.verticesStart;
  28197. var i1 = indices[pos + 1] - submesh.verticesStart;
  28198. var i2 = indices[pos + 2] - submesh.verticesStart;
  28199. var triangle = new DecimationTriangle([_this.vertices[i0].id, _this.vertices[i1].id, _this.vertices[i2].id]);
  28200. _this.triangles.push(triangle);
  28201. };
  28202. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  28203. _this.init(callback);
  28204. });
  28205. });
  28206. };
  28207. QuadraticErrorSimplification.prototype.init = function (callback) {
  28208. var _this = this;
  28209. var triangleInit1 = function (i) {
  28210. var t = _this.triangles[i];
  28211. t.normal = BABYLON.Vector3.Cross(_this.vertices[t.vertices[1]].position.subtract(_this.vertices[t.vertices[0]].position), _this.vertices[t.vertices[2]].position.subtract(_this.vertices[t.vertices[0]].position)).normalize();
  28212. for (var j = 0; j < 3; j++) {
  28213. _this.vertices[t.vertices[j]].q.addArrayInPlace(QuadraticMatrix.DataFromNumbers(t.normal.x, t.normal.y, t.normal.z, -(BABYLON.Vector3.Dot(t.normal, _this.vertices[t.vertices[0]].position))));
  28214. }
  28215. };
  28216. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  28217. var triangleInit2 = function (i) {
  28218. var t = _this.triangles[i];
  28219. for (var j = 0; j < 3; ++j) {
  28220. t.error[j] = _this.calculateError(_this.vertices[t.vertices[j]], _this.vertices[t.vertices[(j + 1) % 3]]);
  28221. }
  28222. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  28223. };
  28224. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  28225. _this.initialised = true;
  28226. callback();
  28227. });
  28228. });
  28229. };
  28230. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  28231. var newTriangles = [];
  28232. var i;
  28233. for (i = 0; i < this.vertices.length; ++i) {
  28234. this.vertices[i].triangleCount = 0;
  28235. }
  28236. var t;
  28237. var j;
  28238. for (i = 0; i < this.triangles.length; ++i) {
  28239. if (!this.triangles[i].deleted) {
  28240. t = this.triangles[i];
  28241. for (j = 0; j < 3; ++j) {
  28242. this.vertices[t.vertices[j]].triangleCount = 1;
  28243. }
  28244. newTriangles.push(t);
  28245. }
  28246. }
  28247. var newVerticesOrder = [];
  28248. //compact vertices, get the IDs of the vertices used.
  28249. var dst = 0;
  28250. for (i = 0; i < this.vertices.length; ++i) {
  28251. if (this.vertices[i].triangleCount) {
  28252. this.vertices[i].triangleStart = dst;
  28253. this.vertices[dst].position = this.vertices[i].position;
  28254. this.vertices[dst].normal = this.vertices[i].normal;
  28255. this.vertices[dst].uv = this.vertices[i].uv;
  28256. this.vertices[dst].color = this.vertices[i].color;
  28257. newVerticesOrder.push(i);
  28258. dst++;
  28259. }
  28260. }
  28261. for (i = 0; i < newTriangles.length; ++i) {
  28262. t = newTriangles[i];
  28263. for (j = 0; j < 3; ++j) {
  28264. t.vertices[j] = this.vertices[t.vertices[j]].triangleStart;
  28265. }
  28266. }
  28267. this.vertices = this.vertices.slice(0, dst);
  28268. var newPositionData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || [];
  28269. var newNormalData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || [];
  28270. var newUVsData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || [];
  28271. var newColorsData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || [];
  28272. for (i = 0; i < newVerticesOrder.length; ++i) {
  28273. newPositionData.push(this.vertices[i].position.x);
  28274. newPositionData.push(this.vertices[i].position.y);
  28275. newPositionData.push(this.vertices[i].position.z);
  28276. newNormalData.push(this.vertices[i].normal.x);
  28277. newNormalData.push(this.vertices[i].normal.y);
  28278. newNormalData.push(this.vertices[i].normal.z);
  28279. if (this.vertices[i].uv) {
  28280. newUVsData.push(this.vertices[i].uv.x);
  28281. newUVsData.push(this.vertices[i].uv.y);
  28282. }
  28283. else if (this.vertices[i].color) {
  28284. newColorsData.push(this.vertices[i].color.r);
  28285. newColorsData.push(this.vertices[i].color.g);
  28286. newColorsData.push(this.vertices[i].color.b);
  28287. newColorsData.push(this.vertices[i].color.a);
  28288. }
  28289. }
  28290. var startingIndex = this._reconstructedMesh.getTotalIndices();
  28291. var startingVertex = this._reconstructedMesh.getTotalVertices();
  28292. var submeshesArray = this._reconstructedMesh.subMeshes;
  28293. this._reconstructedMesh.subMeshes = [];
  28294. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  28295. for (i = 0; i < newTriangles.length; ++i) {
  28296. newIndicesArray.push(newTriangles[i].vertices[0] + startingVertex);
  28297. newIndicesArray.push(newTriangles[i].vertices[1] + startingVertex);
  28298. newIndicesArray.push(newTriangles[i].vertices[2] + startingVertex);
  28299. }
  28300. //overwriting the old vertex buffers and indices.
  28301. this._reconstructedMesh.setIndices(newIndicesArray);
  28302. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  28303. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  28304. if (newUVsData.length > 0)
  28305. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  28306. if (newColorsData.length > 0)
  28307. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  28308. //create submesh
  28309. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  28310. if (submeshIndex > 0) {
  28311. this._reconstructedMesh.subMeshes = [];
  28312. submeshesArray.forEach(function (submesh) {
  28313. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, submesh.indexStart, submesh.indexCount, submesh.getMesh());
  28314. });
  28315. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, newVerticesOrder.length, startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  28316. }
  28317. };
  28318. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  28319. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  28320. this._reconstructedMesh.material = this._mesh.material;
  28321. this._reconstructedMesh.parent = this._mesh.parent;
  28322. this._reconstructedMesh.isVisible = false;
  28323. };
  28324. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, index2, point, deletedArray, borderFactor, delTr) {
  28325. for (var i = 0; i < vertex1.triangleCount; ++i) {
  28326. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  28327. if (t.deleted)
  28328. continue;
  28329. var s = this.references[vertex1.triangleStart + i].vertexId;
  28330. var id1 = t.vertices[(s + 1) % 3];
  28331. var id2 = t.vertices[(s + 2) % 3];
  28332. if ((id1 === index2 || id2 === index2)) {
  28333. deletedArray[i] = true;
  28334. delTr.push(t);
  28335. continue;
  28336. }
  28337. var d1 = this.vertices[id1].position.subtract(point);
  28338. d1 = d1.normalize();
  28339. var d2 = this.vertices[id2].position.subtract(point);
  28340. d2 = d2.normalize();
  28341. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  28342. return true;
  28343. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  28344. deletedArray[i] = false;
  28345. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  28346. return true;
  28347. }
  28348. return false;
  28349. };
  28350. QuadraticErrorSimplification.prototype.updateTriangles = function (vertexId, vertex, deletedArray, deletedTriangles) {
  28351. var newDeleted = deletedTriangles;
  28352. for (var i = 0; i < vertex.triangleCount; ++i) {
  28353. var ref = this.references[vertex.triangleStart + i];
  28354. var t = this.triangles[ref.triangleId];
  28355. if (t.deleted)
  28356. continue;
  28357. if (deletedArray[i]) {
  28358. t.deleted = true;
  28359. newDeleted++;
  28360. continue;
  28361. }
  28362. t.vertices[ref.vertexId] = vertexId;
  28363. t.isDirty = true;
  28364. t.error[0] = this.calculateError(this.vertices[t.vertices[0]], this.vertices[t.vertices[1]]) + (t.borderFactor / 2);
  28365. t.error[1] = this.calculateError(this.vertices[t.vertices[1]], this.vertices[t.vertices[2]]) + (t.borderFactor / 2);
  28366. t.error[2] = this.calculateError(this.vertices[t.vertices[2]], this.vertices[t.vertices[0]]) + (t.borderFactor / 2);
  28367. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  28368. this.references.push(ref);
  28369. }
  28370. return newDeleted;
  28371. };
  28372. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  28373. for (var i = 0; i < this.vertices.length; ++i) {
  28374. var vCount = [];
  28375. var vId = [];
  28376. var v = this.vertices[i];
  28377. var j;
  28378. for (j = 0; j < v.triangleCount; ++j) {
  28379. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  28380. for (var ii = 0; ii < 3; ii++) {
  28381. var ofs = 0;
  28382. var id = triangle.vertices[ii];
  28383. while (ofs < vCount.length) {
  28384. if (vId[ofs] === id)
  28385. break;
  28386. ++ofs;
  28387. }
  28388. if (ofs === vCount.length) {
  28389. vCount.push(1);
  28390. vId.push(id);
  28391. }
  28392. else {
  28393. vCount[ofs]++;
  28394. }
  28395. }
  28396. }
  28397. for (j = 0; j < vCount.length; ++j) {
  28398. if (vCount[j] === 1) {
  28399. this.vertices[vId[j]].isBorder = true;
  28400. }
  28401. else {
  28402. this.vertices[vId[j]].isBorder = false;
  28403. }
  28404. }
  28405. }
  28406. };
  28407. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  28408. if (identifyBorders === void 0) { identifyBorders = false; }
  28409. var i;
  28410. if (!identifyBorders) {
  28411. var newTrianglesVector = [];
  28412. for (i = 0; i < this.triangles.length; ++i) {
  28413. if (!this.triangles[i].deleted) {
  28414. newTrianglesVector.push(this.triangles[i]);
  28415. }
  28416. }
  28417. this.triangles = newTrianglesVector;
  28418. }
  28419. for (i = 0; i < this.vertices.length; ++i) {
  28420. this.vertices[i].triangleCount = 0;
  28421. this.vertices[i].triangleStart = 0;
  28422. }
  28423. var t;
  28424. var j;
  28425. var v;
  28426. for (i = 0; i < this.triangles.length; ++i) {
  28427. t = this.triangles[i];
  28428. for (j = 0; j < 3; ++j) {
  28429. v = this.vertices[t.vertices[j]];
  28430. v.triangleCount++;
  28431. }
  28432. }
  28433. var tStart = 0;
  28434. for (i = 0; i < this.vertices.length; ++i) {
  28435. this.vertices[i].triangleStart = tStart;
  28436. tStart += this.vertices[i].triangleCount;
  28437. this.vertices[i].triangleCount = 0;
  28438. }
  28439. var newReferences = new Array(this.triangles.length * 3);
  28440. for (i = 0; i < this.triangles.length; ++i) {
  28441. t = this.triangles[i];
  28442. for (j = 0; j < 3; ++j) {
  28443. v = this.vertices[t.vertices[j]];
  28444. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  28445. v.triangleCount++;
  28446. }
  28447. }
  28448. this.references = newReferences;
  28449. if (identifyBorders) {
  28450. this.identifyBorder();
  28451. }
  28452. };
  28453. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  28454. var x = point.x;
  28455. var y = point.y;
  28456. var z = point.z;
  28457. 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];
  28458. };
  28459. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  28460. var q = vertex1.q.add(vertex2.q);
  28461. var border = vertex1.isBorder && vertex2.isBorder;
  28462. var error = 0;
  28463. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  28464. if (qDet !== 0 && !border) {
  28465. if (!pointResult) {
  28466. pointResult = BABYLON.Vector3.Zero();
  28467. }
  28468. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  28469. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  28470. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  28471. error = this.vertexError(q, pointResult);
  28472. //TODO this should be correctly calculated
  28473. if (normalResult) {
  28474. normalResult.copyFrom(vertex1.normal);
  28475. if (vertex1.uv)
  28476. uvResult.copyFrom(vertex1.uv);
  28477. else if (vertex1.color)
  28478. colorResult.copyFrom(vertex1.color);
  28479. }
  28480. }
  28481. else {
  28482. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  28483. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  28484. var error1 = this.vertexError(q, vertex1.position);
  28485. var error2 = this.vertexError(q, vertex2.position);
  28486. var error3 = this.vertexError(q, p3);
  28487. error = Math.min(error1, error2, error3);
  28488. if (error === error1) {
  28489. if (pointResult) {
  28490. pointResult.copyFrom(vertex1.position);
  28491. normalResult.copyFrom(vertex1.normal);
  28492. if (vertex1.uv)
  28493. uvResult.copyFrom(vertex1.uv);
  28494. else if (vertex1.color)
  28495. colorResult.copyFrom(vertex1.color);
  28496. }
  28497. }
  28498. else if (error === error2) {
  28499. if (pointResult) {
  28500. pointResult.copyFrom(vertex2.position);
  28501. normalResult.copyFrom(vertex2.normal);
  28502. if (vertex2.uv)
  28503. uvResult.copyFrom(vertex2.uv);
  28504. else if (vertex2.color)
  28505. colorResult.copyFrom(vertex2.color);
  28506. }
  28507. }
  28508. else {
  28509. if (pointResult) {
  28510. pointResult.copyFrom(p3);
  28511. normalResult.copyFrom(vertex1.normal);
  28512. if (vertex1.uv)
  28513. uvResult.copyFrom(vertex1.uv);
  28514. else if (vertex1.color)
  28515. colorResult.copyFrom(vertex1.color);
  28516. }
  28517. }
  28518. }
  28519. return error;
  28520. };
  28521. return QuadraticErrorSimplification;
  28522. })();
  28523. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  28524. })(BABYLON || (BABYLON = {}));
  28525. //# sourceMappingURL=babylon.meshSimplification.js.mapvar BABYLON;
  28526. (function (BABYLON) {
  28527. var Analyser = (function () {
  28528. function Analyser(scene) {
  28529. this.SMOOTHING = 0.75;
  28530. this.FFT_SIZE = 512;
  28531. this.BARGRAPHAMPLITUDE = 256;
  28532. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  28533. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  28534. this._scene = scene;
  28535. this._audioEngine = BABYLON.Engine.audioEngine;
  28536. if (this._audioEngine.canUseWebAudio) {
  28537. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  28538. this._webAudioAnalyser.minDecibels = -140;
  28539. this._webAudioAnalyser.maxDecibels = 0;
  28540. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  28541. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  28542. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  28543. }
  28544. }
  28545. Analyser.prototype.getFrequencyBinCount = function () {
  28546. if (this._audioEngine.canUseWebAudio) {
  28547. return this._webAudioAnalyser.frequencyBinCount;
  28548. }
  28549. else {
  28550. return 0;
  28551. }
  28552. };
  28553. Analyser.prototype.getByteFrequencyData = function () {
  28554. if (this._audioEngine.canUseWebAudio) {
  28555. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  28556. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  28557. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  28558. }
  28559. return this._byteFreqs;
  28560. };
  28561. Analyser.prototype.getByteTimeDomainData = function () {
  28562. if (this._audioEngine.canUseWebAudio) {
  28563. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  28564. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  28565. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  28566. }
  28567. return this._byteTime;
  28568. };
  28569. Analyser.prototype.getFloatFrequencyData = function () {
  28570. if (this._audioEngine.canUseWebAudio) {
  28571. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  28572. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  28573. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  28574. }
  28575. return this._floatFreqs;
  28576. };
  28577. Analyser.prototype.drawDebugCanvas = function () {
  28578. var _this = this;
  28579. if (this._audioEngine.canUseWebAudio) {
  28580. if (!this._debugCanvas) {
  28581. this._debugCanvas = document.createElement("canvas");
  28582. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  28583. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  28584. this._debugCanvas.style.position = "absolute";
  28585. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  28586. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  28587. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  28588. document.body.appendChild(this._debugCanvas);
  28589. this._registerFunc = function () {
  28590. _this.drawDebugCanvas();
  28591. };
  28592. this._scene.registerBeforeRender(this._registerFunc);
  28593. }
  28594. if (this._registerFunc) {
  28595. var workingArray = this.getByteFrequencyData();
  28596. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  28597. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  28598. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  28599. var value = workingArray[i];
  28600. var percent = value / this.BARGRAPHAMPLITUDE;
  28601. var height = this.DEBUGCANVASSIZE.height * percent;
  28602. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  28603. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  28604. var hue = i / this.getFrequencyBinCount() * 360;
  28605. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  28606. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  28607. }
  28608. }
  28609. }
  28610. };
  28611. Analyser.prototype.stopDebugCanvas = function () {
  28612. if (this._debugCanvas) {
  28613. this._scene.unregisterBeforeRender(this._registerFunc);
  28614. this._registerFunc = null;
  28615. document.body.removeChild(this._debugCanvas);
  28616. this._debugCanvas = null;
  28617. this._debugCanvasContext = null;
  28618. }
  28619. };
  28620. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  28621. if (this._audioEngine.canUseWebAudio) {
  28622. inputAudioNode.connect(this._webAudioAnalyser);
  28623. this._webAudioAnalyser.connect(outputAudioNode);
  28624. }
  28625. };
  28626. Analyser.prototype.dispose = function () {
  28627. if (this._audioEngine.canUseWebAudio) {
  28628. this._webAudioAnalyser.disconnect();
  28629. }
  28630. };
  28631. return Analyser;
  28632. })();
  28633. BABYLON.Analyser = Analyser;
  28634. })(BABYLON || (BABYLON = {}));
  28635. //# sourceMappingURL=babylon.analyser.js.mapvar BABYLON;
  28636. (function (BABYLON) {
  28637. var DepthRenderer = (function () {
  28638. function DepthRenderer(scene, type) {
  28639. var _this = this;
  28640. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  28641. this._viewMatrix = BABYLON.Matrix.Zero();
  28642. this._projectionMatrix = BABYLON.Matrix.Zero();
  28643. this._transformMatrix = BABYLON.Matrix.Zero();
  28644. this._worldViewProjection = BABYLON.Matrix.Zero();
  28645. this._scene = scene;
  28646. var engine = scene.getEngine();
  28647. // Render target
  28648. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  28649. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  28650. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  28651. this._depthMap.refreshRate = 1;
  28652. this._depthMap.renderParticles = false;
  28653. this._depthMap.renderList = null;
  28654. // Custom render function
  28655. var renderSubMesh = function (subMesh) {
  28656. var mesh = subMesh.getRenderingMesh();
  28657. var scene = _this._scene;
  28658. var engine = scene.getEngine();
  28659. // Culling
  28660. engine.setState(subMesh.getMaterial().backFaceCulling);
  28661. // Managing instances
  28662. var batch = mesh._getInstancesRenderList(subMesh._id);
  28663. if (batch.mustReturn) {
  28664. return;
  28665. }
  28666. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  28667. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  28668. engine.enableEffect(_this._effect);
  28669. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  28670. var material = subMesh.getMaterial();
  28671. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  28672. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  28673. // Alpha test
  28674. if (material && material.needAlphaTesting()) {
  28675. var alphaTexture = material.getAlphaTestTexture();
  28676. _this._effect.setTexture("diffuseSampler", alphaTexture);
  28677. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  28678. }
  28679. // Bones
  28680. if (mesh.useBones) {
  28681. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  28682. }
  28683. // Draw
  28684. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  28685. }
  28686. };
  28687. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  28688. var index;
  28689. for (index = 0; index < opaqueSubMeshes.length; index++) {
  28690. renderSubMesh(opaqueSubMeshes.data[index]);
  28691. }
  28692. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  28693. renderSubMesh(alphaTestSubMeshes.data[index]);
  28694. }
  28695. };
  28696. }
  28697. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  28698. var defines = [];
  28699. var attribs = [BABYLON.VertexBuffer.PositionKind];
  28700. var mesh = subMesh.getMesh();
  28701. var scene = mesh.getScene();
  28702. var material = subMesh.getMaterial();
  28703. // Alpha test
  28704. if (material && material.needAlphaTesting()) {
  28705. defines.push("#define ALPHATEST");
  28706. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  28707. attribs.push(BABYLON.VertexBuffer.UVKind);
  28708. defines.push("#define UV1");
  28709. }
  28710. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  28711. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  28712. defines.push("#define UV2");
  28713. }
  28714. }
  28715. // Bones
  28716. if (mesh.useBones) {
  28717. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  28718. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  28719. defines.push("#define BONES");
  28720. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  28721. }
  28722. // Instances
  28723. if (useInstances) {
  28724. defines.push("#define INSTANCES");
  28725. attribs.push("world0");
  28726. attribs.push("world1");
  28727. attribs.push("world2");
  28728. attribs.push("world3");
  28729. }
  28730. // Get correct effect
  28731. var join = defines.join("\n");
  28732. if (this._cachedDefines !== join) {
  28733. this._cachedDefines = join;
  28734. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  28735. }
  28736. return this._effect.isReady();
  28737. };
  28738. DepthRenderer.prototype.getDepthMap = function () {
  28739. return this._depthMap;
  28740. };
  28741. // Methods
  28742. DepthRenderer.prototype.dispose = function () {
  28743. this._depthMap.dispose();
  28744. };
  28745. return DepthRenderer;
  28746. })();
  28747. BABYLON.DepthRenderer = DepthRenderer;
  28748. })(BABYLON || (BABYLON = {}));
  28749. //# sourceMappingURL=babylon.depthRenderer.js.map
  28750. var BABYLON;
  28751. (function (BABYLON) {
  28752. var SSAORenderingPipeline = (function (_super) {
  28753. __extends(SSAORenderingPipeline, _super);
  28754. /**
  28755. * @constructor
  28756. * @param {string} name - The rendering pipeline name
  28757. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  28758. * @param {any} ratio - The size of the postprocesses (0.5 means that your postprocess will have a width = canvas.width 0.5 and a height = canvas.height 0.5)
  28759. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  28760. */
  28761. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  28762. var _this = this;
  28763. _super.call(this, scene.getEngine(), name);
  28764. // Members
  28765. /**
  28766. * The PassPostProcess id in the pipeline that contains the original scene color
  28767. * @type {string}
  28768. */
  28769. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  28770. /**
  28771. * The SSAO PostProcess id in the pipeline
  28772. * @type {string}
  28773. */
  28774. this.SSAORenderEffect = "SSAORenderEffect";
  28775. /**
  28776. * The horizontal blur PostProcess id in the pipeline
  28777. * @type {string}
  28778. */
  28779. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  28780. /**
  28781. * The vertical blur PostProcess id in the pipeline
  28782. * @type {string}
  28783. */
  28784. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  28785. /**
  28786. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  28787. * @type {string}
  28788. */
  28789. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  28790. this._firstUpdate = true;
  28791. this._scene = scene;
  28792. // Set up assets
  28793. this._createRandomTexture();
  28794. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  28795. var ssaoRatio = ratio.ssaoRatio || ratio;
  28796. var combineRatio = ratio.combineRatio || ratio;
  28797. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  28798. this._createSSAOPostProcess(ssaoRatio);
  28799. this._blurHPostProcess = new BABYLON.BlurPostProcess("SSAOBlurH", new BABYLON.Vector2(2.0, 0.0), 1.3, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  28800. this._blurVPostProcess = new BABYLON.BlurPostProcess("SSAOBlurV", new BABYLON.Vector2(0.0, 2.0), 1.3, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  28801. this._createSSAOCombinePostProcess(combineRatio);
  28802. // Set up pipeline
  28803. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () {
  28804. return _this._originalColorPostProcess;
  28805. }, true));
  28806. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () {
  28807. return _this._ssaoPostProcess;
  28808. }, true));
  28809. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () {
  28810. return _this._blurHPostProcess;
  28811. }, true));
  28812. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () {
  28813. return _this._blurVPostProcess;
  28814. }, true));
  28815. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () {
  28816. return _this._ssaoCombinePostProcess;
  28817. }, true));
  28818. // Finish
  28819. scene.postProcessRenderPipelineManager.addPipeline(this);
  28820. if (cameras)
  28821. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  28822. }
  28823. // Public Methods
  28824. /**
  28825. * Returns the horizontal blur PostProcess
  28826. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  28827. */
  28828. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  28829. return this._blurHPostProcess;
  28830. };
  28831. /**
  28832. * Returns the vertical blur PostProcess
  28833. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  28834. */
  28835. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  28836. return this._blurVPostProcess;
  28837. };
  28838. /**
  28839. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  28840. */
  28841. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  28842. if (disableDepthRender === void 0) { disableDepthRender = false; }
  28843. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  28844. this._originalColorPostProcess = undefined;
  28845. this._ssaoPostProcess = undefined;
  28846. this._blurHPostProcess = undefined;
  28847. this._blurVPostProcess = undefined;
  28848. this._ssaoCombinePostProcess = undefined;
  28849. this._randomTexture.dispose();
  28850. if (disableDepthRender)
  28851. this._scene.disableDepthRenderer();
  28852. };
  28853. // Private Methods
  28854. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  28855. var _this = this;
  28856. var sampleSphere = [
  28857. 0.5381,
  28858. 0.1856,
  28859. -0.4319,
  28860. 0.1379,
  28861. 0.2486,
  28862. 0.4430,
  28863. 0.3371,
  28864. 0.5679,
  28865. -0.0057,
  28866. -0.6999,
  28867. -0.0451,
  28868. -0.0019,
  28869. 0.0689,
  28870. -0.1598,
  28871. -0.8547,
  28872. 0.0560,
  28873. 0.0069,
  28874. -0.1843,
  28875. -0.0146,
  28876. 0.1402,
  28877. 0.0762,
  28878. 0.0100,
  28879. -0.1924,
  28880. -0.0344,
  28881. -0.3577,
  28882. -0.5301,
  28883. -0.4358,
  28884. -0.3169,
  28885. 0.1063,
  28886. 0.0158,
  28887. 0.0103,
  28888. -0.5869,
  28889. 0.0046,
  28890. -0.0897,
  28891. -0.4940,
  28892. 0.3287,
  28893. 0.7119,
  28894. -0.0154,
  28895. -0.0918,
  28896. -0.0533,
  28897. 0.0596,
  28898. -0.5411,
  28899. 0.0352,
  28900. -0.0631,
  28901. 0.5460,
  28902. -0.4776,
  28903. 0.2847,
  28904. -0.0271
  28905. ];
  28906. var samplesFactor = 1.0 / 16.0;
  28907. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", ["sampleSphere", "samplesFactor", "randTextureTiles"], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  28908. this._ssaoPostProcess.onApply = function (effect) {
  28909. if (_this._firstUpdate) {
  28910. effect.setArray3("sampleSphere", sampleSphere);
  28911. effect.setFloat("samplesFactor", samplesFactor);
  28912. effect.setFloat("randTextureTiles", 4.0 / ratio);
  28913. _this._firstUpdate = false;
  28914. }
  28915. effect.setTexture("textureSampler", _this._depthTexture);
  28916. effect.setTexture("randomSampler", _this._randomTexture);
  28917. };
  28918. };
  28919. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  28920. var _this = this;
  28921. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  28922. this._ssaoCombinePostProcess.onApply = function (effect) {
  28923. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  28924. };
  28925. };
  28926. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  28927. var size = 512;
  28928. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  28929. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  28930. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  28931. var context = this._randomTexture.getContext();
  28932. var rand = function (min, max) {
  28933. return Math.random() * (max - min) + min;
  28934. };
  28935. for (var x = 0; x < size; x++) {
  28936. for (var y = 0; y < size; y++) {
  28937. var randVector = BABYLON.Vector3.Zero();
  28938. randVector.x = Math.floor(rand(0.0, 1.0) * 255);
  28939. randVector.y = Math.floor(rand(0.0, 1.0) * 255);
  28940. randVector.z = Math.floor(rand(0.0, 1.0) * 255);
  28941. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  28942. context.fillRect(x, y, 1, 1);
  28943. }
  28944. }
  28945. this._randomTexture.update(false);
  28946. };
  28947. return SSAORenderingPipeline;
  28948. })(BABYLON.PostProcessRenderPipeline);
  28949. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  28950. })(BABYLON || (BABYLON = {}));
  28951. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  28952. var BABYLON;
  28953. (function (BABYLON) {
  28954. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  28955. var VolumetricLightScatteringPostProcess = (function (_super) {
  28956. __extends(VolumetricLightScatteringPostProcess, _super);
  28957. /**
  28958. * @constructor
  28959. * @param {string} name - The post-process name
  28960. * @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)
  28961. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  28962. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  28963. * @param {number} samples - The post-process quality, default 100
  28964. * @param {number} samplingMode - The post-process filtering mode
  28965. * @param {BABYLON.Engine} engine - The babylon engine
  28966. * @param {boolean} reusable - If the post-process is reusable
  28967. */
  28968. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable) {
  28969. var _this = this;
  28970. if (samples === void 0) { samples = 100; }
  28971. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  28972. _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  28973. this._screenCoordinates = BABYLON.Vector2.Zero();
  28974. /**
  28975. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  28976. * @type {boolean}
  28977. */
  28978. this.useCustomMeshPosition = false;
  28979. /**
  28980. * If the post-process should inverse the light scattering direction
  28981. * @type {boolean}
  28982. */
  28983. this.invert = true;
  28984. /**
  28985. * Array containing the excluded meshes not rendered in the internal pass
  28986. */
  28987. this.excludedMeshes = new Array();
  28988. this.exposure = 0.3;
  28989. this.decay = 0.96815;
  28990. this.weight = 0.58767;
  28991. this.density = 0.926;
  28992. var scene = camera.getScene();
  28993. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(scene.getEngine());
  28994. // Configure mesh
  28995. this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  28996. // Configure
  28997. this._createPass(scene, ratio.passRatio || ratio);
  28998. this.onApply = function (effect) {
  28999. _this._updateMeshScreenCoordinates(scene);
  29000. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  29001. effect.setFloat("exposure", _this.exposure);
  29002. effect.setFloat("decay", _this.decay);
  29003. effect.setFloat("weight", _this.weight);
  29004. effect.setFloat("density", _this.density);
  29005. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  29006. };
  29007. }
  29008. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  29009. var mesh = subMesh.getMesh();
  29010. var defines = [];
  29011. var attribs = [BABYLON.VertexBuffer.PositionKind];
  29012. var material = subMesh.getMaterial();
  29013. var needUV = false;
  29014. // Render this.mesh as default
  29015. if (mesh === this.mesh) {
  29016. defines.push("#define BASIC_RENDER");
  29017. defines.push("#define NEED_UV");
  29018. needUV = true;
  29019. }
  29020. // Alpha test
  29021. if (material) {
  29022. if (material.needAlphaTesting() || mesh === this.mesh)
  29023. defines.push("#define ALPHATEST");
  29024. if (material.opacityTexture !== undefined) {
  29025. defines.push("#define OPACITY");
  29026. if (material.opacityTexture.getAlphaFromRGB)
  29027. defines.push("#define OPACITYRGB");
  29028. if (!needUV)
  29029. defines.push("#define NEED_UV");
  29030. }
  29031. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  29032. attribs.push(BABYLON.VertexBuffer.UVKind);
  29033. defines.push("#define UV1");
  29034. }
  29035. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  29036. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  29037. defines.push("#define UV2");
  29038. }
  29039. }
  29040. // Bones
  29041. if (mesh.useBones) {
  29042. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  29043. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  29044. defines.push("#define BONES");
  29045. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  29046. }
  29047. // Instances
  29048. if (useInstances) {
  29049. defines.push("#define INSTANCES");
  29050. attribs.push("world0");
  29051. attribs.push("world1");
  29052. attribs.push("world2");
  29053. attribs.push("world3");
  29054. }
  29055. // Get correct effect
  29056. var join = defines.join("\n");
  29057. if (this._cachedDefines !== join) {
  29058. this._cachedDefines = join;
  29059. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "opacityLevel"], ["diffuseSampler", "opacitySampler"], join);
  29060. }
  29061. return this._volumetricLightScatteringPass.isReady();
  29062. };
  29063. /**
  29064. * Sets the new light position for light scattering effect
  29065. * @param {BABYLON.Vector3} The new custom light position
  29066. */
  29067. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  29068. this._customMeshPosition = position;
  29069. };
  29070. /**
  29071. * Returns the light position for light scattering effect
  29072. * @return {BABYLON.Vector3} The custom light position
  29073. */
  29074. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  29075. return this._customMeshPosition;
  29076. };
  29077. /**
  29078. * Disposes the internal assets and detaches the post-process from the camera
  29079. */
  29080. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  29081. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  29082. if (rttIndex !== -1) {
  29083. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  29084. }
  29085. this._volumetricLightScatteringRTT.dispose();
  29086. _super.prototype.dispose.call(this, camera);
  29087. };
  29088. /**
  29089. * Returns the render target texture used by the post-process
  29090. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  29091. */
  29092. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  29093. return this._volumetricLightScatteringRTT;
  29094. };
  29095. // Private methods
  29096. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  29097. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  29098. return true;
  29099. }
  29100. return false;
  29101. };
  29102. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  29103. var _this = this;
  29104. var engine = scene.getEngine();
  29105. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  29106. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  29107. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  29108. this._volumetricLightScatteringRTT.renderList = null;
  29109. this._volumetricLightScatteringRTT.renderParticles = false;
  29110. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  29111. // Custom render function for submeshes
  29112. var renderSubMesh = function (subMesh) {
  29113. var mesh = subMesh.getRenderingMesh();
  29114. if (_this._meshExcluded(mesh)) {
  29115. return;
  29116. }
  29117. var scene = mesh.getScene();
  29118. var engine = scene.getEngine();
  29119. // Culling
  29120. engine.setState(subMesh.getMaterial().backFaceCulling);
  29121. // Managing instances
  29122. var batch = mesh._getInstancesRenderList(subMesh._id);
  29123. if (batch.mustReturn) {
  29124. return;
  29125. }
  29126. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  29127. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  29128. engine.enableEffect(_this._volumetricLightScatteringPass);
  29129. mesh._bind(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode);
  29130. var material = subMesh.getMaterial();
  29131. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  29132. // Alpha test
  29133. if (material && (mesh === _this.mesh || material.needAlphaTesting() || material.opacityTexture !== undefined)) {
  29134. var alphaTexture = material.getAlphaTestTexture();
  29135. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  29136. if (alphaTexture) {
  29137. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  29138. }
  29139. if (material.opacityTexture !== undefined) {
  29140. _this._volumetricLightScatteringPass.setTexture("opacitySampler", material.opacityTexture);
  29141. _this._volumetricLightScatteringPass.setFloat("opacityLevel", material.opacityTexture.level);
  29142. }
  29143. }
  29144. // Bones
  29145. if (mesh.useBones) {
  29146. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  29147. }
  29148. // Draw
  29149. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._volumetricLightScatteringPass.setMatrix("world", world); });
  29150. }
  29151. };
  29152. // Render target texture callbacks
  29153. var savedSceneClearColor;
  29154. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  29155. this._volumetricLightScatteringRTT.onBeforeRender = function () {
  29156. savedSceneClearColor = scene.clearColor;
  29157. scene.clearColor = sceneClearColor;
  29158. };
  29159. this._volumetricLightScatteringRTT.onAfterRender = function () {
  29160. scene.clearColor = savedSceneClearColor;
  29161. };
  29162. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  29163. var engine = scene.getEngine();
  29164. var index;
  29165. for (index = 0; index < opaqueSubMeshes.length; index++) {
  29166. renderSubMesh(opaqueSubMeshes.data[index]);
  29167. }
  29168. engine.setAlphaTesting(true);
  29169. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  29170. renderSubMesh(alphaTestSubMeshes.data[index]);
  29171. }
  29172. engine.setAlphaTesting(false);
  29173. if (transparentSubMeshes.length) {
  29174. for (index = 0; index < transparentSubMeshes.length; index++) {
  29175. var submesh = transparentSubMeshes.data[index];
  29176. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  29177. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  29178. }
  29179. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  29180. sortedArray.sort(function (a, b) {
  29181. // Alpha index first
  29182. if (a._alphaIndex > b._alphaIndex) {
  29183. return 1;
  29184. }
  29185. if (a._alphaIndex < b._alphaIndex) {
  29186. return -1;
  29187. }
  29188. // Then distance to camera
  29189. if (a._distanceToCamera < b._distanceToCamera) {
  29190. return 1;
  29191. }
  29192. if (a._distanceToCamera > b._distanceToCamera) {
  29193. return -1;
  29194. }
  29195. return 0;
  29196. });
  29197. // Render sub meshes
  29198. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  29199. for (index = 0; index < sortedArray.length; index++) {
  29200. renderSubMesh(sortedArray[index]);
  29201. }
  29202. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  29203. }
  29204. };
  29205. };
  29206. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  29207. var transform = scene.getTransformMatrix();
  29208. var pos = BABYLON.Vector3.Project(this.useCustomMeshPosition ? this._customMeshPosition : this.mesh.position, BABYLON.Matrix.Identity(), transform, this._viewPort);
  29209. this._screenCoordinates.x = pos.x / this._viewPort.width;
  29210. this._screenCoordinates.y = pos.y / this._viewPort.height;
  29211. if (this.invert)
  29212. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  29213. };
  29214. // Static methods
  29215. /**
  29216. * Creates a default mesh for the Volumeric Light Scattering post-process
  29217. * @param {string} The mesh name
  29218. * @param {BABYLON.Scene} The scene where to create the mesh
  29219. * @return {BABYLON.Mesh} the default mesh
  29220. */
  29221. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  29222. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  29223. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  29224. mesh.material = new BABYLON.StandardMaterial(name + "Material", scene);
  29225. return mesh;
  29226. };
  29227. return VolumetricLightScatteringPostProcess;
  29228. })(BABYLON.PostProcess);
  29229. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  29230. })(BABYLON || (BABYLON = {}));
  29231. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  29232. var BABYLON;
  29233. (function (BABYLON) {
  29234. var LensRenderingPipeline = (function (_super) {
  29235. __extends(LensRenderingPipeline, _super);
  29236. /**
  29237. * @constructor
  29238. * @param {string} name - The rendering pipeline name
  29239. * @param {object} parameters - An object containing all parameters (see below)
  29240. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  29241. * @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)
  29242. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  29243. Effect parameters are as follow:
  29244. {
  29245. chromatic_aberration: number; // from 0 to x (1 for realism)
  29246. edge_blur: number; // from 0 to x (1 for realism)
  29247. distortion: number; // from 0 to x (1 for realism)
  29248. grain_amount: number; // from 0 to 1
  29249. grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  29250. dof_focus_depth: number; // depth-of-field: focus depth; unset to disable
  29251. dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  29252. dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  29253. dof_gain: boolean; // depth-of-field: depthOfField gain (default: 1)
  29254. dof_threshold: boolean; // depth-of-field: depthOfField threshold (default: 1)
  29255. blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  29256. }
  29257. Note: if an effect parameter is unset, effect is disabled
  29258. */
  29259. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  29260. var _this = this;
  29261. if (ratio === void 0) { ratio = 1.0; }
  29262. _super.call(this, scene.getEngine(), name);
  29263. // Lens effects can be of the following:
  29264. // - chromatic aberration (slight shift of RGB colors)
  29265. // - blur on the edge of the lens
  29266. // - lens distortion
  29267. // - depth-of-field 'bokeh' effect (shapes appearing in blured areas, stronger highlights)
  29268. // - grain/dust-on-lens effect
  29269. // Two additional texture samplers are needed:
  29270. // - depth map (for depth-of-field)
  29271. // - grain texture
  29272. /**
  29273. * The chromatic aberration PostProcess id in the pipeline
  29274. * @type {string}
  29275. */
  29276. this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  29277. /**
  29278. * The depth-of-field PostProcess id in the pipeline
  29279. * @type {string}
  29280. */
  29281. this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  29282. this._scene = scene;
  29283. // Fetch texture samplers
  29284. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  29285. if (parameters.grain_texture) {
  29286. this._grainTexture = parameters.grain_texture;
  29287. }
  29288. else {
  29289. this._createGrainTexture();
  29290. }
  29291. // save parameters
  29292. this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  29293. this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  29294. this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  29295. this._distortion = parameters.distortion ? parameters.distortion : 0;
  29296. this._highlightsGain = parameters.dof_gain ? parameters.dof_gain : 1;
  29297. this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  29298. this._dofDepth = parameters.dof_focus_depth !== undefined ? parameters.dof_focus_depth : -1;
  29299. this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  29300. this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  29301. this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  29302. // Create effects
  29303. this._createChromaticAberrationPostProcess(ratio);
  29304. this._createDepthOfFieldPostProcess(ratio);
  29305. // Set up pipeline
  29306. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensChromaticAberrationEffect, function () {
  29307. return _this._chromaticAberrationPostProcess;
  29308. }, true));
  29309. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensDepthOfFieldEffect, function () {
  29310. return _this._depthOfFieldPostProcess;
  29311. }, true));
  29312. // Finish
  29313. scene.postProcessRenderPipelineManager.addPipeline(this);
  29314. if (cameras) {
  29315. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  29316. }
  29317. }
  29318. // public methods
  29319. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) {
  29320. this._edgeBlur = amount;
  29321. };
  29322. LensRenderingPipeline.prototype.disableEdgeBlur = function () {
  29323. this._edgeBlur = 0;
  29324. };
  29325. LensRenderingPipeline.prototype.setGrainAmount = function (amount) {
  29326. this._grainAmount = amount;
  29327. };
  29328. LensRenderingPipeline.prototype.disableGrain = function () {
  29329. this._grainAmount = 0;
  29330. };
  29331. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) {
  29332. this._chromaticAberration = amount;
  29333. };
  29334. LensRenderingPipeline.prototype.disableChromaticAberration = function () {
  29335. this._chromaticAberration = 0;
  29336. };
  29337. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) {
  29338. this._distortion = amount;
  29339. };
  29340. LensRenderingPipeline.prototype.disableEdgeDistortion = function () {
  29341. this._distortion = 0;
  29342. };
  29343. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  29344. this._highlightsGain = amount;
  29345. };
  29346. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  29347. this._highlightsThreshold = amount;
  29348. };
  29349. LensRenderingPipeline.prototype.setFocusDepth = function (amount) {
  29350. this._dofDepth = amount;
  29351. };
  29352. LensRenderingPipeline.prototype.disableDepthOfField = function () {
  29353. this._dofDepth = -1;
  29354. };
  29355. LensRenderingPipeline.prototype.setAperture = function (amount) {
  29356. this._dofAperture = amount;
  29357. };
  29358. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  29359. this._dofPentagon = true;
  29360. };
  29361. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  29362. this._dofPentagon = false;
  29363. };
  29364. LensRenderingPipeline.prototype.enableNoiseBlur = function () {
  29365. this._blurNoise = true;
  29366. };
  29367. LensRenderingPipeline.prototype.disableNoiseBlur = function () {
  29368. this._blurNoise = false;
  29369. };
  29370. /**
  29371. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  29372. */
  29373. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  29374. if (disableDepthRender === void 0) { disableDepthRender = false; }
  29375. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  29376. this._chromaticAberrationPostProcess = undefined;
  29377. this._depthOfFieldPostProcess = undefined;
  29378. this._grainTexture.dispose();
  29379. if (disableDepthRender)
  29380. this._scene.disableDepthRenderer();
  29381. };
  29382. // colors shifting and distortion
  29383. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  29384. var _this = this;
  29385. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], [], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  29386. this._chromaticAberrationPostProcess.onApply = function (effect) {
  29387. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  29388. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  29389. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  29390. };
  29391. };
  29392. // colors shifting and distortion
  29393. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  29394. var _this = this;
  29395. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  29396. "gain",
  29397. "threshold",
  29398. "focus_depth",
  29399. "aperture",
  29400. "pentagon",
  29401. "maxZ",
  29402. "edge_blur",
  29403. "chromatic_aberration",
  29404. "distortion",
  29405. "blur_noise",
  29406. "grain_amount",
  29407. "screen_width",
  29408. "screen_height"
  29409. ], ["depthSampler", "grainSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  29410. this._depthOfFieldPostProcess.onApply = function (effect) {
  29411. effect.setBool('pentagon', _this._dofPentagon);
  29412. effect.setBool('blur_noise', _this._blurNoise);
  29413. effect.setFloat('maxZ', _this._scene.activeCamera.maxZ);
  29414. effect.setFloat('grain_amount', _this._grainAmount);
  29415. effect.setTexture("depthSampler", _this._depthTexture);
  29416. effect.setTexture("grainSampler", _this._grainTexture);
  29417. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  29418. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  29419. effect.setFloat('distortion', _this._distortion);
  29420. effect.setFloat('focus_depth', _this._dofDepth);
  29421. effect.setFloat('aperture', _this._dofAperture);
  29422. effect.setFloat('gain', _this._highlightsGain);
  29423. effect.setFloat('threshold', _this._highlightsThreshold);
  29424. effect.setFloat('edge_blur', _this._edgeBlur);
  29425. };
  29426. };
  29427. // creates a black and white random noise texture, 512x512
  29428. LensRenderingPipeline.prototype._createGrainTexture = function () {
  29429. var size = 512;
  29430. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  29431. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  29432. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  29433. var context = this._grainTexture.getContext();
  29434. var rand = function (min, max) {
  29435. return Math.random() * (max - min) + min;
  29436. };
  29437. var value;
  29438. for (var x = 0; x < size; x++) {
  29439. for (var y = 0; y < size; y++) {
  29440. value = Math.floor(rand(0.42, 0.58) * 255);
  29441. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  29442. context.fillRect(x, y, 1, 1);
  29443. }
  29444. }
  29445. this._grainTexture.update(false);
  29446. };
  29447. return LensRenderingPipeline;
  29448. })(BABYLON.PostProcessRenderPipeline);
  29449. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  29450. })(BABYLON || (BABYLON = {}));
  29451. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map//
  29452. // This post-process allows the modification of rendered colors by using
  29453. // a 'look-up table' (LUT). This effect is also called Color Grading.
  29454. //
  29455. // The object needs to be provided an url to a texture containing the color
  29456. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  29457. // Use an image editing software to tweak the LUT to match your needs.
  29458. //
  29459. // For an example of a color LUT, see here:
  29460. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  29461. // For explanations on color grading, see here:
  29462. // http://udn.epicgames.com/Three/ColorGrading.html
  29463. //
  29464. var BABYLON;
  29465. (function (BABYLON) {
  29466. var ColorCorrectionPostProcess = (function (_super) {
  29467. __extends(ColorCorrectionPostProcess, _super);
  29468. function ColorCorrectionPostProcess(name, colorTableUrl, ratio, camera, samplingMode, engine, reusable) {
  29469. var _this = this;
  29470. _super.call(this, name, 'colorCorrection', null, ['colorTable'], ratio, camera, samplingMode, engine, reusable);
  29471. this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  29472. this._colorTableTexture.anisotropicFilteringLevel = 1;
  29473. this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  29474. this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  29475. this.onApply = function (effect) {
  29476. effect.setTexture("colorTable", _this._colorTableTexture);
  29477. };
  29478. }
  29479. return ColorCorrectionPostProcess;
  29480. })(BABYLON.PostProcess);
  29481. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  29482. })(BABYLON || (BABYLON = {}));
  29483. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map