babylon.2.1-alpha.debug.js 1.4 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699
  1. var __extends = this.__extends || function (d, b) {
  2. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  3. function __() { this.constructor = d; }
  4. __.prototype = b.prototype;
  5. d.prototype = new __();
  6. };var BABYLON;
  7. (function (BABYLON) {
  8. var Color3 = (function () {
  9. function Color3(r, g, b) {
  10. if (r === void 0) { r = 0; }
  11. if (g === void 0) { g = 0; }
  12. if (b === void 0) { b = 0; }
  13. this.r = r;
  14. this.g = g;
  15. this.b = b;
  16. }
  17. Color3.prototype.toString = function () {
  18. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  19. };
  20. // Operators
  21. Color3.prototype.toArray = function (array, index) {
  22. if (index === undefined) {
  23. index = 0;
  24. }
  25. array[index] = this.r;
  26. array[index + 1] = this.g;
  27. array[index + 2] = this.b;
  28. return this;
  29. };
  30. Color3.prototype.toColor4 = function (alpha) {
  31. if (alpha === void 0) { alpha = 1; }
  32. return new Color4(this.r, this.g, this.b, alpha);
  33. };
  34. Color3.prototype.asArray = function () {
  35. var result = [];
  36. this.toArray(result, 0);
  37. return result;
  38. };
  39. Color3.prototype.toLuminance = function () {
  40. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  41. };
  42. Color3.prototype.multiply = function (otherColor) {
  43. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  44. };
  45. Color3.prototype.multiplyToRef = function (otherColor, result) {
  46. result.r = this.r * otherColor.r;
  47. result.g = this.g * otherColor.g;
  48. result.b = this.b * otherColor.b;
  49. return this;
  50. };
  51. Color3.prototype.equals = function (otherColor) {
  52. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  53. };
  54. Color3.prototype.scale = function (scale) {
  55. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  56. };
  57. Color3.prototype.scaleToRef = function (scale, result) {
  58. result.r = this.r * scale;
  59. result.g = this.g * scale;
  60. result.b = this.b * scale;
  61. return this;
  62. };
  63. Color3.prototype.add = function (otherColor) {
  64. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  65. };
  66. Color3.prototype.addToRef = function (otherColor, result) {
  67. result.r = this.r + otherColor.r;
  68. result.g = this.g + otherColor.g;
  69. result.b = this.b + otherColor.b;
  70. return this;
  71. };
  72. Color3.prototype.subtract = function (otherColor) {
  73. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  74. };
  75. Color3.prototype.subtractToRef = function (otherColor, result) {
  76. result.r = this.r - otherColor.r;
  77. result.g = this.g - otherColor.g;
  78. result.b = this.b - otherColor.b;
  79. return this;
  80. };
  81. Color3.prototype.clone = function () {
  82. return new Color3(this.r, this.g, this.b);
  83. };
  84. Color3.prototype.copyFrom = function (source) {
  85. this.r = source.r;
  86. this.g = source.g;
  87. this.b = source.b;
  88. return this;
  89. };
  90. Color3.prototype.copyFromFloats = function (r, g, b) {
  91. this.r = r;
  92. this.g = g;
  93. this.b = b;
  94. return this;
  95. };
  96. // Statics
  97. Color3.FromArray = function (array, offset) {
  98. if (offset === void 0) { offset = 0; }
  99. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  100. };
  101. Color3.FromInts = function (r, g, b) {
  102. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  103. };
  104. Color3.Lerp = function (start, end, amount) {
  105. var r = start.r + ((end.r - start.r) * amount);
  106. var g = start.g + ((end.g - start.g) * amount);
  107. var b = start.b + ((end.b - start.b) * amount);
  108. return new Color3(r, g, b);
  109. };
  110. Color3.Red = function () {
  111. return new Color3(1, 0, 0);
  112. };
  113. Color3.Green = function () {
  114. return new Color3(0, 1, 0);
  115. };
  116. Color3.Blue = function () {
  117. return new Color3(0, 0, 1);
  118. };
  119. Color3.Black = function () {
  120. return new Color3(0, 0, 0);
  121. };
  122. Color3.White = function () {
  123. return new Color3(1, 1, 1);
  124. };
  125. Color3.Purple = function () {
  126. return new Color3(0.5, 0, 0.5);
  127. };
  128. Color3.Magenta = function () {
  129. return new Color3(1, 0, 1);
  130. };
  131. Color3.Yellow = function () {
  132. return new Color3(1, 1, 0);
  133. };
  134. Color3.Gray = function () {
  135. return new Color3(0.5, 0.5, 0.5);
  136. };
  137. return Color3;
  138. })();
  139. BABYLON.Color3 = Color3;
  140. var Color4 = (function () {
  141. function Color4(r, g, b, a) {
  142. this.r = r;
  143. this.g = g;
  144. this.b = b;
  145. this.a = a;
  146. }
  147. // Operators
  148. Color4.prototype.addInPlace = function (right) {
  149. this.r += right.r;
  150. this.g += right.g;
  151. this.b += right.b;
  152. this.a += right.a;
  153. return this;
  154. };
  155. Color4.prototype.asArray = function () {
  156. var result = [];
  157. this.toArray(result, 0);
  158. return result;
  159. };
  160. Color4.prototype.toArray = function (array, index) {
  161. if (index === undefined) {
  162. index = 0;
  163. }
  164. array[index] = this.r;
  165. array[index + 1] = this.g;
  166. array[index + 2] = this.b;
  167. array[index + 3] = this.a;
  168. return this;
  169. };
  170. Color4.prototype.add = function (right) {
  171. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  172. };
  173. Color4.prototype.subtract = function (right) {
  174. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  175. };
  176. Color4.prototype.subtractToRef = function (right, result) {
  177. result.r = this.r - right.r;
  178. result.g = this.g - right.g;
  179. result.b = this.b - right.b;
  180. result.a = this.a - right.a;
  181. return this;
  182. };
  183. Color4.prototype.scale = function (scale) {
  184. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  185. };
  186. Color4.prototype.scaleToRef = function (scale, result) {
  187. result.r = this.r * scale;
  188. result.g = this.g * scale;
  189. result.b = this.b * scale;
  190. result.a = this.a * scale;
  191. return this;
  192. };
  193. Color4.prototype.toString = function () {
  194. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  195. };
  196. Color4.prototype.clone = function () {
  197. return new Color4(this.r, this.g, this.b, this.a);
  198. };
  199. Color4.prototype.copyFrom = function (source) {
  200. this.r = source.r;
  201. this.g = source.g;
  202. this.b = source.b;
  203. this.a = source.a;
  204. return this;
  205. };
  206. // Statics
  207. Color4.Lerp = function (left, right, amount) {
  208. var result = new Color4(0, 0, 0, 0);
  209. Color4.LerpToRef(left, right, amount, result);
  210. return result;
  211. };
  212. Color4.LerpToRef = function (left, right, amount, result) {
  213. result.r = left.r + (right.r - left.r) * amount;
  214. result.g = left.g + (right.g - left.g) * amount;
  215. result.b = left.b + (right.b - left.b) * amount;
  216. result.a = left.a + (right.a - left.a) * amount;
  217. };
  218. Color4.FromArray = function (array, offset) {
  219. if (offset === void 0) { offset = 0; }
  220. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  221. };
  222. Color4.FromInts = function (r, g, b, a) {
  223. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  224. };
  225. return Color4;
  226. })();
  227. BABYLON.Color4 = Color4;
  228. var Vector2 = (function () {
  229. function Vector2(x, y) {
  230. this.x = x;
  231. this.y = y;
  232. }
  233. Vector2.prototype.toString = function () {
  234. return "{X: " + this.x + " Y:" + this.y + "}";
  235. };
  236. // Operators
  237. Vector2.prototype.toArray = function (array, index) {
  238. if (index === void 0) { index = 0; }
  239. array[index] = this.x;
  240. array[index + 1] = this.y;
  241. return this;
  242. };
  243. Vector2.prototype.asArray = function () {
  244. var result = [];
  245. this.toArray(result, 0);
  246. return result;
  247. };
  248. Vector2.prototype.copyFrom = function (source) {
  249. this.x = source.x;
  250. this.y = source.y;
  251. return this;
  252. };
  253. Vector2.prototype.copyFromFloats = function (x, y) {
  254. this.x = x;
  255. this.y = y;
  256. return this;
  257. };
  258. Vector2.prototype.add = function (otherVector) {
  259. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  260. };
  261. Vector2.prototype.addVector3 = function (otherVector) {
  262. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  263. };
  264. Vector2.prototype.subtract = function (otherVector) {
  265. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  266. };
  267. Vector2.prototype.subtractInPlace = function (otherVector) {
  268. this.x -= otherVector.x;
  269. this.y -= otherVector.y;
  270. return this;
  271. };
  272. Vector2.prototype.multiplyInPlace = function (otherVector) {
  273. this.x *= otherVector.x;
  274. this.y *= otherVector.y;
  275. return this;
  276. };
  277. Vector2.prototype.multiply = function (otherVector) {
  278. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  279. };
  280. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  281. result.x = this.x * otherVector.x;
  282. result.y = this.y * otherVector.y;
  283. return this;
  284. };
  285. Vector2.prototype.multiplyByFloats = function (x, y) {
  286. return new Vector2(this.x * x, this.y * y);
  287. };
  288. Vector2.prototype.divide = function (otherVector) {
  289. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  290. };
  291. Vector2.prototype.divideToRef = function (otherVector, result) {
  292. result.x = this.x / otherVector.x;
  293. result.y = this.y / otherVector.y;
  294. return this;
  295. };
  296. Vector2.prototype.negate = function () {
  297. return new Vector2(-this.x, -this.y);
  298. };
  299. Vector2.prototype.scaleInPlace = function (scale) {
  300. this.x *= scale;
  301. this.y *= scale;
  302. return this;
  303. };
  304. Vector2.prototype.scale = function (scale) {
  305. return new Vector2(this.x * scale, this.y * scale);
  306. };
  307. Vector2.prototype.equals = function (otherVector) {
  308. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  309. };
  310. // Properties
  311. Vector2.prototype.length = function () {
  312. return Math.sqrt(this.x * this.x + this.y * this.y);
  313. };
  314. Vector2.prototype.lengthSquared = function () {
  315. return (this.x * this.x + this.y * this.y);
  316. };
  317. // Methods
  318. Vector2.prototype.normalize = function () {
  319. var len = this.length();
  320. if (len === 0)
  321. return this;
  322. var num = 1.0 / len;
  323. this.x *= num;
  324. this.y *= num;
  325. return this;
  326. };
  327. Vector2.prototype.clone = function () {
  328. return new Vector2(this.x, this.y);
  329. };
  330. // Statics
  331. Vector2.Zero = function () {
  332. return new Vector2(0, 0);
  333. };
  334. Vector2.FromArray = function (array, offset) {
  335. if (offset === void 0) { offset = 0; }
  336. return new Vector2(array[offset], array[offset + 1]);
  337. };
  338. Vector2.FromArrayToRef = function (array, offset, result) {
  339. result.x = array[offset];
  340. result.y = array[offset + 1];
  341. };
  342. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  343. var squared = amount * amount;
  344. var cubed = amount * squared;
  345. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) + (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) + ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  346. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) + (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) + ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  347. return new Vector2(x, y);
  348. };
  349. Vector2.Clamp = function (value, min, max) {
  350. var x = value.x;
  351. x = (x > max.x) ? max.x : x;
  352. x = (x < min.x) ? min.x : x;
  353. var y = value.y;
  354. y = (y > max.y) ? max.y : y;
  355. y = (y < min.y) ? min.y : y;
  356. return new Vector2(x, y);
  357. };
  358. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  359. var squared = amount * amount;
  360. var cubed = amount * squared;
  361. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  362. var part2 = (-2.0 * cubed) + (3.0 * squared);
  363. var part3 = (cubed - (2.0 * squared)) + amount;
  364. var part4 = cubed - squared;
  365. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  366. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  367. return new Vector2(x, y);
  368. };
  369. Vector2.Lerp = function (start, end, amount) {
  370. var x = start.x + ((end.x - start.x) * amount);
  371. var y = start.y + ((end.y - start.y) * amount);
  372. return new Vector2(x, y);
  373. };
  374. Vector2.Dot = function (left, right) {
  375. return left.x * right.x + left.y * right.y;
  376. };
  377. Vector2.Normalize = function (vector) {
  378. var newVector = vector.clone();
  379. newVector.normalize();
  380. return newVector;
  381. };
  382. Vector2.Minimize = function (left, right) {
  383. var x = (left.x < right.x) ? left.x : right.x;
  384. var y = (left.y < right.y) ? left.y : right.y;
  385. return new Vector2(x, y);
  386. };
  387. Vector2.Maximize = function (left, right) {
  388. var x = (left.x > right.x) ? left.x : right.x;
  389. var y = (left.y > right.y) ? left.y : right.y;
  390. return new Vector2(x, y);
  391. };
  392. Vector2.Transform = function (vector, transformation) {
  393. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]);
  394. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]);
  395. return new Vector2(x, y);
  396. };
  397. Vector2.Distance = function (value1, value2) {
  398. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  399. };
  400. Vector2.DistanceSquared = function (value1, value2) {
  401. var x = value1.x - value2.x;
  402. var y = value1.y - value2.y;
  403. return (x * x) + (y * y);
  404. };
  405. return Vector2;
  406. })();
  407. BABYLON.Vector2 = Vector2;
  408. var Vector3 = (function () {
  409. function Vector3(x, y, z) {
  410. this.x = x;
  411. this.y = y;
  412. this.z = z;
  413. }
  414. Vector3.prototype.toString = function () {
  415. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  416. };
  417. // Operators
  418. Vector3.prototype.asArray = function () {
  419. var result = [];
  420. this.toArray(result, 0);
  421. return result;
  422. };
  423. Vector3.prototype.toArray = function (array, index) {
  424. if (index === void 0) { index = 0; }
  425. array[index] = this.x;
  426. array[index + 1] = this.y;
  427. array[index + 2] = this.z;
  428. return this;
  429. };
  430. Vector3.prototype.toQuaternion = function () {
  431. var result = new Quaternion(0, 0, 0, 1);
  432. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  433. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  434. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  435. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  436. var cosy = Math.cos(this.y * 0.5);
  437. var siny = Math.sin(this.y * 0.5);
  438. result.x = coszMinusx * siny;
  439. result.y = -sinzMinusx * siny;
  440. result.z = sinxPlusz * cosy;
  441. result.w = cosxPlusz * cosy;
  442. return result;
  443. };
  444. Vector3.prototype.addInPlace = function (otherVector) {
  445. this.x += otherVector.x;
  446. this.y += otherVector.y;
  447. this.z += otherVector.z;
  448. return this;
  449. };
  450. Vector3.prototype.add = function (otherVector) {
  451. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  452. };
  453. Vector3.prototype.addToRef = function (otherVector, result) {
  454. result.x = this.x + otherVector.x;
  455. result.y = this.y + otherVector.y;
  456. result.z = this.z + otherVector.z;
  457. return this;
  458. };
  459. Vector3.prototype.subtractInPlace = function (otherVector) {
  460. this.x -= otherVector.x;
  461. this.y -= otherVector.y;
  462. this.z -= otherVector.z;
  463. return this;
  464. };
  465. Vector3.prototype.subtract = function (otherVector) {
  466. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  467. };
  468. Vector3.prototype.subtractToRef = function (otherVector, result) {
  469. result.x = this.x - otherVector.x;
  470. result.y = this.y - otherVector.y;
  471. result.z = this.z - otherVector.z;
  472. return this;
  473. };
  474. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  475. return new Vector3(this.x - x, this.y - y, this.z - z);
  476. };
  477. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  478. result.x = this.x - x;
  479. result.y = this.y - y;
  480. result.z = this.z - z;
  481. return this;
  482. };
  483. Vector3.prototype.negate = function () {
  484. return new Vector3(-this.x, -this.y, -this.z);
  485. };
  486. Vector3.prototype.scaleInPlace = function (scale) {
  487. this.x *= scale;
  488. this.y *= scale;
  489. this.z *= scale;
  490. return this;
  491. };
  492. Vector3.prototype.scale = function (scale) {
  493. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  494. };
  495. Vector3.prototype.scaleToRef = function (scale, result) {
  496. result.x = this.x * scale;
  497. result.y = this.y * scale;
  498. result.z = this.z * scale;
  499. };
  500. Vector3.prototype.equals = function (otherVector) {
  501. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  502. };
  503. Vector3.prototype.equalsWithEpsilon = function (otherVector) {
  504. return Math.abs(this.x - otherVector.x) < BABYLON.Engine.Epsilon && Math.abs(this.y - otherVector.y) < BABYLON.Engine.Epsilon && Math.abs(this.z - otherVector.z) < BABYLON.Engine.Epsilon;
  505. };
  506. Vector3.prototype.equalsToFloats = function (x, y, z) {
  507. return this.x === x && this.y === y && this.z === z;
  508. };
  509. Vector3.prototype.multiplyInPlace = function (otherVector) {
  510. this.x *= otherVector.x;
  511. this.y *= otherVector.y;
  512. this.z *= otherVector.z;
  513. return this;
  514. };
  515. Vector3.prototype.multiply = function (otherVector) {
  516. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  517. };
  518. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  519. result.x = this.x * otherVector.x;
  520. result.y = this.y * otherVector.y;
  521. result.z = this.z * otherVector.z;
  522. return this;
  523. };
  524. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  525. return new Vector3(this.x * x, this.y * y, this.z * z);
  526. };
  527. Vector3.prototype.divide = function (otherVector) {
  528. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  529. };
  530. Vector3.prototype.divideToRef = function (otherVector, result) {
  531. result.x = this.x / otherVector.x;
  532. result.y = this.y / otherVector.y;
  533. result.z = this.z / otherVector.z;
  534. return this;
  535. };
  536. Vector3.prototype.MinimizeInPlace = function (other) {
  537. if (other.x < this.x)
  538. this.x = other.x;
  539. if (other.y < this.y)
  540. this.y = other.y;
  541. if (other.z < this.z)
  542. this.z = other.z;
  543. return this;
  544. };
  545. Vector3.prototype.MaximizeInPlace = function (other) {
  546. if (other.x > this.x)
  547. this.x = other.x;
  548. if (other.y > this.y)
  549. this.y = other.y;
  550. if (other.z > this.z)
  551. this.z = other.z;
  552. return this;
  553. };
  554. // Properties
  555. Vector3.prototype.length = function () {
  556. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  557. };
  558. Vector3.prototype.lengthSquared = function () {
  559. return (this.x * this.x + this.y * this.y + this.z * this.z);
  560. };
  561. // Methods
  562. Vector3.prototype.normalize = function () {
  563. var len = this.length();
  564. if (len === 0)
  565. return this;
  566. var num = 1.0 / len;
  567. this.x *= num;
  568. this.y *= num;
  569. this.z *= num;
  570. return this;
  571. };
  572. Vector3.prototype.clone = function () {
  573. return new Vector3(this.x, this.y, this.z);
  574. };
  575. Vector3.prototype.copyFrom = function (source) {
  576. this.x = source.x;
  577. this.y = source.y;
  578. this.z = source.z;
  579. return this;
  580. };
  581. Vector3.prototype.copyFromFloats = function (x, y, z) {
  582. this.x = x;
  583. this.y = y;
  584. this.z = z;
  585. return this;
  586. };
  587. // Statics
  588. Vector3.FromArray = function (array, offset) {
  589. if (!offset) {
  590. offset = 0;
  591. }
  592. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  593. };
  594. Vector3.FromArrayToRef = function (array, offset, result) {
  595. result.x = array[offset];
  596. result.y = array[offset + 1];
  597. result.z = array[offset + 2];
  598. };
  599. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  600. result.x = array[offset];
  601. result.y = array[offset + 1];
  602. result.z = array[offset + 2];
  603. };
  604. Vector3.FromFloatsToRef = function (x, y, z, result) {
  605. result.x = x;
  606. result.y = y;
  607. result.z = z;
  608. };
  609. Vector3.Zero = function () {
  610. return new Vector3(0, 0, 0);
  611. };
  612. Vector3.Up = function () {
  613. return new Vector3(0, 1.0, 0);
  614. };
  615. Vector3.TransformCoordinates = function (vector, transformation) {
  616. var result = Vector3.Zero();
  617. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  618. return result;
  619. };
  620. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  621. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  622. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  623. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  624. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  625. result.x = x / w;
  626. result.y = y / w;
  627. result.z = z / w;
  628. };
  629. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  630. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  631. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  632. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  633. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  634. result.x = rx / rw;
  635. result.y = ry / rw;
  636. result.z = rz / rw;
  637. };
  638. Vector3.TransformNormal = function (vector, transformation) {
  639. var result = Vector3.Zero();
  640. Vector3.TransformNormalToRef(vector, transformation, result);
  641. return result;
  642. };
  643. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  644. result.x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  645. result.y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  646. result.z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  647. };
  648. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  649. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  650. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  651. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  652. };
  653. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  654. var squared = amount * amount;
  655. var cubed = amount * squared;
  656. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) + (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) + ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  657. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) + (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) + ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  658. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) + (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) + ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  659. return new Vector3(x, y, z);
  660. };
  661. Vector3.Clamp = function (value, min, max) {
  662. var x = value.x;
  663. x = (x > max.x) ? max.x : x;
  664. x = (x < min.x) ? min.x : x;
  665. var y = value.y;
  666. y = (y > max.y) ? max.y : y;
  667. y = (y < min.y) ? min.y : y;
  668. var z = value.z;
  669. z = (z > max.z) ? max.z : z;
  670. z = (z < min.z) ? min.z : z;
  671. return new Vector3(x, y, z);
  672. };
  673. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  674. var squared = amount * amount;
  675. var cubed = amount * squared;
  676. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  677. var part2 = (-2.0 * cubed) + (3.0 * squared);
  678. var part3 = (cubed - (2.0 * squared)) + amount;
  679. var part4 = cubed - squared;
  680. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  681. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  682. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  683. return new Vector3(x, y, z);
  684. };
  685. Vector3.Lerp = function (start, end, amount) {
  686. var x = start.x + ((end.x - start.x) * amount);
  687. var y = start.y + ((end.y - start.y) * amount);
  688. var z = start.z + ((end.z - start.z) * amount);
  689. return new Vector3(x, y, z);
  690. };
  691. Vector3.Dot = function (left, right) {
  692. return (left.x * right.x + left.y * right.y + left.z * right.z);
  693. };
  694. Vector3.Cross = function (left, right) {
  695. var result = Vector3.Zero();
  696. Vector3.CrossToRef(left, right, result);
  697. return result;
  698. };
  699. Vector3.CrossToRef = function (left, right, result) {
  700. result.x = left.y * right.z - left.z * right.y;
  701. result.y = left.z * right.x - left.x * right.z;
  702. result.z = left.x * right.y - left.y * right.x;
  703. };
  704. Vector3.Normalize = function (vector) {
  705. var result = Vector3.Zero();
  706. Vector3.NormalizeToRef(vector, result);
  707. return result;
  708. };
  709. Vector3.NormalizeToRef = function (vector, result) {
  710. result.copyFrom(vector);
  711. result.normalize();
  712. };
  713. Vector3.Project = function (vector, world, transform, viewport) {
  714. var cw = viewport.width;
  715. var ch = viewport.height;
  716. var cx = viewport.x;
  717. var cy = viewport.y;
  718. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, 1, 0, cx + cw / 2.0, ch / 2.0 + cy, 0, 1);
  719. var finalMatrix = world.multiply(transform).multiply(viewportMatrix);
  720. return Vector3.TransformCoordinates(vector, finalMatrix);
  721. };
  722. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  723. var matrix = world.multiply(transform);
  724. matrix.invert();
  725. source.x = source.x / viewportWidth * 2 - 1;
  726. source.y = -(source.y / viewportHeight * 2 - 1);
  727. var vector = Vector3.TransformCoordinates(source, matrix);
  728. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  729. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  730. vector = vector.scale(1.0 / num);
  731. }
  732. return vector;
  733. };
  734. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  735. var matrix = world.multiply(view).multiply(projection);
  736. matrix.invert();
  737. source.x = source.x / viewportWidth * 2 - 1;
  738. source.y = -(source.y / viewportHeight * 2 - 1);
  739. var vector = Vector3.TransformCoordinates(source, matrix);
  740. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  741. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  742. vector = vector.scale(1.0 / num);
  743. }
  744. return vector;
  745. };
  746. Vector3.Minimize = function (left, right) {
  747. var min = left.clone();
  748. min.MinimizeInPlace(right);
  749. return min;
  750. };
  751. Vector3.Maximize = function (left, right) {
  752. var max = left.clone();
  753. max.MaximizeInPlace(right);
  754. return max;
  755. };
  756. Vector3.Distance = function (value1, value2) {
  757. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  758. };
  759. Vector3.DistanceSquared = function (value1, value2) {
  760. var x = value1.x - value2.x;
  761. var y = value1.y - value2.y;
  762. var z = value1.z - value2.z;
  763. return (x * x) + (y * y) + (z * z);
  764. };
  765. Vector3.Center = function (value1, value2) {
  766. var center = value1.add(value2);
  767. center.scaleInPlace(0.5);
  768. return center;
  769. };
  770. return Vector3;
  771. })();
  772. BABYLON.Vector3 = Vector3;
  773. //Vector4 class created for EulerAngle class conversion to Quaternion
  774. var Vector4 = (function () {
  775. function Vector4(x, y, z, w) {
  776. this.x = x;
  777. this.y = y;
  778. this.z = z;
  779. this.w = w;
  780. }
  781. Vector4.prototype.toString = function () {
  782. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "W:" + this.w + "}";
  783. };
  784. // Operators
  785. Vector4.prototype.asArray = function () {
  786. var result = [];
  787. this.toArray(result, 0);
  788. return result;
  789. };
  790. Vector4.prototype.toArray = function (array, index) {
  791. if (index === undefined) {
  792. index = 0;
  793. }
  794. array[index] = this.x;
  795. array[index + 1] = this.y;
  796. array[index + 2] = this.z;
  797. array[index + 3] = this.w;
  798. return this;
  799. };
  800. Vector4.prototype.addInPlace = function (otherVector) {
  801. this.x += otherVector.x;
  802. this.y += otherVector.y;
  803. this.z += otherVector.z;
  804. this.w += otherVector.w;
  805. return this;
  806. };
  807. Vector4.prototype.add = function (otherVector) {
  808. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  809. };
  810. Vector4.prototype.addToRef = function (otherVector, result) {
  811. result.x = this.x + otherVector.x;
  812. result.y = this.y + otherVector.y;
  813. result.z = this.z + otherVector.z;
  814. result.w = this.w + otherVector.w;
  815. return this;
  816. };
  817. Vector4.prototype.subtractInPlace = function (otherVector) {
  818. this.x -= otherVector.x;
  819. this.y -= otherVector.y;
  820. this.z -= otherVector.z;
  821. this.w -= otherVector.w;
  822. return this;
  823. };
  824. Vector4.prototype.subtract = function (otherVector) {
  825. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  826. };
  827. Vector4.prototype.subtractToRef = function (otherVector, result) {
  828. result.x = this.x - otherVector.x;
  829. result.y = this.y - otherVector.y;
  830. result.z = this.z - otherVector.z;
  831. result.w = this.w - otherVector.w;
  832. return this;
  833. };
  834. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  835. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  836. };
  837. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  838. result.x = this.x - x;
  839. result.y = this.y - y;
  840. result.z = this.z - z;
  841. result.w = this.w - w;
  842. return this;
  843. };
  844. Vector4.prototype.negate = function () {
  845. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  846. };
  847. Vector4.prototype.scaleInPlace = function (scale) {
  848. this.x *= scale;
  849. this.y *= scale;
  850. this.z *= scale;
  851. this.w *= scale;
  852. return this;
  853. };
  854. Vector4.prototype.scale = function (scale) {
  855. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  856. };
  857. Vector4.prototype.scaleToRef = function (scale, result) {
  858. result.x = this.x * scale;
  859. result.y = this.y * scale;
  860. result.z = this.z * scale;
  861. result.w = this.w * scale;
  862. };
  863. Vector4.prototype.equals = function (otherVector) {
  864. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  865. };
  866. Vector4.prototype.equalsWithEpsilon = function (otherVector) {
  867. return Math.abs(this.x - otherVector.x) < BABYLON.Engine.Epsilon && Math.abs(this.y - otherVector.y) < BABYLON.Engine.Epsilon && Math.abs(this.z - otherVector.z) < BABYLON.Engine.Epsilon && Math.abs(this.w - otherVector.w) < BABYLON.Engine.Epsilon;
  868. };
  869. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  870. return this.x === x && this.y === y && this.z === z && this.w === w;
  871. };
  872. Vector4.prototype.multiplyInPlace = function (otherVector) {
  873. this.x *= otherVector.x;
  874. this.y *= otherVector.y;
  875. this.z *= otherVector.z;
  876. this.w *= otherVector.w;
  877. return this;
  878. };
  879. Vector4.prototype.multiply = function (otherVector) {
  880. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  881. };
  882. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  883. result.x = this.x * otherVector.x;
  884. result.y = this.y * otherVector.y;
  885. result.z = this.z * otherVector.z;
  886. result.w = this.w * otherVector.w;
  887. return this;
  888. };
  889. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  890. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  891. };
  892. Vector4.prototype.divide = function (otherVector) {
  893. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  894. };
  895. Vector4.prototype.divideToRef = function (otherVector, result) {
  896. result.x = this.x / otherVector.x;
  897. result.y = this.y / otherVector.y;
  898. result.z = this.z / otherVector.z;
  899. result.w = this.w / otherVector.w;
  900. return this;
  901. };
  902. Vector4.prototype.MinimizeInPlace = function (other) {
  903. if (other.x < this.x)
  904. this.x = other.x;
  905. if (other.y < this.y)
  906. this.y = other.y;
  907. if (other.z < this.z)
  908. this.z = other.z;
  909. if (other.w < this.w)
  910. this.w = other.w;
  911. return this;
  912. };
  913. Vector4.prototype.MaximizeInPlace = function (other) {
  914. if (other.x > this.x)
  915. this.x = other.x;
  916. if (other.y > this.y)
  917. this.y = other.y;
  918. if (other.z > this.z)
  919. this.z = other.z;
  920. if (other.w > this.w)
  921. this.w = other.w;
  922. return this;
  923. };
  924. // Properties
  925. Vector4.prototype.length = function () {
  926. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  927. };
  928. Vector4.prototype.lengthSquared = function () {
  929. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  930. };
  931. // Methods
  932. Vector4.prototype.normalize = function () {
  933. var len = this.length();
  934. if (len === 0)
  935. return this;
  936. var num = 1.0 / len;
  937. this.x *= num;
  938. this.y *= num;
  939. this.z *= num;
  940. this.w *= num;
  941. return this;
  942. };
  943. Vector4.prototype.clone = function () {
  944. return new Vector4(this.x, this.y, this.z, this.w);
  945. };
  946. Vector4.prototype.copyFrom = function (source) {
  947. this.x = source.x;
  948. this.y = source.y;
  949. this.z = source.z;
  950. this.w = source.w;
  951. return this;
  952. };
  953. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  954. this.x = x;
  955. this.y = y;
  956. this.z = z;
  957. this.w = w;
  958. return this;
  959. };
  960. // Statics
  961. Vector4.FromArray = function (array, offset) {
  962. if (!offset) {
  963. offset = 0;
  964. }
  965. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  966. };
  967. Vector4.FromArrayToRef = function (array, offset, result) {
  968. result.x = array[offset];
  969. result.y = array[offset + 1];
  970. result.z = array[offset + 2];
  971. result.w = array[offset + 3];
  972. };
  973. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  974. result.x = array[offset];
  975. result.y = array[offset + 1];
  976. result.z = array[offset + 2];
  977. result.w = array[offset + 3];
  978. };
  979. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  980. result.x = x;
  981. result.y = y;
  982. result.z = z;
  983. result.w = w;
  984. };
  985. Vector4.Zero = function () {
  986. return new Vector4(0, 0, 0, 0);
  987. };
  988. Vector4.Normalize = function (vector) {
  989. var result = Vector4.Zero();
  990. Vector4.NormalizeToRef(vector, result);
  991. return result;
  992. };
  993. Vector4.NormalizeToRef = function (vector, result) {
  994. result.copyFrom(vector);
  995. result.normalize();
  996. };
  997. Vector4.Minimize = function (left, right) {
  998. var min = left.clone();
  999. min.MinimizeInPlace(right);
  1000. return min;
  1001. };
  1002. Vector4.Maximize = function (left, right) {
  1003. var max = left.clone();
  1004. max.MaximizeInPlace(right);
  1005. return max;
  1006. };
  1007. Vector4.Distance = function (value1, value2) {
  1008. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  1009. };
  1010. Vector4.DistanceSquared = function (value1, value2) {
  1011. var x = value1.x - value2.x;
  1012. var y = value1.y - value2.y;
  1013. var z = value1.z - value2.z;
  1014. var w = value1.w - value2.w;
  1015. return (x * x) + (y * y) + (z * z) + (w * w);
  1016. };
  1017. Vector4.Center = function (value1, value2) {
  1018. var center = value1.add(value2);
  1019. center.scaleInPlace(0.5);
  1020. return center;
  1021. };
  1022. return Vector4;
  1023. })();
  1024. BABYLON.Vector4 = Vector4;
  1025. var Quaternion = (function () {
  1026. function Quaternion(x, y, z, w) {
  1027. if (x === void 0) { x = 0; }
  1028. if (y === void 0) { y = 0; }
  1029. if (z === void 0) { z = 0; }
  1030. if (w === void 0) { w = 1; }
  1031. this.x = x;
  1032. this.y = y;
  1033. this.z = z;
  1034. this.w = w;
  1035. }
  1036. Quaternion.prototype.toString = function () {
  1037. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1038. };
  1039. Quaternion.prototype.asArray = function () {
  1040. return [this.x, this.y, this.z, this.w];
  1041. };
  1042. Quaternion.prototype.equals = function (otherQuaternion) {
  1043. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  1044. };
  1045. Quaternion.prototype.clone = function () {
  1046. return new Quaternion(this.x, this.y, this.z, this.w);
  1047. };
  1048. Quaternion.prototype.copyFrom = function (other) {
  1049. this.x = other.x;
  1050. this.y = other.y;
  1051. this.z = other.z;
  1052. this.w = other.w;
  1053. return this;
  1054. };
  1055. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  1056. this.x = x;
  1057. this.y = y;
  1058. this.z = z;
  1059. this.w = w;
  1060. return this;
  1061. };
  1062. Quaternion.prototype.add = function (other) {
  1063. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  1064. };
  1065. Quaternion.prototype.subtract = function (other) {
  1066. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  1067. };
  1068. Quaternion.prototype.scale = function (value) {
  1069. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  1070. };
  1071. Quaternion.prototype.multiply = function (q1) {
  1072. var result = new Quaternion(0, 0, 0, 1.0);
  1073. this.multiplyToRef(q1, result);
  1074. return result;
  1075. };
  1076. Quaternion.prototype.multiplyToRef = function (q1, result) {
  1077. result.x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  1078. result.y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  1079. result.z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  1080. result.w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  1081. return this;
  1082. };
  1083. Quaternion.prototype.length = function () {
  1084. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  1085. };
  1086. Quaternion.prototype.normalize = function () {
  1087. var length = 1.0 / this.length();
  1088. this.x *= length;
  1089. this.y *= length;
  1090. this.z *= length;
  1091. this.w *= length;
  1092. return this;
  1093. };
  1094. Quaternion.prototype.toEulerAngles = function () {
  1095. var result = Vector3.Zero();
  1096. this.toEulerAnglesToRef(result);
  1097. return result;
  1098. };
  1099. Quaternion.prototype.toEulerAnglesToRef = function (result) {
  1100. //result is an EulerAngles in the in the z-x-z convention
  1101. var qx = this.x;
  1102. var qy = this.y;
  1103. var qz = this.z;
  1104. var qw = this.w;
  1105. var qxy = qx * qy;
  1106. var qxz = qx * qz;
  1107. var qwy = qw * qy;
  1108. var qwz = qw * qz;
  1109. var qwx = qw * qx;
  1110. var qyz = qy * qz;
  1111. var sqx = qx * qx;
  1112. var sqy = qy * qy;
  1113. var determinant = sqx + sqy;
  1114. if (determinant !== 0.000 && determinant !== 1.000) {
  1115. result.x = Math.atan2(qxz + qwy, qwx - qyz);
  1116. result.y = Math.acos(1 - 2 * determinant);
  1117. result.z = Math.atan2(qxz - qwy, qwx + qyz);
  1118. }
  1119. else {
  1120. if (determinant === 0.0) {
  1121. result.x = 0.0;
  1122. result.y = 0.0;
  1123. result.z = Math.atan2(qxy - qwz, 0.5 - sqy - qz * qz); //actually, degeneracy gives us choice with x+z=Math.atan2(qxy-qwz,0.5-sqy-qz*qz)
  1124. }
  1125. else {
  1126. result.x = Math.atan2(qxy - qwz, 0.5 - sqy - qz * qz); //actually, degeneracy gives us choice with x-z=Math.atan2(qxy-qwz,0.5-sqy-qz*qz)
  1127. result.y = Math.PI;
  1128. result.z = 0.0;
  1129. }
  1130. }
  1131. return this;
  1132. };
  1133. Quaternion.prototype.toRotationMatrix = function (result) {
  1134. var xx = this.x * this.x;
  1135. var yy = this.y * this.y;
  1136. var zz = this.z * this.z;
  1137. var xy = this.x * this.y;
  1138. var zw = this.z * this.w;
  1139. var zx = this.z * this.x;
  1140. var yw = this.y * this.w;
  1141. var yz = this.y * this.z;
  1142. var xw = this.x * this.w;
  1143. result.m[0] = 1.0 - (2.0 * (yy + zz));
  1144. result.m[1] = 2.0 * (xy + zw);
  1145. result.m[2] = 2.0 * (zx - yw);
  1146. result.m[3] = 0;
  1147. result.m[4] = 2.0 * (xy - zw);
  1148. result.m[5] = 1.0 - (2.0 * (zz + xx));
  1149. result.m[6] = 2.0 * (yz + xw);
  1150. result.m[7] = 0;
  1151. result.m[8] = 2.0 * (zx + yw);
  1152. result.m[9] = 2.0 * (yz - xw);
  1153. result.m[10] = 1.0 - (2.0 * (yy + xx));
  1154. result.m[11] = 0;
  1155. result.m[12] = 0;
  1156. result.m[13] = 0;
  1157. result.m[14] = 0;
  1158. result.m[15] = 1.0;
  1159. return this;
  1160. };
  1161. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  1162. Quaternion.FromRotationMatrixToRef(matrix, this);
  1163. return this;
  1164. };
  1165. // Statics
  1166. Quaternion.FromRotationMatrix = function (matrix) {
  1167. var result = new Quaternion();
  1168. Quaternion.FromRotationMatrixToRef(matrix, result);
  1169. return result;
  1170. };
  1171. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  1172. var data = matrix.m;
  1173. var m11 = data[0], m12 = data[4], m13 = data[8];
  1174. var m21 = data[1], m22 = data[5], m23 = data[9];
  1175. var m31 = data[2], m32 = data[6], m33 = data[10];
  1176. var trace = m11 + m22 + m33;
  1177. var s;
  1178. if (trace > 0) {
  1179. s = 0.5 / Math.sqrt(trace + 1.0);
  1180. result.w = 0.25 / s;
  1181. result.x = (m32 - m23) * s;
  1182. result.y = (m13 - m31) * s;
  1183. result.z = (m21 - m12) * s;
  1184. }
  1185. else if (m11 > m22 && m11 > m33) {
  1186. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1187. result.w = (m32 - m23) / s;
  1188. result.x = 0.25 * s;
  1189. result.y = (m12 + m21) / s;
  1190. result.z = (m13 + m31) / s;
  1191. }
  1192. else if (m22 > m33) {
  1193. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1194. result.w = (m13 - m31) / s;
  1195. result.x = (m12 + m21) / s;
  1196. result.y = 0.25 * s;
  1197. result.z = (m23 + m32) / s;
  1198. }
  1199. else {
  1200. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1201. result.w = (m21 - m12) / s;
  1202. result.x = (m13 + m31) / s;
  1203. result.y = (m23 + m32) / s;
  1204. result.z = 0.25 * s;
  1205. }
  1206. };
  1207. Quaternion.Inverse = function (q) {
  1208. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  1209. };
  1210. Quaternion.Identity = function () {
  1211. return new Quaternion(0, 0, 0, 1);
  1212. };
  1213. Quaternion.RotationAxis = function (axis, angle) {
  1214. var result = new Quaternion();
  1215. var sin = Math.sin(angle / 2);
  1216. result.w = Math.cos(angle / 2);
  1217. result.x = axis.x * sin;
  1218. result.y = axis.y * sin;
  1219. result.z = axis.z * sin;
  1220. return result;
  1221. };
  1222. Quaternion.FromArray = function (array, offset) {
  1223. if (!offset) {
  1224. offset = 0;
  1225. }
  1226. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1227. };
  1228. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1229. var result = new Quaternion();
  1230. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1231. return result;
  1232. };
  1233. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1234. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  1235. var halfRoll = roll * 0.5;
  1236. var halfPitch = pitch * 0.5;
  1237. var halfYaw = yaw * 0.5;
  1238. var sinRoll = Math.sin(halfRoll);
  1239. var cosRoll = Math.cos(halfRoll);
  1240. var sinPitch = Math.sin(halfPitch);
  1241. var cosPitch = Math.cos(halfPitch);
  1242. var sinYaw = Math.sin(halfYaw);
  1243. var cosYaw = Math.cos(halfYaw);
  1244. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  1245. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  1246. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  1247. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  1248. };
  1249. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  1250. var result = new Quaternion();
  1251. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  1252. return result;
  1253. };
  1254. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  1255. // Produces a quaternion from Euler angles in the z-x-z orientation
  1256. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  1257. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  1258. var halfBeta = beta * 0.5;
  1259. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1260. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1261. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1262. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1263. };
  1264. Quaternion.Slerp = function (left, right, amount) {
  1265. var num2;
  1266. var num3;
  1267. var num = amount;
  1268. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  1269. var flag = false;
  1270. if (num4 < 0) {
  1271. flag = true;
  1272. num4 = -num4;
  1273. }
  1274. if (num4 > 0.999999) {
  1275. num3 = 1 - num;
  1276. num2 = flag ? -num : num;
  1277. }
  1278. else {
  1279. var num5 = Math.acos(num4);
  1280. var num6 = (1.0 / Math.sin(num5));
  1281. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  1282. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  1283. }
  1284. return new Quaternion((num3 * left.x) + (num2 * right.x), (num3 * left.y) + (num2 * right.y), (num3 * left.z) + (num2 * right.z), (num3 * left.w) + (num2 * right.w));
  1285. };
  1286. return Quaternion;
  1287. })();
  1288. BABYLON.Quaternion = Quaternion;
  1289. var Matrix = (function () {
  1290. function Matrix() {
  1291. this.m = new Float32Array(16);
  1292. }
  1293. // Properties
  1294. Matrix.prototype.isIdentity = function () {
  1295. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  1296. return false;
  1297. if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 || this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 || this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 || this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0)
  1298. return false;
  1299. return true;
  1300. };
  1301. Matrix.prototype.determinant = function () {
  1302. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  1303. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  1304. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  1305. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  1306. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  1307. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  1308. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) - (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) - (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  1309. };
  1310. // Methods
  1311. Matrix.prototype.toArray = function () {
  1312. return this.m;
  1313. };
  1314. Matrix.prototype.asArray = function () {
  1315. return this.toArray();
  1316. };
  1317. Matrix.prototype.invert = function () {
  1318. this.invertToRef(this);
  1319. return this;
  1320. };
  1321. Matrix.prototype.invertToRef = function (other) {
  1322. var l1 = this.m[0];
  1323. var l2 = this.m[1];
  1324. var l3 = this.m[2];
  1325. var l4 = this.m[3];
  1326. var l5 = this.m[4];
  1327. var l6 = this.m[5];
  1328. var l7 = this.m[6];
  1329. var l8 = this.m[7];
  1330. var l9 = this.m[8];
  1331. var l10 = this.m[9];
  1332. var l11 = this.m[10];
  1333. var l12 = this.m[11];
  1334. var l13 = this.m[12];
  1335. var l14 = this.m[13];
  1336. var l15 = this.m[14];
  1337. var l16 = this.m[15];
  1338. var l17 = (l11 * l16) - (l12 * l15);
  1339. var l18 = (l10 * l16) - (l12 * l14);
  1340. var l19 = (l10 * l15) - (l11 * l14);
  1341. var l20 = (l9 * l16) - (l12 * l13);
  1342. var l21 = (l9 * l15) - (l11 * l13);
  1343. var l22 = (l9 * l14) - (l10 * l13);
  1344. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  1345. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  1346. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  1347. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  1348. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  1349. var l28 = (l7 * l16) - (l8 * l15);
  1350. var l29 = (l6 * l16) - (l8 * l14);
  1351. var l30 = (l6 * l15) - (l7 * l14);
  1352. var l31 = (l5 * l16) - (l8 * l13);
  1353. var l32 = (l5 * l15) - (l7 * l13);
  1354. var l33 = (l5 * l14) - (l6 * l13);
  1355. var l34 = (l7 * l12) - (l8 * l11);
  1356. var l35 = (l6 * l12) - (l8 * l10);
  1357. var l36 = (l6 * l11) - (l7 * l10);
  1358. var l37 = (l5 * l12) - (l8 * l9);
  1359. var l38 = (l5 * l11) - (l7 * l9);
  1360. var l39 = (l5 * l10) - (l6 * l9);
  1361. other.m[0] = l23 * l27;
  1362. other.m[4] = l24 * l27;
  1363. other.m[8] = l25 * l27;
  1364. other.m[12] = l26 * l27;
  1365. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  1366. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  1367. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  1368. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  1369. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  1370. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  1371. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  1372. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  1373. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  1374. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  1375. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  1376. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  1377. return this;
  1378. };
  1379. Matrix.prototype.setTranslation = function (vector3) {
  1380. this.m[12] = vector3.x;
  1381. this.m[13] = vector3.y;
  1382. this.m[14] = vector3.z;
  1383. return this;
  1384. };
  1385. Matrix.prototype.multiply = function (other) {
  1386. var result = new Matrix();
  1387. this.multiplyToRef(other, result);
  1388. return result;
  1389. };
  1390. Matrix.prototype.copyFrom = function (other) {
  1391. for (var index = 0; index < 16; index++) {
  1392. this.m[index] = other.m[index];
  1393. }
  1394. return this;
  1395. };
  1396. Matrix.prototype.copyToArray = function (array, offset) {
  1397. if (offset === void 0) { offset = 0; }
  1398. for (var index = 0; index < 16; index++) {
  1399. array[offset + index] = this.m[index];
  1400. }
  1401. return this;
  1402. };
  1403. Matrix.prototype.multiplyToRef = function (other, result) {
  1404. this.multiplyToArray(other, result.m, 0);
  1405. return this;
  1406. };
  1407. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1408. var tm0 = this.m[0];
  1409. var tm1 = this.m[1];
  1410. var tm2 = this.m[2];
  1411. var tm3 = this.m[3];
  1412. var tm4 = this.m[4];
  1413. var tm5 = this.m[5];
  1414. var tm6 = this.m[6];
  1415. var tm7 = this.m[7];
  1416. var tm8 = this.m[8];
  1417. var tm9 = this.m[9];
  1418. var tm10 = this.m[10];
  1419. var tm11 = this.m[11];
  1420. var tm12 = this.m[12];
  1421. var tm13 = this.m[13];
  1422. var tm14 = this.m[14];
  1423. var tm15 = this.m[15];
  1424. var om0 = other.m[0];
  1425. var om1 = other.m[1];
  1426. var om2 = other.m[2];
  1427. var om3 = other.m[3];
  1428. var om4 = other.m[4];
  1429. var om5 = other.m[5];
  1430. var om6 = other.m[6];
  1431. var om7 = other.m[7];
  1432. var om8 = other.m[8];
  1433. var om9 = other.m[9];
  1434. var om10 = other.m[10];
  1435. var om11 = other.m[11];
  1436. var om12 = other.m[12];
  1437. var om13 = other.m[13];
  1438. var om14 = other.m[14];
  1439. var om15 = other.m[15];
  1440. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1441. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1442. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1443. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1444. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1445. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1446. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1447. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1448. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1449. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1450. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1451. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1452. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1453. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1454. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1455. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1456. return this;
  1457. };
  1458. Matrix.prototype.equals = function (value) {
  1459. return value && (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] && this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] && this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] && this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  1460. };
  1461. Matrix.prototype.clone = function () {
  1462. return Matrix.FromValues(this.m[0], this.m[1], this.m[2], this.m[3], this.m[4], this.m[5], this.m[6], this.m[7], this.m[8], this.m[9], this.m[10], this.m[11], this.m[12], this.m[13], this.m[14], this.m[15]);
  1463. };
  1464. Matrix.prototype.decompose = function (scale, rotation, translation) {
  1465. translation.x = this.m[12];
  1466. translation.y = this.m[13];
  1467. translation.z = this.m[14];
  1468. var xs = BABYLON.Tools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  1469. var ys = BABYLON.Tools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  1470. var zs = BABYLON.Tools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  1471. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  1472. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  1473. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  1474. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  1475. rotation.x = 0;
  1476. rotation.y = 0;
  1477. rotation.z = 0;
  1478. rotation.w = 1;
  1479. return false;
  1480. }
  1481. var rotationMatrix = Matrix.FromValues(this.m[0] / scale.x, this.m[1] / scale.x, this.m[2] / scale.x, 0, this.m[4] / scale.y, this.m[5] / scale.y, this.m[6] / scale.y, 0, this.m[8] / scale.z, this.m[9] / scale.z, this.m[10] / scale.z, 0, 0, 0, 0, 1);
  1482. Quaternion.FromRotationMatrixToRef(rotationMatrix, rotation);
  1483. return true;
  1484. };
  1485. // Statics
  1486. Matrix.FromArray = function (array, offset) {
  1487. var result = new Matrix();
  1488. if (!offset) {
  1489. offset = 0;
  1490. }
  1491. Matrix.FromArrayToRef(array, offset, result);
  1492. return result;
  1493. };
  1494. Matrix.FromArrayToRef = function (array, offset, result) {
  1495. for (var index = 0; index < 16; index++) {
  1496. result.m[index] = array[index + offset];
  1497. }
  1498. };
  1499. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  1500. result.m[0] = initialM11;
  1501. result.m[1] = initialM12;
  1502. result.m[2] = initialM13;
  1503. result.m[3] = initialM14;
  1504. result.m[4] = initialM21;
  1505. result.m[5] = initialM22;
  1506. result.m[6] = initialM23;
  1507. result.m[7] = initialM24;
  1508. result.m[8] = initialM31;
  1509. result.m[9] = initialM32;
  1510. result.m[10] = initialM33;
  1511. result.m[11] = initialM34;
  1512. result.m[12] = initialM41;
  1513. result.m[13] = initialM42;
  1514. result.m[14] = initialM43;
  1515. result.m[15] = initialM44;
  1516. };
  1517. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  1518. var result = new Matrix();
  1519. result.m[0] = initialM11;
  1520. result.m[1] = initialM12;
  1521. result.m[2] = initialM13;
  1522. result.m[3] = initialM14;
  1523. result.m[4] = initialM21;
  1524. result.m[5] = initialM22;
  1525. result.m[6] = initialM23;
  1526. result.m[7] = initialM24;
  1527. result.m[8] = initialM31;
  1528. result.m[9] = initialM32;
  1529. result.m[10] = initialM33;
  1530. result.m[11] = initialM34;
  1531. result.m[12] = initialM41;
  1532. result.m[13] = initialM42;
  1533. result.m[14] = initialM43;
  1534. result.m[15] = initialM44;
  1535. return result;
  1536. };
  1537. Matrix.Compose = function (scale, rotation, translation) {
  1538. var result = Matrix.FromValues(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1);
  1539. var rotationMatrix = Matrix.Identity();
  1540. rotation.toRotationMatrix(rotationMatrix);
  1541. result = result.multiply(rotationMatrix);
  1542. result.setTranslation(translation);
  1543. return result;
  1544. };
  1545. Matrix.Identity = function () {
  1546. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  1547. };
  1548. Matrix.IdentityToRef = function (result) {
  1549. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  1550. };
  1551. Matrix.Zero = function () {
  1552. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  1553. };
  1554. Matrix.RotationX = function (angle) {
  1555. var result = new Matrix();
  1556. Matrix.RotationXToRef(angle, result);
  1557. return result;
  1558. };
  1559. Matrix.Invert = function (source) {
  1560. var result = new Matrix();
  1561. source.invertToRef(result);
  1562. return result;
  1563. };
  1564. Matrix.RotationXToRef = function (angle, result) {
  1565. var s = Math.sin(angle);
  1566. var c = Math.cos(angle);
  1567. result.m[0] = 1.0;
  1568. result.m[15] = 1.0;
  1569. result.m[5] = c;
  1570. result.m[10] = c;
  1571. result.m[9] = -s;
  1572. result.m[6] = s;
  1573. result.m[1] = 0;
  1574. result.m[2] = 0;
  1575. result.m[3] = 0;
  1576. result.m[4] = 0;
  1577. result.m[7] = 0;
  1578. result.m[8] = 0;
  1579. result.m[11] = 0;
  1580. result.m[12] = 0;
  1581. result.m[13] = 0;
  1582. result.m[14] = 0;
  1583. };
  1584. Matrix.RotationY = function (angle) {
  1585. var result = new Matrix();
  1586. Matrix.RotationYToRef(angle, result);
  1587. return result;
  1588. };
  1589. Matrix.RotationYToRef = function (angle, result) {
  1590. var s = Math.sin(angle);
  1591. var c = Math.cos(angle);
  1592. result.m[5] = 1.0;
  1593. result.m[15] = 1.0;
  1594. result.m[0] = c;
  1595. result.m[2] = -s;
  1596. result.m[8] = s;
  1597. result.m[10] = c;
  1598. result.m[1] = 0;
  1599. result.m[3] = 0;
  1600. result.m[4] = 0;
  1601. result.m[6] = 0;
  1602. result.m[7] = 0;
  1603. result.m[9] = 0;
  1604. result.m[11] = 0;
  1605. result.m[12] = 0;
  1606. result.m[13] = 0;
  1607. result.m[14] = 0;
  1608. };
  1609. Matrix.RotationZ = function (angle) {
  1610. var result = new Matrix();
  1611. Matrix.RotationZToRef(angle, result);
  1612. return result;
  1613. };
  1614. Matrix.RotationZToRef = function (angle, result) {
  1615. var s = Math.sin(angle);
  1616. var c = Math.cos(angle);
  1617. result.m[10] = 1.0;
  1618. result.m[15] = 1.0;
  1619. result.m[0] = c;
  1620. result.m[1] = s;
  1621. result.m[4] = -s;
  1622. result.m[5] = c;
  1623. result.m[2] = 0;
  1624. result.m[3] = 0;
  1625. result.m[6] = 0;
  1626. result.m[7] = 0;
  1627. result.m[8] = 0;
  1628. result.m[9] = 0;
  1629. result.m[11] = 0;
  1630. result.m[12] = 0;
  1631. result.m[13] = 0;
  1632. result.m[14] = 0;
  1633. };
  1634. Matrix.RotationAxis = function (axis, angle) {
  1635. var s = Math.sin(-angle);
  1636. var c = Math.cos(-angle);
  1637. var c1 = 1 - c;
  1638. axis.normalize();
  1639. var result = Matrix.Zero();
  1640. result.m[0] = (axis.x * axis.x) * c1 + c;
  1641. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  1642. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  1643. result.m[3] = 0.0;
  1644. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  1645. result.m[5] = (axis.y * axis.y) * c1 + c;
  1646. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  1647. result.m[7] = 0.0;
  1648. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  1649. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  1650. result.m[10] = (axis.z * axis.z) * c1 + c;
  1651. result.m[11] = 0.0;
  1652. result.m[15] = 1.0;
  1653. return result;
  1654. };
  1655. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1656. var result = new Matrix();
  1657. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1658. return result;
  1659. };
  1660. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1661. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  1662. this._tempQuaternion.toRotationMatrix(result);
  1663. };
  1664. Matrix.Scaling = function (x, y, z) {
  1665. var result = Matrix.Zero();
  1666. Matrix.ScalingToRef(x, y, z, result);
  1667. return result;
  1668. };
  1669. Matrix.ScalingToRef = function (x, y, z, result) {
  1670. result.m[0] = x;
  1671. result.m[1] = 0;
  1672. result.m[2] = 0;
  1673. result.m[3] = 0;
  1674. result.m[4] = 0;
  1675. result.m[5] = y;
  1676. result.m[6] = 0;
  1677. result.m[7] = 0;
  1678. result.m[8] = 0;
  1679. result.m[9] = 0;
  1680. result.m[10] = z;
  1681. result.m[11] = 0;
  1682. result.m[12] = 0;
  1683. result.m[13] = 0;
  1684. result.m[14] = 0;
  1685. result.m[15] = 1.0;
  1686. };
  1687. Matrix.Translation = function (x, y, z) {
  1688. var result = Matrix.Identity();
  1689. Matrix.TranslationToRef(x, y, z, result);
  1690. return result;
  1691. };
  1692. Matrix.TranslationToRef = function (x, y, z, result) {
  1693. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  1694. };
  1695. Matrix.LookAtLH = function (eye, target, up) {
  1696. var result = Matrix.Zero();
  1697. Matrix.LookAtLHToRef(eye, target, up, result);
  1698. return result;
  1699. };
  1700. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  1701. // Z axis
  1702. target.subtractToRef(eye, this._zAxis);
  1703. this._zAxis.normalize();
  1704. // X axis
  1705. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  1706. this._xAxis.normalize();
  1707. // Y axis
  1708. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  1709. this._yAxis.normalize();
  1710. // Eye angles
  1711. var ex = -Vector3.Dot(this._xAxis, eye);
  1712. var ey = -Vector3.Dot(this._yAxis, eye);
  1713. var ez = -Vector3.Dot(this._zAxis, eye);
  1714. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  1715. };
  1716. Matrix.OrthoLH = function (width, height, znear, zfar) {
  1717. var hw = 2.0 / width;
  1718. var hh = 2.0 / height;
  1719. var id = 1.0 / (zfar - znear);
  1720. var nid = znear / (znear - zfar);
  1721. return Matrix.FromValues(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1);
  1722. };
  1723. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  1724. var matrix = Matrix.Zero();
  1725. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  1726. return matrix;
  1727. };
  1728. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  1729. result.m[0] = 2.0 / (right - left);
  1730. result.m[1] = result.m[2] = result.m[3] = 0;
  1731. result.m[5] = 2.0 / (top - bottom);
  1732. result.m[4] = result.m[6] = result.m[7] = 0;
  1733. result.m[10] = -1.0 / (znear - zfar);
  1734. result.m[8] = result.m[9] = result.m[11] = 0;
  1735. result.m[12] = (left + right) / (left - right);
  1736. result.m[13] = (top + bottom) / (bottom - top);
  1737. result.m[14] = znear / (znear - zfar);
  1738. result.m[15] = 1.0;
  1739. };
  1740. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  1741. var matrix = Matrix.Zero();
  1742. matrix.m[0] = (2.0 * znear) / width;
  1743. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  1744. matrix.m[5] = (2.0 * znear) / height;
  1745. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  1746. matrix.m[10] = -zfar / (znear - zfar);
  1747. matrix.m[8] = matrix.m[9] = 0.0;
  1748. matrix.m[11] = 1.0;
  1749. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  1750. matrix.m[14] = (znear * zfar) / (znear - zfar);
  1751. return matrix;
  1752. };
  1753. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  1754. var matrix = Matrix.Zero();
  1755. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  1756. return matrix;
  1757. };
  1758. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, fovMode) {
  1759. if (fovMode === void 0) { fovMode = BABYLON.Camera.FOVMODE_VERTICAL_FIXED; }
  1760. var tan = 1.0 / (Math.tan(fov * 0.5));
  1761. var v_fixed = (fovMode === BABYLON.Camera.FOVMODE_VERTICAL_FIXED);
  1762. if (v_fixed) {
  1763. result.m[0] = tan / aspect;
  1764. }
  1765. else {
  1766. result.m[0] = tan;
  1767. }
  1768. result.m[1] = result.m[2] = result.m[3] = 0.0;
  1769. if (v_fixed) {
  1770. result.m[5] = tan;
  1771. }
  1772. else {
  1773. result.m[5] = tan * aspect;
  1774. }
  1775. result.m[4] = result.m[6] = result.m[7] = 0.0;
  1776. result.m[8] = result.m[9] = 0.0;
  1777. result.m[10] = -zfar / (znear - zfar);
  1778. result.m[11] = 1.0;
  1779. result.m[12] = result.m[13] = result.m[15] = 0.0;
  1780. result.m[14] = (znear * zfar) / (znear - zfar);
  1781. };
  1782. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  1783. var cw = viewport.width;
  1784. var ch = viewport.height;
  1785. var cx = viewport.x;
  1786. var cy = viewport.y;
  1787. 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);
  1788. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  1789. };
  1790. Matrix.Transpose = function (matrix) {
  1791. var result = new Matrix();
  1792. result.m[0] = matrix.m[0];
  1793. result.m[1] = matrix.m[4];
  1794. result.m[2] = matrix.m[8];
  1795. result.m[3] = matrix.m[12];
  1796. result.m[4] = matrix.m[1];
  1797. result.m[5] = matrix.m[5];
  1798. result.m[6] = matrix.m[9];
  1799. result.m[7] = matrix.m[13];
  1800. result.m[8] = matrix.m[2];
  1801. result.m[9] = matrix.m[6];
  1802. result.m[10] = matrix.m[10];
  1803. result.m[11] = matrix.m[14];
  1804. result.m[12] = matrix.m[3];
  1805. result.m[13] = matrix.m[7];
  1806. result.m[14] = matrix.m[11];
  1807. result.m[15] = matrix.m[15];
  1808. return result;
  1809. };
  1810. Matrix.Reflection = function (plane) {
  1811. var matrix = new Matrix();
  1812. Matrix.ReflectionToRef(plane, matrix);
  1813. return matrix;
  1814. };
  1815. Matrix.ReflectionToRef = function (plane, result) {
  1816. plane.normalize();
  1817. var x = plane.normal.x;
  1818. var y = plane.normal.y;
  1819. var z = plane.normal.z;
  1820. var temp = -2 * x;
  1821. var temp2 = -2 * y;
  1822. var temp3 = -2 * z;
  1823. result.m[0] = (temp * x) + 1;
  1824. result.m[1] = temp2 * x;
  1825. result.m[2] = temp3 * x;
  1826. result.m[3] = 0.0;
  1827. result.m[4] = temp * y;
  1828. result.m[5] = (temp2 * y) + 1;
  1829. result.m[6] = temp3 * y;
  1830. result.m[7] = 0.0;
  1831. result.m[8] = temp * z;
  1832. result.m[9] = temp2 * z;
  1833. result.m[10] = (temp3 * z) + 1;
  1834. result.m[11] = 0.0;
  1835. result.m[12] = temp * plane.d;
  1836. result.m[13] = temp2 * plane.d;
  1837. result.m[14] = temp3 * plane.d;
  1838. result.m[15] = 1.0;
  1839. };
  1840. Matrix._tempQuaternion = new Quaternion();
  1841. Matrix._xAxis = Vector3.Zero();
  1842. Matrix._yAxis = Vector3.Zero();
  1843. Matrix._zAxis = Vector3.Zero();
  1844. return Matrix;
  1845. })();
  1846. BABYLON.Matrix = Matrix;
  1847. var Plane = (function () {
  1848. function Plane(a, b, c, d) {
  1849. this.normal = new Vector3(a, b, c);
  1850. this.d = d;
  1851. }
  1852. Plane.prototype.asArray = function () {
  1853. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  1854. };
  1855. // Methods
  1856. Plane.prototype.clone = function () {
  1857. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  1858. };
  1859. Plane.prototype.normalize = function () {
  1860. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  1861. var magnitude = 0;
  1862. if (norm !== 0) {
  1863. magnitude = 1.0 / norm;
  1864. }
  1865. this.normal.x *= magnitude;
  1866. this.normal.y *= magnitude;
  1867. this.normal.z *= magnitude;
  1868. this.d *= magnitude;
  1869. return this;
  1870. };
  1871. Plane.prototype.transform = function (transformation) {
  1872. var transposedMatrix = Matrix.Transpose(transformation);
  1873. var x = this.normal.x;
  1874. var y = this.normal.y;
  1875. var z = this.normal.z;
  1876. var d = this.d;
  1877. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  1878. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  1879. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  1880. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  1881. return new Plane(normalX, normalY, normalZ, finalD);
  1882. };
  1883. Plane.prototype.dotCoordinate = function (point) {
  1884. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  1885. };
  1886. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  1887. var x1 = point2.x - point1.x;
  1888. var y1 = point2.y - point1.y;
  1889. var z1 = point2.z - point1.z;
  1890. var x2 = point3.x - point1.x;
  1891. var y2 = point3.y - point1.y;
  1892. var z2 = point3.z - point1.z;
  1893. var yz = (y1 * z2) - (z1 * y2);
  1894. var xz = (z1 * x2) - (x1 * z2);
  1895. var xy = (x1 * y2) - (y1 * x2);
  1896. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  1897. var invPyth;
  1898. if (pyth !== 0) {
  1899. invPyth = 1.0 / pyth;
  1900. }
  1901. else {
  1902. invPyth = 0;
  1903. }
  1904. this.normal.x = yz * invPyth;
  1905. this.normal.y = xz * invPyth;
  1906. this.normal.z = xy * invPyth;
  1907. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  1908. return this;
  1909. };
  1910. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  1911. var dot = Vector3.Dot(this.normal, direction);
  1912. return (dot <= epsilon);
  1913. };
  1914. Plane.prototype.signedDistanceTo = function (point) {
  1915. return Vector3.Dot(point, this.normal) + this.d;
  1916. };
  1917. // Statics
  1918. Plane.FromArray = function (array) {
  1919. return new Plane(array[0], array[1], array[2], array[3]);
  1920. };
  1921. Plane.FromPoints = function (point1, point2, point3) {
  1922. var result = new Plane(0, 0, 0, 0);
  1923. result.copyFromPoints(point1, point2, point3);
  1924. return result;
  1925. };
  1926. Plane.FromPositionAndNormal = function (origin, normal) {
  1927. var result = new Plane(0, 0, 0, 0);
  1928. normal.normalize();
  1929. result.normal = normal;
  1930. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  1931. return result;
  1932. };
  1933. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  1934. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  1935. return Vector3.Dot(point, normal) + d;
  1936. };
  1937. return Plane;
  1938. })();
  1939. BABYLON.Plane = Plane;
  1940. var Viewport = (function () {
  1941. function Viewport(x, y, width, height) {
  1942. this.x = x;
  1943. this.y = y;
  1944. this.width = width;
  1945. this.height = height;
  1946. }
  1947. Viewport.prototype.toGlobal = function (engine) {
  1948. var width = engine.getRenderWidth();
  1949. var height = engine.getRenderHeight();
  1950. return new Viewport(this.x * width, this.y * height, this.width * width, this.height * height);
  1951. };
  1952. return Viewport;
  1953. })();
  1954. BABYLON.Viewport = Viewport;
  1955. var Frustum = (function () {
  1956. function Frustum() {
  1957. }
  1958. Frustum.GetPlanes = function (transform) {
  1959. var frustumPlanes = [];
  1960. for (var index = 0; index < 6; index++) {
  1961. frustumPlanes.push(new Plane(0, 0, 0, 0));
  1962. }
  1963. Frustum.GetPlanesToRef(transform, frustumPlanes);
  1964. return frustumPlanes;
  1965. };
  1966. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  1967. // Near
  1968. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  1969. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  1970. frustumPlanes[0].normal.z = transform.m[10] + transform.m[10];
  1971. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  1972. frustumPlanes[0].normalize();
  1973. // Far
  1974. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  1975. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  1976. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  1977. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  1978. frustumPlanes[1].normalize();
  1979. // Left
  1980. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  1981. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  1982. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  1983. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  1984. frustumPlanes[2].normalize();
  1985. // Right
  1986. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  1987. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  1988. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  1989. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  1990. frustumPlanes[3].normalize();
  1991. // Top
  1992. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  1993. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  1994. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  1995. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  1996. frustumPlanes[4].normalize();
  1997. // Bottom
  1998. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  1999. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  2000. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  2001. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  2002. frustumPlanes[5].normalize();
  2003. };
  2004. return Frustum;
  2005. })();
  2006. BABYLON.Frustum = Frustum;
  2007. var Ray = (function () {
  2008. function Ray(origin, direction, length) {
  2009. if (length === void 0) { length = Number.MAX_VALUE; }
  2010. this.origin = origin;
  2011. this.direction = direction;
  2012. this.length = length;
  2013. }
  2014. // Methods
  2015. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  2016. var d = 0.0;
  2017. var maxValue = Number.MAX_VALUE;
  2018. if (Math.abs(this.direction.x) < 0.0000001) {
  2019. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  2020. return false;
  2021. }
  2022. }
  2023. else {
  2024. var inv = 1.0 / this.direction.x;
  2025. var min = (minimum.x - this.origin.x) * inv;
  2026. var max = (maximum.x - this.origin.x) * inv;
  2027. if (max === -Infinity) {
  2028. max = Infinity;
  2029. }
  2030. if (min > max) {
  2031. var temp = min;
  2032. min = max;
  2033. max = temp;
  2034. }
  2035. d = Math.max(min, d);
  2036. maxValue = Math.min(max, maxValue);
  2037. if (d > maxValue) {
  2038. return false;
  2039. }
  2040. }
  2041. if (Math.abs(this.direction.y) < 0.0000001) {
  2042. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  2043. return false;
  2044. }
  2045. }
  2046. else {
  2047. inv = 1.0 / this.direction.y;
  2048. min = (minimum.y - this.origin.y) * inv;
  2049. max = (maximum.y - this.origin.y) * inv;
  2050. if (max === -Infinity) {
  2051. max = Infinity;
  2052. }
  2053. if (min > max) {
  2054. temp = min;
  2055. min = max;
  2056. max = temp;
  2057. }
  2058. d = Math.max(min, d);
  2059. maxValue = Math.min(max, maxValue);
  2060. if (d > maxValue) {
  2061. return false;
  2062. }
  2063. }
  2064. if (Math.abs(this.direction.z) < 0.0000001) {
  2065. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  2066. return false;
  2067. }
  2068. }
  2069. else {
  2070. inv = 1.0 / this.direction.z;
  2071. min = (minimum.z - this.origin.z) * inv;
  2072. max = (maximum.z - this.origin.z) * inv;
  2073. if (max === -Infinity) {
  2074. max = Infinity;
  2075. }
  2076. if (min > max) {
  2077. temp = min;
  2078. min = max;
  2079. max = temp;
  2080. }
  2081. d = Math.max(min, d);
  2082. maxValue = Math.min(max, maxValue);
  2083. if (d > maxValue) {
  2084. return false;
  2085. }
  2086. }
  2087. return true;
  2088. };
  2089. Ray.prototype.intersectsBox = function (box) {
  2090. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  2091. };
  2092. Ray.prototype.intersectsSphere = function (sphere) {
  2093. var x = sphere.center.x - this.origin.x;
  2094. var y = sphere.center.y - this.origin.y;
  2095. var z = sphere.center.z - this.origin.z;
  2096. var pyth = (x * x) + (y * y) + (z * z);
  2097. var rr = sphere.radius * sphere.radius;
  2098. if (pyth <= rr) {
  2099. return true;
  2100. }
  2101. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  2102. if (dot < 0.0) {
  2103. return false;
  2104. }
  2105. var temp = pyth - (dot * dot);
  2106. return temp <= rr;
  2107. };
  2108. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  2109. if (!this._edge1) {
  2110. this._edge1 = Vector3.Zero();
  2111. this._edge2 = Vector3.Zero();
  2112. this._pvec = Vector3.Zero();
  2113. this._tvec = Vector3.Zero();
  2114. this._qvec = Vector3.Zero();
  2115. }
  2116. vertex1.subtractToRef(vertex0, this._edge1);
  2117. vertex2.subtractToRef(vertex0, this._edge2);
  2118. Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  2119. var det = Vector3.Dot(this._edge1, this._pvec);
  2120. if (det === 0) {
  2121. return null;
  2122. }
  2123. var invdet = 1 / det;
  2124. this.origin.subtractToRef(vertex0, this._tvec);
  2125. var bu = Vector3.Dot(this._tvec, this._pvec) * invdet;
  2126. if (bu < 0 || bu > 1.0) {
  2127. return null;
  2128. }
  2129. Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  2130. var bv = Vector3.Dot(this.direction, this._qvec) * invdet;
  2131. if (bv < 0 || bu + bv > 1.0) {
  2132. return null;
  2133. }
  2134. //check if the distance is longer than the predefined length.
  2135. var distance = Vector3.Dot(this._edge2, this._qvec) * invdet;
  2136. if (distance > this.length) {
  2137. return null;
  2138. }
  2139. return new BABYLON.IntersectionInfo(bu, bv, distance);
  2140. };
  2141. // Statics
  2142. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  2143. var start = Vector3.Unproject(new Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  2144. var end = Vector3.Unproject(new Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  2145. var direction = end.subtract(start);
  2146. direction.normalize();
  2147. return new Ray(start, direction);
  2148. };
  2149. /**
  2150. * 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
  2151. * transformed to the given world matrix.
  2152. * @param origin The origin point
  2153. * @param end The end point
  2154. * @param world a matrix to transform the ray to. Default is the identity matrix.
  2155. */
  2156. Ray.CreateNewFromTo = function (origin, end, world) {
  2157. if (world === void 0) { world = Matrix.Identity(); }
  2158. var direction = end.subtract(origin);
  2159. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  2160. direction.normalize();
  2161. return Ray.Transform(new Ray(origin, direction, length), world);
  2162. };
  2163. Ray.Transform = function (ray, matrix) {
  2164. var newOrigin = Vector3.TransformCoordinates(ray.origin, matrix);
  2165. var newDirection = Vector3.TransformNormal(ray.direction, matrix);
  2166. return new Ray(newOrigin, newDirection, ray.length);
  2167. };
  2168. return Ray;
  2169. })();
  2170. BABYLON.Ray = Ray;
  2171. (function (Space) {
  2172. Space[Space["LOCAL"] = 0] = "LOCAL";
  2173. Space[Space["WORLD"] = 1] = "WORLD";
  2174. })(BABYLON.Space || (BABYLON.Space = {}));
  2175. var Space = BABYLON.Space;
  2176. var Axis = (function () {
  2177. function Axis() {
  2178. }
  2179. Axis.X = new Vector3(1, 0, 0);
  2180. Axis.Y = new Vector3(0, 1, 0);
  2181. Axis.Z = new Vector3(0, 0, 1);
  2182. return Axis;
  2183. })();
  2184. BABYLON.Axis = Axis;
  2185. ;
  2186. var BezierCurve = (function () {
  2187. function BezierCurve() {
  2188. }
  2189. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  2190. // Extract X (which is equal to time here)
  2191. var f0 = 1 - 3 * x2 + 3 * x1;
  2192. var f1 = 3 * x2 - 6 * x1;
  2193. var f2 = 3 * x1;
  2194. var refinedT = t;
  2195. for (var i = 0; i < 5; i++) {
  2196. var refinedT2 = refinedT * refinedT;
  2197. var refinedT3 = refinedT2 * refinedT;
  2198. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  2199. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  2200. refinedT -= (x - t) * slope;
  2201. refinedT = Math.min(1, Math.max(0, refinedT));
  2202. }
  2203. // Resolve cubic bezier for the given x
  2204. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 + 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 + Math.pow(refinedT, 3);
  2205. };
  2206. return BezierCurve;
  2207. })();
  2208. BABYLON.BezierCurve = BezierCurve;
  2209. (function (Orientation) {
  2210. Orientation[Orientation["CW"] = 0] = "CW";
  2211. Orientation[Orientation["CCW"] = 1] = "CCW";
  2212. })(BABYLON.Orientation || (BABYLON.Orientation = {}));
  2213. var Orientation = BABYLON.Orientation;
  2214. var Angle = (function () {
  2215. function Angle(radians) {
  2216. var _this = this;
  2217. this.degrees = function () { return _this._radians * 180 / Math.PI; };
  2218. this.radians = function () { return _this._radians; };
  2219. this._radians = radians;
  2220. if (this._radians < 0)
  2221. this._radians += (2 * Math.PI);
  2222. }
  2223. Angle.BetweenTwoPoints = function (a, b) {
  2224. var delta = b.subtract(a);
  2225. var theta = Math.atan2(delta.y, delta.x);
  2226. return new Angle(theta);
  2227. };
  2228. Angle.FromRadians = function (radians) {
  2229. return new Angle(radians);
  2230. };
  2231. Angle.FromDegrees = function (degrees) {
  2232. return new Angle(degrees * Math.PI / 180);
  2233. };
  2234. return Angle;
  2235. })();
  2236. BABYLON.Angle = Angle;
  2237. var Arc2 = (function () {
  2238. function Arc2(startPoint, midPoint, endPoint) {
  2239. this.startPoint = startPoint;
  2240. this.midPoint = midPoint;
  2241. this.endPoint = endPoint;
  2242. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  2243. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  2244. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  2245. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  2246. 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);
  2247. this.radius = this.centerPoint.subtract(this.startPoint).length();
  2248. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  2249. var a1 = this.startAngle.degrees();
  2250. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  2251. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  2252. // angles correction
  2253. if (a2 - a1 > +180.0)
  2254. a2 -= 360.0;
  2255. if (a2 - a1 < -180.0)
  2256. a2 += 360.0;
  2257. if (a3 - a2 > +180.0)
  2258. a3 -= 360.0;
  2259. if (a3 - a2 < -180.0)
  2260. a3 += 360.0;
  2261. this.orientation = (a2 - a1) < 0 ? 0 /* CW */ : 1 /* CCW */;
  2262. this.angle = Angle.FromDegrees(this.orientation === 0 /* CW */ ? a1 - a3 : a3 - a1);
  2263. }
  2264. return Arc2;
  2265. })();
  2266. BABYLON.Arc2 = Arc2;
  2267. var PathCursor = (function () {
  2268. function PathCursor(path) {
  2269. this.path = path;
  2270. this._onchange = new Array();
  2271. this.value = 0;
  2272. this.animations = new Array();
  2273. }
  2274. PathCursor.prototype.getPoint = function () {
  2275. var point = this.path.getPointAtLengthPosition(this.value);
  2276. return new Vector3(point.x, 0, point.y);
  2277. };
  2278. PathCursor.prototype.moveAhead = function (step) {
  2279. if (step === void 0) { step = 0.002; }
  2280. this.move(step);
  2281. return this;
  2282. };
  2283. PathCursor.prototype.moveBack = function (step) {
  2284. if (step === void 0) { step = 0.002; }
  2285. this.move(-step);
  2286. return this;
  2287. };
  2288. PathCursor.prototype.move = function (step) {
  2289. if (Math.abs(step) > 1) {
  2290. throw "step size should be less than 1.";
  2291. }
  2292. this.value += step;
  2293. this.ensureLimits();
  2294. this.raiseOnChange();
  2295. return this;
  2296. };
  2297. PathCursor.prototype.ensureLimits = function () {
  2298. while (this.value > 1) {
  2299. this.value -= 1;
  2300. }
  2301. while (this.value < 0) {
  2302. this.value += 1;
  2303. }
  2304. return this;
  2305. };
  2306. // used by animation engine
  2307. PathCursor.prototype.markAsDirty = function (propertyName) {
  2308. this.ensureLimits();
  2309. this.raiseOnChange();
  2310. return this;
  2311. };
  2312. PathCursor.prototype.raiseOnChange = function () {
  2313. var _this = this;
  2314. this._onchange.forEach(function (f) { return f(_this); });
  2315. return this;
  2316. };
  2317. PathCursor.prototype.onchange = function (f) {
  2318. this._onchange.push(f);
  2319. return this;
  2320. };
  2321. return PathCursor;
  2322. })();
  2323. BABYLON.PathCursor = PathCursor;
  2324. var Path2 = (function () {
  2325. function Path2(x, y) {
  2326. this._points = [];
  2327. this._length = 0;
  2328. this.closed = false;
  2329. this._points.push(new Vector2(x, y));
  2330. }
  2331. Path2.prototype.addLineTo = function (x, y) {
  2332. if (closed) {
  2333. BABYLON.Tools.Error("cannot add lines to closed paths");
  2334. return this;
  2335. }
  2336. var newPoint = new Vector2(x, y);
  2337. var previousPoint = this._points[this._points.length - 1];
  2338. this._points.push(newPoint);
  2339. this._length += newPoint.subtract(previousPoint).length();
  2340. return this;
  2341. };
  2342. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  2343. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  2344. if (closed) {
  2345. BABYLON.Tools.Error("cannot add arcs to closed paths");
  2346. return this;
  2347. }
  2348. var startPoint = this._points[this._points.length - 1];
  2349. var midPoint = new Vector2(midX, midY);
  2350. var endPoint = new Vector2(endX, endY);
  2351. var arc = new Arc2(startPoint, midPoint, endPoint);
  2352. var increment = arc.angle.radians() / numberOfSegments;
  2353. if (arc.orientation === 0 /* CW */)
  2354. increment *= -1;
  2355. var currentAngle = arc.startAngle.radians() + increment;
  2356. for (var i = 0; i < numberOfSegments; i++) {
  2357. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  2358. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  2359. this.addLineTo(x, y);
  2360. currentAngle += increment;
  2361. }
  2362. return this;
  2363. };
  2364. Path2.prototype.close = function () {
  2365. this.closed = true;
  2366. return this;
  2367. };
  2368. Path2.prototype.length = function () {
  2369. var result = this._length;
  2370. if (!this.closed) {
  2371. var lastPoint = this._points[this._points.length - 1];
  2372. var firstPoint = this._points[0];
  2373. result += (firstPoint.subtract(lastPoint).length());
  2374. }
  2375. return result;
  2376. };
  2377. Path2.prototype.getPoints = function () {
  2378. return this._points;
  2379. };
  2380. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  2381. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  2382. BABYLON.Tools.Error("normalized length position should be between 0 and 1.");
  2383. return Vector2.Zero();
  2384. }
  2385. var lengthPosition = normalizedLengthPosition * this.length();
  2386. var previousOffset = 0;
  2387. for (var i = 0; i < this._points.length; i++) {
  2388. var j = (i + 1) % this._points.length;
  2389. var a = this._points[i];
  2390. var b = this._points[j];
  2391. var bToA = b.subtract(a);
  2392. var nextOffset = (bToA.length() + previousOffset);
  2393. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  2394. var dir = bToA.normalize();
  2395. var localOffset = lengthPosition - previousOffset;
  2396. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  2397. }
  2398. previousOffset = nextOffset;
  2399. }
  2400. BABYLON.Tools.Error("internal error");
  2401. return Vector2.Zero();
  2402. };
  2403. Path2.StartingAt = function (x, y) {
  2404. return new Path2(x, y);
  2405. };
  2406. return Path2;
  2407. })();
  2408. BABYLON.Path2 = Path2;
  2409. var Path3D = (function () {
  2410. function Path3D(path) {
  2411. this.path = path;
  2412. this._curve = [];
  2413. this._distances = [];
  2414. this._tangents = [];
  2415. this._normals = [];
  2416. this._binormals = [];
  2417. this._curve = path.slice(); // copy array
  2418. var l = this._curve.length;
  2419. // first and last tangents
  2420. this._tangents[0] = this._curve[1].subtract(this._curve[0]);
  2421. this._tangents[0].normalize();
  2422. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  2423. this._tangents[l - 1].normalize();
  2424. // normals and binormals at first point : arbitrary vector with _normalVector()
  2425. var tg0 = this._tangents[0];
  2426. var pp0 = this._normalVector(this._curve[0], tg0);
  2427. this._normals[0] = pp0;
  2428. this._normals[0].normalize();
  2429. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  2430. this._normals[0].normalize();
  2431. this._distances[0] = 0;
  2432. // normals and binormals : next points
  2433. var prev; // previous vector (segment)
  2434. var cur; // current vector (segment)
  2435. var curTang; // current tangent
  2436. var prevNorm; // previous normal
  2437. var prevBinor; // previous binormal
  2438. for (var i = 1; i < l; i++) {
  2439. // tangents
  2440. prev = this._curve[i].subtract(this._curve[i - 1]);
  2441. if (i < l - 1) {
  2442. cur = this._curve[i + 1].subtract(this._curve[i]);
  2443. this._tangents[i] = prev.add(cur);
  2444. this._tangents[i].normalize();
  2445. }
  2446. this._distances[i] = this._distances[i - 1] + prev.length();
  2447. // normals and binormals
  2448. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  2449. curTang = this._tangents[i];
  2450. prevNorm = this._normals[i - 1];
  2451. prevBinor = this._binormals[i - 1];
  2452. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  2453. this._normals[i].normalize();
  2454. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  2455. this._binormals[i].normalize();
  2456. }
  2457. }
  2458. Path3D.prototype.getCurve = function () {
  2459. return this._curve;
  2460. };
  2461. Path3D.prototype.getTangents = function () {
  2462. return this._tangents;
  2463. };
  2464. Path3D.prototype.getNormals = function () {
  2465. return this._normals;
  2466. };
  2467. Path3D.prototype.getBinormals = function () {
  2468. return this._binormals;
  2469. };
  2470. Path3D.prototype.getDistances = function () {
  2471. return this._distances;
  2472. };
  2473. // private function normalVector(v0, vt) :
  2474. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  2475. Path3D.prototype._normalVector = function (v0, vt) {
  2476. var point;
  2477. if (vt.x !== 1) {
  2478. point = new Vector3(1, 0, 0);
  2479. }
  2480. else if (vt.y !== 1) {
  2481. point = new Vector3(0, 1, 0);
  2482. }
  2483. else if (vt.z !== 1) {
  2484. point = new Vector3(0, 0, 1);
  2485. }
  2486. var normal0 = Vector3.Cross(vt, point);
  2487. normal0.normalize();
  2488. return normal0;
  2489. };
  2490. return Path3D;
  2491. })();
  2492. BABYLON.Path3D = Path3D;
  2493. })(BABYLON || (BABYLON = {}));
  2494. //# sourceMappingURL=babylon.math.js.mapvar BABYLON;
  2495. (function (BABYLON) {
  2496. // Screenshots
  2497. var screenshotCanvas;
  2498. var cloneValue = function (source, destinationObject) {
  2499. if (!source)
  2500. return null;
  2501. if (source instanceof BABYLON.Mesh) {
  2502. return null;
  2503. }
  2504. if (source instanceof BABYLON.SubMesh) {
  2505. return source.clone(destinationObject);
  2506. }
  2507. else if (source.clone) {
  2508. return source.clone();
  2509. }
  2510. return null;
  2511. };
  2512. var Tools = (function () {
  2513. function Tools() {
  2514. }
  2515. Tools.GetFilename = function (path) {
  2516. var index = path.lastIndexOf("/");
  2517. if (index < 0)
  2518. return path;
  2519. return path.substring(index + 1);
  2520. };
  2521. Tools.GetDOMTextContent = function (element) {
  2522. var result = "";
  2523. var child = element.firstChild;
  2524. while (child) {
  2525. if (child.nodeType === 3) {
  2526. result += child.textContent;
  2527. }
  2528. child = child.nextSibling;
  2529. }
  2530. return result;
  2531. };
  2532. Tools.ToDegrees = function (angle) {
  2533. return angle * 180 / Math.PI;
  2534. };
  2535. Tools.ToRadians = function (angle) {
  2536. return angle * Math.PI / 180;
  2537. };
  2538. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount) {
  2539. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  2540. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  2541. for (var index = indexStart; index < indexStart + indexCount; index++) {
  2542. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  2543. minimum = BABYLON.Vector3.Minimize(current, minimum);
  2544. maximum = BABYLON.Vector3.Maximize(current, maximum);
  2545. }
  2546. return {
  2547. minimum: minimum,
  2548. maximum: maximum
  2549. };
  2550. };
  2551. Tools.ExtractMinAndMax = function (positions, start, count) {
  2552. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  2553. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  2554. for (var index = start; index < start + count; index++) {
  2555. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  2556. minimum = BABYLON.Vector3.Minimize(current, minimum);
  2557. maximum = BABYLON.Vector3.Maximize(current, maximum);
  2558. }
  2559. return {
  2560. minimum: minimum,
  2561. maximum: maximum
  2562. };
  2563. };
  2564. Tools.MakeArray = function (obj, allowsNullUndefined) {
  2565. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  2566. return undefined;
  2567. return Array.isArray(obj) ? obj : [obj];
  2568. };
  2569. // Misc.
  2570. Tools.GetPointerPrefix = function () {
  2571. var eventPrefix = "pointer";
  2572. // Check if hand.js is referenced or if the browser natively supports pointer events
  2573. if (!navigator.pointerEnabled) {
  2574. eventPrefix = "mouse";
  2575. }
  2576. return eventPrefix;
  2577. };
  2578. Tools.QueueNewFrame = function (func) {
  2579. if (window.requestAnimationFrame)
  2580. window.requestAnimationFrame(func);
  2581. else if (window.msRequestAnimationFrame)
  2582. window.msRequestAnimationFrame(func);
  2583. else if (window.webkitRequestAnimationFrame)
  2584. window.webkitRequestAnimationFrame(func);
  2585. else if (window.mozRequestAnimationFrame)
  2586. window.mozRequestAnimationFrame(func);
  2587. else if (window.oRequestAnimationFrame)
  2588. window.oRequestAnimationFrame(func);
  2589. else {
  2590. window.setTimeout(func, 16);
  2591. }
  2592. };
  2593. Tools.RequestFullscreen = function (element) {
  2594. if (element.requestFullscreen)
  2595. element.requestFullscreen();
  2596. else if (element.msRequestFullscreen)
  2597. element.msRequestFullscreen();
  2598. else if (element.webkitRequestFullscreen)
  2599. element.webkitRequestFullscreen();
  2600. else if (element.mozRequestFullScreen)
  2601. element.mozRequestFullScreen();
  2602. };
  2603. Tools.ExitFullscreen = function () {
  2604. if (document.exitFullscreen) {
  2605. document.exitFullscreen();
  2606. }
  2607. else if (document.mozCancelFullScreen) {
  2608. document.mozCancelFullScreen();
  2609. }
  2610. else if (document.webkitCancelFullScreen) {
  2611. document.webkitCancelFullScreen();
  2612. }
  2613. else if (document.msCancelFullScreen) {
  2614. document.msCancelFullScreen();
  2615. }
  2616. };
  2617. // External files
  2618. Tools.CleanUrl = function (url) {
  2619. url = url.replace(/#/mg, "%23");
  2620. return url;
  2621. };
  2622. Tools.LoadImage = function (url, onload, onerror, database) {
  2623. url = Tools.CleanUrl(url);
  2624. var img = new Image();
  2625. if (url.substr(0, 5) !== "data:")
  2626. img.crossOrigin = 'anonymous';
  2627. img.onload = function () {
  2628. onload(img);
  2629. };
  2630. img.onerror = function (err) {
  2631. onerror(img, err);
  2632. };
  2633. var noIndexedDB = function () {
  2634. img.src = url;
  2635. };
  2636. var loadFromIndexedDB = function () {
  2637. database.loadImageFromDB(url, img);
  2638. };
  2639. //ANY database to do!
  2640. if (database && database.enableTexturesOffline && BABYLON.Database.isUASupportingBlobStorage) {
  2641. database.openAsync(loadFromIndexedDB, noIndexedDB);
  2642. }
  2643. else {
  2644. if (url.indexOf("file:") === -1) {
  2645. noIndexedDB();
  2646. }
  2647. else {
  2648. try {
  2649. var textureName = url.substring(5);
  2650. var blobURL;
  2651. try {
  2652. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  2653. }
  2654. catch (ex) {
  2655. // Chrome doesn't support oneTimeOnly parameter
  2656. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  2657. }
  2658. img.src = blobURL;
  2659. }
  2660. catch (e) {
  2661. Tools.Log("Error while trying to load texture: " + textureName);
  2662. img.src = null;
  2663. }
  2664. }
  2665. }
  2666. return img;
  2667. };
  2668. //ANY
  2669. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  2670. url = Tools.CleanUrl(url);
  2671. var noIndexedDB = function () {
  2672. var request = new XMLHttpRequest();
  2673. var loadUrl = Tools.BaseUrl + url;
  2674. request.open('GET', loadUrl, true);
  2675. if (useArrayBuffer) {
  2676. request.responseType = "arraybuffer";
  2677. }
  2678. request.onprogress = progressCallBack;
  2679. request.onreadystatechange = function () {
  2680. if (request.readyState === 4) {
  2681. if (request.status === 200 || Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  2682. callback(!useArrayBuffer ? request.responseText : request.response);
  2683. }
  2684. else {
  2685. if (onError) {
  2686. onError();
  2687. }
  2688. else {
  2689. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  2690. }
  2691. }
  2692. }
  2693. };
  2694. request.send(null);
  2695. };
  2696. var loadFromIndexedDB = function () {
  2697. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  2698. };
  2699. if (url.indexOf("file:") !== -1) {
  2700. var fileName = url.substring(5);
  2701. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, true);
  2702. }
  2703. else {
  2704. // Caching all files
  2705. if (database && database.enableSceneOffline) {
  2706. database.openAsync(loadFromIndexedDB, noIndexedDB);
  2707. }
  2708. else {
  2709. noIndexedDB();
  2710. }
  2711. }
  2712. };
  2713. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  2714. var reader = new FileReader();
  2715. reader.onload = function (e) {
  2716. //target doesn't have result from ts 1.3
  2717. callback(e.target['result']);
  2718. };
  2719. reader.onprogress = progressCallback;
  2720. reader.readAsDataURL(fileToLoad);
  2721. };
  2722. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  2723. var reader = new FileReader();
  2724. reader.onload = function (e) {
  2725. //target doesn't have result from ts 1.3
  2726. callback(e.target['result']);
  2727. };
  2728. reader.onprogress = progressCallBack;
  2729. if (!useArrayBuffer) {
  2730. // Asynchronous read
  2731. reader.readAsText(fileToLoad);
  2732. }
  2733. else {
  2734. reader.readAsArrayBuffer(fileToLoad);
  2735. }
  2736. };
  2737. // Misc.
  2738. Tools.Clamp = function (value, min, max) {
  2739. if (min === void 0) { min = 0; }
  2740. if (max === void 0) { max = 1; }
  2741. return Math.min(max, Math.max(min, value));
  2742. };
  2743. // Returns -1 when value is a negative number and
  2744. // +1 when value is a positive number.
  2745. Tools.Sign = function (value) {
  2746. value = +value; // convert to a number
  2747. if (value === 0 || isNaN(value))
  2748. return value;
  2749. return value > 0 ? 1 : -1;
  2750. };
  2751. Tools.Format = function (value, decimals) {
  2752. if (decimals === void 0) { decimals = 2; }
  2753. return value.toFixed(decimals);
  2754. };
  2755. Tools.CheckExtends = function (v, min, max) {
  2756. if (v.x < min.x)
  2757. min.x = v.x;
  2758. if (v.y < min.y)
  2759. min.y = v.y;
  2760. if (v.z < min.z)
  2761. min.z = v.z;
  2762. if (v.x > max.x)
  2763. max.x = v.x;
  2764. if (v.y > max.y)
  2765. max.y = v.y;
  2766. if (v.z > max.z)
  2767. max.z = v.z;
  2768. };
  2769. Tools.WithinEpsilon = function (a, b, epsilon) {
  2770. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  2771. var num = a - b;
  2772. return -epsilon <= num && num <= epsilon;
  2773. };
  2774. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  2775. for (var prop in source) {
  2776. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  2777. continue;
  2778. }
  2779. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  2780. continue;
  2781. }
  2782. var sourceValue = source[prop];
  2783. var typeOfSourceValue = typeof sourceValue;
  2784. if (typeOfSourceValue === "function") {
  2785. continue;
  2786. }
  2787. if (typeOfSourceValue === "object") {
  2788. if (sourceValue instanceof Array) {
  2789. destination[prop] = [];
  2790. if (sourceValue.length > 0) {
  2791. if (typeof sourceValue[0] == "object") {
  2792. for (var index = 0; index < sourceValue.length; index++) {
  2793. var clonedValue = cloneValue(sourceValue[index], destination);
  2794. if (destination[prop].indexOf(clonedValue) === -1) {
  2795. destination[prop].push(clonedValue);
  2796. }
  2797. }
  2798. }
  2799. else {
  2800. destination[prop] = sourceValue.slice(0);
  2801. }
  2802. }
  2803. }
  2804. else {
  2805. destination[prop] = cloneValue(sourceValue, destination);
  2806. }
  2807. }
  2808. else {
  2809. destination[prop] = sourceValue;
  2810. }
  2811. }
  2812. };
  2813. Tools.IsEmpty = function (obj) {
  2814. for (var i in obj) {
  2815. return false;
  2816. }
  2817. return true;
  2818. };
  2819. Tools.RegisterTopRootEvents = function (events) {
  2820. for (var index = 0; index < events.length; index++) {
  2821. var event = events[index];
  2822. window.addEventListener(event.name, event.handler, false);
  2823. try {
  2824. if (window.parent) {
  2825. window.parent.addEventListener(event.name, event.handler, false);
  2826. }
  2827. }
  2828. catch (e) {
  2829. }
  2830. }
  2831. };
  2832. Tools.UnregisterTopRootEvents = function (events) {
  2833. for (var index = 0; index < events.length; index++) {
  2834. var event = events[index];
  2835. window.removeEventListener(event.name, event.handler);
  2836. try {
  2837. if (window.parent) {
  2838. window.parent.removeEventListener(event.name, event.handler);
  2839. }
  2840. }
  2841. catch (e) {
  2842. }
  2843. }
  2844. };
  2845. Tools.CreateScreenshot = function (engine, camera, size) {
  2846. var width;
  2847. var height;
  2848. var scene = camera.getScene();
  2849. var previousCamera = null;
  2850. if (scene.activeCamera !== camera) {
  2851. previousCamera = scene.activeCamera;
  2852. scene.activeCamera = camera;
  2853. }
  2854. //If a precision value is specified
  2855. if (size.precision) {
  2856. width = Math.round(engine.getRenderWidth() * size.precision);
  2857. height = Math.round(width / engine.getAspectRatio(camera));
  2858. size = { width: width, height: height };
  2859. }
  2860. else if (size.width && size.height) {
  2861. width = size.width;
  2862. height = size.height;
  2863. }
  2864. else if (size.width && !size.height) {
  2865. width = size.width;
  2866. height = Math.round(width / engine.getAspectRatio(camera));
  2867. size = { width: width, height: height };
  2868. }
  2869. else if (size.height && !size.width) {
  2870. height = size.height;
  2871. width = Math.round(height * engine.getAspectRatio(camera));
  2872. size = { width: width, height: height };
  2873. }
  2874. else if (!isNaN(size)) {
  2875. height = size;
  2876. width = size;
  2877. }
  2878. else {
  2879. Tools.Error("Invalid 'size' parameter !");
  2880. return;
  2881. }
  2882. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  2883. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false);
  2884. texture.renderList = scene.meshes;
  2885. texture.onAfterRender = function () {
  2886. // Read the contents of the framebuffer
  2887. var numberOfChannelsByLine = width * 4;
  2888. var halfHeight = height / 2;
  2889. //Reading datas from WebGL
  2890. var data = engine.readPixels(0, 0, width, height);
  2891. for (var i = 0; i < halfHeight; i++) {
  2892. for (var j = 0; j < numberOfChannelsByLine; j++) {
  2893. var currentCell = j + i * numberOfChannelsByLine;
  2894. var targetLine = height - i - 1;
  2895. var targetCell = j + targetLine * numberOfChannelsByLine;
  2896. var temp = data[currentCell];
  2897. data[currentCell] = data[targetCell];
  2898. data[targetCell] = temp;
  2899. }
  2900. }
  2901. // Create a 2D canvas to store the result
  2902. if (!screenshotCanvas) {
  2903. screenshotCanvas = document.createElement('canvas');
  2904. }
  2905. screenshotCanvas.width = width;
  2906. screenshotCanvas.height = height;
  2907. var context = screenshotCanvas.getContext('2d');
  2908. // Copy the pixels to a 2D canvas
  2909. var imageData = context.createImageData(width, height);
  2910. //cast is due to ts error in lib.d.ts, see here - https://github.com/Microsoft/TypeScript/issues/949
  2911. var data = imageData.data;
  2912. data.set(data);
  2913. context.putImageData(imageData, 0, 0);
  2914. var base64Image = screenshotCanvas.toDataURL();
  2915. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  2916. if (("download" in document.createElement("a"))) {
  2917. var a = window.document.createElement("a");
  2918. a.href = base64Image;
  2919. var date = new Date();
  2920. var stringDate = date.getFullYear() + "/" + date.getMonth() + "/" + date.getDate() + "-" + date.getHours() + ":" + date.getMinutes();
  2921. a.setAttribute("download", "screenshot-" + stringDate + ".png");
  2922. window.document.body.appendChild(a);
  2923. a.addEventListener("click", function () {
  2924. a.parentElement.removeChild(a);
  2925. });
  2926. a.click();
  2927. }
  2928. else {
  2929. var newWindow = window.open("");
  2930. var img = newWindow.document.createElement("img");
  2931. img.src = base64Image;
  2932. newWindow.document.body.appendChild(img);
  2933. }
  2934. };
  2935. scene.incrementRenderId();
  2936. texture.render(true);
  2937. texture.dispose();
  2938. if (previousCamera) {
  2939. scene.activeCamera = previousCamera;
  2940. }
  2941. };
  2942. // XHR response validator for local file scenario
  2943. Tools.ValidateXHRData = function (xhr, dataType) {
  2944. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  2945. if (dataType === void 0) { dataType = 7; }
  2946. try {
  2947. if (dataType & 1) {
  2948. if (xhr.responseText && xhr.responseText.length > 0) {
  2949. return true;
  2950. }
  2951. else if (dataType === 1) {
  2952. return false;
  2953. }
  2954. }
  2955. if (dataType & 2) {
  2956. // Check header width and height since there is no "TGA" magic number
  2957. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  2958. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  2959. return true;
  2960. }
  2961. else if (dataType === 2) {
  2962. return false;
  2963. }
  2964. }
  2965. if (dataType & 4) {
  2966. // Check for the "DDS" magic number
  2967. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  2968. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  2969. return true;
  2970. }
  2971. else {
  2972. return false;
  2973. }
  2974. }
  2975. }
  2976. catch (e) {
  2977. }
  2978. return false;
  2979. };
  2980. Object.defineProperty(Tools, "NoneLogLevel", {
  2981. get: function () {
  2982. return Tools._NoneLogLevel;
  2983. },
  2984. enumerable: true,
  2985. configurable: true
  2986. });
  2987. Object.defineProperty(Tools, "MessageLogLevel", {
  2988. get: function () {
  2989. return Tools._MessageLogLevel;
  2990. },
  2991. enumerable: true,
  2992. configurable: true
  2993. });
  2994. Object.defineProperty(Tools, "WarningLogLevel", {
  2995. get: function () {
  2996. return Tools._WarningLogLevel;
  2997. },
  2998. enumerable: true,
  2999. configurable: true
  3000. });
  3001. Object.defineProperty(Tools, "ErrorLogLevel", {
  3002. get: function () {
  3003. return Tools._ErrorLogLevel;
  3004. },
  3005. enumerable: true,
  3006. configurable: true
  3007. });
  3008. Object.defineProperty(Tools, "AllLogLevel", {
  3009. get: function () {
  3010. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  3011. },
  3012. enumerable: true,
  3013. configurable: true
  3014. });
  3015. Tools._AddLogEntry = function (entry) {
  3016. Tools._LogCache = entry + Tools._LogCache;
  3017. if (Tools.OnNewCacheEntry) {
  3018. Tools.OnNewCacheEntry(entry);
  3019. }
  3020. };
  3021. Tools._FormatMessage = function (message) {
  3022. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  3023. var date = new Date();
  3024. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  3025. };
  3026. Tools._LogDisabled = function (message) {
  3027. // nothing to do
  3028. };
  3029. Tools._LogEnabled = function (message) {
  3030. var formattedMessage = Tools._FormatMessage(message);
  3031. console.log("BJS - " + formattedMessage);
  3032. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  3033. Tools._AddLogEntry(entry);
  3034. };
  3035. Tools._WarnDisabled = function (message) {
  3036. // nothing to do
  3037. };
  3038. Tools._WarnEnabled = function (message) {
  3039. var formattedMessage = Tools._FormatMessage(message);
  3040. console.warn("BJS - " + formattedMessage);
  3041. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  3042. Tools._AddLogEntry(entry);
  3043. };
  3044. Tools._ErrorDisabled = function (message) {
  3045. // nothing to do
  3046. };
  3047. Tools._ErrorEnabled = function (message) {
  3048. var formattedMessage = Tools._FormatMessage(message);
  3049. console.error("BJS - " + formattedMessage);
  3050. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  3051. Tools._AddLogEntry(entry);
  3052. };
  3053. Object.defineProperty(Tools, "LogCache", {
  3054. get: function () {
  3055. return Tools._LogCache;
  3056. },
  3057. enumerable: true,
  3058. configurable: true
  3059. });
  3060. Object.defineProperty(Tools, "LogLevels", {
  3061. set: function (level) {
  3062. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  3063. Tools.Log = Tools._LogEnabled;
  3064. }
  3065. else {
  3066. Tools.Log = Tools._LogDisabled;
  3067. }
  3068. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  3069. Tools.Warn = Tools._WarnEnabled;
  3070. }
  3071. else {
  3072. Tools.Warn = Tools._WarnDisabled;
  3073. }
  3074. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  3075. Tools.Error = Tools._ErrorEnabled;
  3076. }
  3077. else {
  3078. Tools.Error = Tools._ErrorDisabled;
  3079. }
  3080. },
  3081. enumerable: true,
  3082. configurable: true
  3083. });
  3084. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  3085. get: function () {
  3086. return Tools._PerformanceNoneLogLevel;
  3087. },
  3088. enumerable: true,
  3089. configurable: true
  3090. });
  3091. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  3092. get: function () {
  3093. return Tools._PerformanceUserMarkLogLevel;
  3094. },
  3095. enumerable: true,
  3096. configurable: true
  3097. });
  3098. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  3099. get: function () {
  3100. return Tools._PerformanceConsoleLogLevel;
  3101. },
  3102. enumerable: true,
  3103. configurable: true
  3104. });
  3105. Object.defineProperty(Tools, "PerformanceLogLevel", {
  3106. set: function (level) {
  3107. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  3108. Tools.StartPerformanceCounter = Tools._StartUserMark;
  3109. Tools.EndPerformanceCounter = Tools._EndUserMark;
  3110. return;
  3111. }
  3112. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  3113. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  3114. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  3115. return;
  3116. }
  3117. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  3118. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  3119. },
  3120. enumerable: true,
  3121. configurable: true
  3122. });
  3123. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  3124. };
  3125. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  3126. };
  3127. Tools._StartUserMark = function (counterName, condition) {
  3128. if (condition === void 0) { condition = true; }
  3129. if (!condition || !Tools._performance.mark) {
  3130. return;
  3131. }
  3132. Tools._performance.mark(counterName + "-Begin");
  3133. };
  3134. Tools._EndUserMark = function (counterName, condition) {
  3135. if (condition === void 0) { condition = true; }
  3136. if (!condition || !Tools._performance.mark) {
  3137. return;
  3138. }
  3139. Tools._performance.mark(counterName + "-End");
  3140. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  3141. };
  3142. Tools._StartPerformanceConsole = function (counterName, condition) {
  3143. if (condition === void 0) { condition = true; }
  3144. if (!condition) {
  3145. return;
  3146. }
  3147. Tools._StartUserMark(counterName, condition);
  3148. if (console.time) {
  3149. console.time(counterName);
  3150. }
  3151. };
  3152. Tools._EndPerformanceConsole = function (counterName, condition) {
  3153. if (condition === void 0) { condition = true; }
  3154. if (!condition) {
  3155. return;
  3156. }
  3157. Tools._EndUserMark(counterName, condition);
  3158. if (console.time) {
  3159. console.timeEnd(counterName);
  3160. }
  3161. };
  3162. Object.defineProperty(Tools, "Now", {
  3163. get: function () {
  3164. if (window.performance && window.performance.now) {
  3165. return window.performance.now();
  3166. }
  3167. return new Date().getTime();
  3168. },
  3169. enumerable: true,
  3170. configurable: true
  3171. });
  3172. // Deprecated
  3173. Tools.GetFps = function () {
  3174. Tools.Warn("Tools.GetFps() is deprecated. Please use engine.getFps() instead");
  3175. return 0;
  3176. };
  3177. Tools.BaseUrl = "";
  3178. Tools.GetExponantOfTwo = function (value, max) {
  3179. var count = 1;
  3180. do {
  3181. count *= 2;
  3182. } while (count < value);
  3183. if (count > max)
  3184. count = max;
  3185. return count;
  3186. };
  3187. // Logs
  3188. Tools._NoneLogLevel = 0;
  3189. Tools._MessageLogLevel = 1;
  3190. Tools._WarningLogLevel = 2;
  3191. Tools._ErrorLogLevel = 4;
  3192. Tools._LogCache = "";
  3193. Tools.Log = Tools._LogEnabled;
  3194. Tools.Warn = Tools._WarnEnabled;
  3195. Tools.Error = Tools._ErrorEnabled;
  3196. // Performances
  3197. Tools._PerformanceNoneLogLevel = 0;
  3198. Tools._PerformanceUserMarkLogLevel = 1;
  3199. Tools._PerformanceConsoleLogLevel = 2;
  3200. Tools._performance = window.performance;
  3201. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  3202. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  3203. return Tools;
  3204. })();
  3205. BABYLON.Tools = Tools;
  3206. /**
  3207. * An implementation of a loop for asynchronous functions.
  3208. */
  3209. var AsyncLoop = (function () {
  3210. /**
  3211. * Constroctor.
  3212. * @param iterations the number of iterations.
  3213. * @param _fn the function to run each iteration
  3214. * @param _successCallback the callback that will be called upon succesful execution
  3215. * @param offset starting offset.
  3216. */
  3217. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  3218. if (offset === void 0) { offset = 0; }
  3219. this.iterations = iterations;
  3220. this._fn = _fn;
  3221. this._successCallback = _successCallback;
  3222. this.index = offset - 1;
  3223. this._done = false;
  3224. }
  3225. /**
  3226. * Execute the next iteration. Must be called after the last iteration was finished.
  3227. */
  3228. AsyncLoop.prototype.executeNext = function () {
  3229. if (!this._done) {
  3230. if (this.index + 1 < this.iterations) {
  3231. ++this.index;
  3232. this._fn(this);
  3233. }
  3234. else {
  3235. this.breakLoop();
  3236. }
  3237. }
  3238. };
  3239. /**
  3240. * Break the loop and run the success callback.
  3241. */
  3242. AsyncLoop.prototype.breakLoop = function () {
  3243. this._done = true;
  3244. this._successCallback();
  3245. };
  3246. /**
  3247. * Helper function
  3248. */
  3249. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  3250. if (offset === void 0) { offset = 0; }
  3251. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  3252. loop.executeNext();
  3253. return loop;
  3254. };
  3255. /**
  3256. * A for-loop that will run a given number of iterations synchronous and the rest async.
  3257. * @param iterations total number of iterations
  3258. * @param syncedIterations number of synchronous iterations in each async iteration.
  3259. * @param fn the function to call each iteration.
  3260. * @param callback a success call back that will be called when iterating stops.
  3261. * @param breakFunction a break condition (optional)
  3262. * @param timeout timeout settings for the setTimeout function. default - 0.
  3263. * @constructor
  3264. */
  3265. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  3266. if (timeout === void 0) { timeout = 0; }
  3267. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  3268. if (breakFunction && breakFunction())
  3269. loop.breakLoop();
  3270. else {
  3271. setTimeout(function () {
  3272. for (var i = 0; i < syncedIterations; ++i) {
  3273. var iteration = (loop.index * syncedIterations) + i;
  3274. if (iteration >= iterations)
  3275. break;
  3276. fn(iteration);
  3277. if (breakFunction && breakFunction()) {
  3278. loop.breakLoop();
  3279. break;
  3280. }
  3281. }
  3282. loop.executeNext();
  3283. }, timeout);
  3284. }
  3285. }, callback);
  3286. };
  3287. return AsyncLoop;
  3288. })();
  3289. BABYLON.AsyncLoop = AsyncLoop;
  3290. })(BABYLON || (BABYLON = {}));
  3291. //# sourceMappingURL=babylon.tools.js.mapvar BABYLON;
  3292. (function (BABYLON) {
  3293. var _DepthCullingState = (function () {
  3294. function _DepthCullingState() {
  3295. this._isDepthTestDirty = false;
  3296. this._isDepthMaskDirty = false;
  3297. this._isDepthFuncDirty = false;
  3298. this._isCullFaceDirty = false;
  3299. this._isCullDirty = false;
  3300. }
  3301. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  3302. get: function () {
  3303. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty;
  3304. },
  3305. enumerable: true,
  3306. configurable: true
  3307. });
  3308. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  3309. get: function () {
  3310. return this._cullFace;
  3311. },
  3312. set: function (value) {
  3313. if (this._cullFace === value) {
  3314. return;
  3315. }
  3316. this._cullFace = value;
  3317. this._isCullFaceDirty = true;
  3318. },
  3319. enumerable: true,
  3320. configurable: true
  3321. });
  3322. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  3323. get: function () {
  3324. return this._cull;
  3325. },
  3326. set: function (value) {
  3327. if (this._cull === value) {
  3328. return;
  3329. }
  3330. this._cull = value;
  3331. this._isCullDirty = true;
  3332. },
  3333. enumerable: true,
  3334. configurable: true
  3335. });
  3336. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  3337. get: function () {
  3338. return this._depthFunc;
  3339. },
  3340. set: function (value) {
  3341. if (this._depthFunc === value) {
  3342. return;
  3343. }
  3344. this._depthFunc = value;
  3345. this._isDepthFuncDirty = true;
  3346. },
  3347. enumerable: true,
  3348. configurable: true
  3349. });
  3350. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  3351. get: function () {
  3352. return this._depthMask;
  3353. },
  3354. set: function (value) {
  3355. if (this._depthMask === value) {
  3356. return;
  3357. }
  3358. this._depthMask = value;
  3359. this._isDepthMaskDirty = true;
  3360. },
  3361. enumerable: true,
  3362. configurable: true
  3363. });
  3364. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  3365. get: function () {
  3366. return this._depthTest;
  3367. },
  3368. set: function (value) {
  3369. if (this._depthTest === value) {
  3370. return;
  3371. }
  3372. this._depthTest = value;
  3373. this._isDepthTestDirty = true;
  3374. },
  3375. enumerable: true,
  3376. configurable: true
  3377. });
  3378. _DepthCullingState.prototype.reset = function () {
  3379. this._depthMask = true;
  3380. this._depthTest = true;
  3381. this._depthFunc = null;
  3382. this._cull = null;
  3383. this._cullFace = null;
  3384. this._isDepthTestDirty = true;
  3385. this._isDepthMaskDirty = true;
  3386. this._isDepthFuncDirty = false;
  3387. this._isCullFaceDirty = false;
  3388. this._isCullDirty = false;
  3389. };
  3390. _DepthCullingState.prototype.apply = function (gl) {
  3391. if (!this.isDirty) {
  3392. return;
  3393. }
  3394. // Cull
  3395. if (this._isCullDirty) {
  3396. if (this.cull) {
  3397. gl.enable(gl.CULL_FACE);
  3398. }
  3399. else {
  3400. gl.disable(gl.CULL_FACE);
  3401. }
  3402. this._isCullDirty = false;
  3403. }
  3404. // Cull face
  3405. if (this._isCullFaceDirty) {
  3406. gl.cullFace(this.cullFace);
  3407. this._isCullFaceDirty = false;
  3408. }
  3409. // Depth mask
  3410. if (this._isDepthMaskDirty) {
  3411. gl.depthMask(this.depthMask);
  3412. this._isDepthMaskDirty = false;
  3413. }
  3414. // Depth test
  3415. if (this._isDepthTestDirty) {
  3416. if (this.depthTest) {
  3417. gl.enable(gl.DEPTH_TEST);
  3418. }
  3419. else {
  3420. gl.disable(gl.DEPTH_TEST);
  3421. }
  3422. this._isDepthTestDirty = false;
  3423. }
  3424. // Depth func
  3425. if (this._isDepthFuncDirty) {
  3426. gl.depthFunc(this.depthFunc);
  3427. this._isDepthFuncDirty = false;
  3428. }
  3429. };
  3430. return _DepthCullingState;
  3431. })();
  3432. BABYLON._DepthCullingState = _DepthCullingState;
  3433. var _AlphaState = (function () {
  3434. function _AlphaState() {
  3435. this._isAlphaBlendDirty = false;
  3436. this._isBlendFunctionParametersDirty = false;
  3437. this._alphaBlend = false;
  3438. this._blendFunctionParameters = new Array(4);
  3439. }
  3440. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  3441. get: function () {
  3442. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  3443. },
  3444. enumerable: true,
  3445. configurable: true
  3446. });
  3447. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  3448. get: function () {
  3449. return this._alphaBlend;
  3450. },
  3451. set: function (value) {
  3452. if (this._alphaBlend === value) {
  3453. return;
  3454. }
  3455. this._alphaBlend = value;
  3456. this._isAlphaBlendDirty = true;
  3457. },
  3458. enumerable: true,
  3459. configurable: true
  3460. });
  3461. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  3462. if (this._blendFunctionParameters[0] === value0 && this._blendFunctionParameters[1] === value1 && this._blendFunctionParameters[2] === value2 && this._blendFunctionParameters[3] === value3) {
  3463. return;
  3464. }
  3465. this._blendFunctionParameters[0] = value0;
  3466. this._blendFunctionParameters[1] = value1;
  3467. this._blendFunctionParameters[2] = value2;
  3468. this._blendFunctionParameters[3] = value3;
  3469. this._isBlendFunctionParametersDirty = true;
  3470. };
  3471. _AlphaState.prototype.reset = function () {
  3472. this._alphaBlend = false;
  3473. this._blendFunctionParameters[0] = null;
  3474. this._blendFunctionParameters[1] = null;
  3475. this._blendFunctionParameters[2] = null;
  3476. this._blendFunctionParameters[3] = null;
  3477. this._isAlphaBlendDirty = true;
  3478. this._isBlendFunctionParametersDirty = false;
  3479. };
  3480. _AlphaState.prototype.apply = function (gl) {
  3481. if (!this.isDirty) {
  3482. return;
  3483. }
  3484. // Alpha blend
  3485. if (this._isAlphaBlendDirty) {
  3486. if (this._alphaBlend) {
  3487. gl.enable(gl.BLEND);
  3488. }
  3489. else {
  3490. gl.disable(gl.BLEND);
  3491. }
  3492. this._isAlphaBlendDirty = false;
  3493. }
  3494. // Alpha function
  3495. if (this._isBlendFunctionParametersDirty) {
  3496. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  3497. this._isBlendFunctionParametersDirty = false;
  3498. }
  3499. };
  3500. return _AlphaState;
  3501. })();
  3502. BABYLON._AlphaState = _AlphaState;
  3503. var compileShader = function (gl, source, type, defines) {
  3504. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  3505. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  3506. gl.compileShader(shader);
  3507. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  3508. throw new Error(gl.getShaderInfoLog(shader));
  3509. }
  3510. return shader;
  3511. };
  3512. var getWebGLTextureType = function (gl, type) {
  3513. var textureType = gl.UNSIGNED_BYTE;
  3514. if (type === Engine.TEXTURETYPE_FLOAT)
  3515. textureType = gl.FLOAT;
  3516. return textureType;
  3517. };
  3518. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  3519. var magFilter = gl.NEAREST;
  3520. var minFilter = gl.NEAREST;
  3521. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  3522. magFilter = gl.LINEAR;
  3523. if (generateMipMaps) {
  3524. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  3525. }
  3526. else {
  3527. minFilter = gl.LINEAR;
  3528. }
  3529. }
  3530. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  3531. magFilter = gl.LINEAR;
  3532. if (generateMipMaps) {
  3533. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  3534. }
  3535. else {
  3536. minFilter = gl.LINEAR;
  3537. }
  3538. }
  3539. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  3540. magFilter = gl.NEAREST;
  3541. if (generateMipMaps) {
  3542. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  3543. }
  3544. else {
  3545. minFilter = gl.NEAREST;
  3546. }
  3547. }
  3548. return {
  3549. min: minFilter,
  3550. mag: magFilter
  3551. };
  3552. };
  3553. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  3554. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  3555. var engine = scene.getEngine();
  3556. var potWidth = BABYLON.Tools.GetExponantOfTwo(width, engine.getCaps().maxTextureSize);
  3557. var potHeight = BABYLON.Tools.GetExponantOfTwo(height, engine.getCaps().maxTextureSize);
  3558. gl.bindTexture(gl.TEXTURE_2D, texture);
  3559. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  3560. processFunction(potWidth, potHeight);
  3561. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  3562. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  3563. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  3564. if (!noMipmap && !isCompressed) {
  3565. gl.generateMipmap(gl.TEXTURE_2D);
  3566. }
  3567. gl.bindTexture(gl.TEXTURE_2D, null);
  3568. engine._activeTexturesCache = [];
  3569. texture._baseWidth = width;
  3570. texture._baseHeight = height;
  3571. texture._width = potWidth;
  3572. texture._height = potHeight;
  3573. texture.isReady = true;
  3574. texture.samplingMode = samplingMode;
  3575. scene._removePendingData(texture);
  3576. };
  3577. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  3578. var onload = function () {
  3579. loadedImages[index] = img;
  3580. loadedImages._internalCount++;
  3581. scene._removePendingData(img);
  3582. if (loadedImages._internalCount === 6) {
  3583. onfinish(loadedImages);
  3584. }
  3585. };
  3586. var onerror = function () {
  3587. scene._removePendingData(img);
  3588. };
  3589. var img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  3590. scene._addPendingData(img);
  3591. };
  3592. var cascadeLoad = function (rootUrl, scene, onfinish, extensions) {
  3593. var loadedImages = [];
  3594. loadedImages._internalCount = 0;
  3595. for (var index = 0; index < 6; index++) {
  3596. partialLoad(rootUrl + extensions[index], index, loadedImages, scene, onfinish);
  3597. }
  3598. };
  3599. var EngineCapabilities = (function () {
  3600. function EngineCapabilities() {
  3601. }
  3602. return EngineCapabilities;
  3603. })();
  3604. BABYLON.EngineCapabilities = EngineCapabilities;
  3605. /**
  3606. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  3607. */
  3608. var Engine = (function () {
  3609. /**
  3610. * @constructor
  3611. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  3612. * @param {boolean} [antialias] - enable antialias
  3613. * @param options - further options to be sent to the getContext function
  3614. */
  3615. function Engine(canvas, antialias, options) {
  3616. var _this = this;
  3617. // Public members
  3618. this.isFullscreen = false;
  3619. this.isPointerLock = false;
  3620. this.cullBackFaces = true;
  3621. this.renderEvenInBackground = true;
  3622. this.scenes = new Array();
  3623. this._windowIsBackground = false;
  3624. this._loadingDivBackgroundColor = "black";
  3625. this._drawCalls = 0;
  3626. this._renderingQueueLaunched = false;
  3627. this._activeRenderLoops = [];
  3628. // FPS
  3629. this.fpsRange = 60;
  3630. this.previousFramesDuration = [];
  3631. this.fps = 60;
  3632. this.deltaTime = 0;
  3633. // States
  3634. this._depthCullingState = new _DepthCullingState();
  3635. this._alphaState = new _AlphaState();
  3636. this._alphaMode = Engine.ALPHA_DISABLE;
  3637. // Cache
  3638. this._loadedTexturesCache = new Array();
  3639. this._activeTexturesCache = new Array();
  3640. this._compiledEffects = {};
  3641. this._uintIndicesCurrentlySet = false;
  3642. this._renderingCanvas = canvas;
  3643. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  3644. options = options || {};
  3645. options.antialias = antialias;
  3646. try {
  3647. this._gl = canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options);
  3648. }
  3649. catch (e) {
  3650. throw new Error("WebGL not supported");
  3651. }
  3652. if (!this._gl) {
  3653. throw new Error("WebGL not supported");
  3654. }
  3655. this._onBlur = function () {
  3656. _this._windowIsBackground = true;
  3657. };
  3658. this._onFocus = function () {
  3659. _this._windowIsBackground = false;
  3660. };
  3661. window.addEventListener("blur", this._onBlur);
  3662. window.addEventListener("focus", this._onFocus);
  3663. // Textures
  3664. this._workingCanvas = document.createElement("canvas");
  3665. this._workingContext = this._workingCanvas.getContext("2d");
  3666. // Viewport
  3667. this._hardwareScalingLevel = 1.0 / (window.devicePixelRatio || 1.0);
  3668. this.resize();
  3669. // Caps
  3670. this._caps = new EngineCapabilities();
  3671. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  3672. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  3673. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  3674. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  3675. // Infos
  3676. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  3677. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  3678. if (rendererInfo != null) {
  3679. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  3680. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  3681. }
  3682. if (!this._glVendor) {
  3683. this._glVendor = "Unknown vendor";
  3684. }
  3685. if (!this._glRenderer) {
  3686. this._glRenderer = "Unknown renderer";
  3687. }
  3688. // Extensions
  3689. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  3690. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  3691. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  3692. 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');
  3693. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  3694. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  3695. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  3696. // Depth buffer
  3697. this.setDepthBuffer(true);
  3698. this.setDepthFunctionToLessOrEqual();
  3699. this.setDepthWrite(true);
  3700. // Fullscreen
  3701. this._onFullscreenChange = function () {
  3702. if (document.fullscreen !== undefined) {
  3703. _this.isFullscreen = document.fullscreen;
  3704. }
  3705. else if (document.mozFullScreen !== undefined) {
  3706. _this.isFullscreen = document.mozFullScreen;
  3707. }
  3708. else if (document.webkitIsFullScreen !== undefined) {
  3709. _this.isFullscreen = document.webkitIsFullScreen;
  3710. }
  3711. else if (document.msIsFullScreen !== undefined) {
  3712. _this.isFullscreen = document.msIsFullScreen;
  3713. }
  3714. // Pointer lock
  3715. if (_this.isFullscreen && _this._pointerLockRequested) {
  3716. canvas.requestPointerLock = canvas.requestPointerLock || canvas.msRequestPointerLock || canvas.mozRequestPointerLock || canvas.webkitRequestPointerLock;
  3717. if (canvas.requestPointerLock) {
  3718. canvas.requestPointerLock();
  3719. }
  3720. }
  3721. };
  3722. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  3723. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  3724. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  3725. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  3726. // Pointer lock
  3727. this._onPointerLockChange = function () {
  3728. _this.isPointerLock = (document.mozPointerLockElement === canvas || document.webkitPointerLockElement === canvas || document.msPointerLockElement === canvas || document.pointerLockElement === canvas);
  3729. };
  3730. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  3731. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  3732. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  3733. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  3734. if (!Engine.audioEngine) {
  3735. Engine.audioEngine = new BABYLON.AudioEngine();
  3736. }
  3737. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  3738. }
  3739. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  3740. get: function () {
  3741. return Engine._ALPHA_DISABLE;
  3742. },
  3743. enumerable: true,
  3744. configurable: true
  3745. });
  3746. Object.defineProperty(Engine, "ALPHA_ADD", {
  3747. get: function () {
  3748. return Engine._ALPHA_ADD;
  3749. },
  3750. enumerable: true,
  3751. configurable: true
  3752. });
  3753. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  3754. get: function () {
  3755. return Engine._ALPHA_COMBINE;
  3756. },
  3757. enumerable: true,
  3758. configurable: true
  3759. });
  3760. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  3761. get: function () {
  3762. return Engine._DELAYLOADSTATE_NONE;
  3763. },
  3764. enumerable: true,
  3765. configurable: true
  3766. });
  3767. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  3768. get: function () {
  3769. return Engine._DELAYLOADSTATE_LOADED;
  3770. },
  3771. enumerable: true,
  3772. configurable: true
  3773. });
  3774. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  3775. get: function () {
  3776. return Engine._DELAYLOADSTATE_LOADING;
  3777. },
  3778. enumerable: true,
  3779. configurable: true
  3780. });
  3781. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  3782. get: function () {
  3783. return Engine._DELAYLOADSTATE_NOTLOADED;
  3784. },
  3785. enumerable: true,
  3786. configurable: true
  3787. });
  3788. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  3789. get: function () {
  3790. return Engine._TEXTUREFORMAT_ALPHA;
  3791. },
  3792. enumerable: true,
  3793. configurable: true
  3794. });
  3795. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  3796. get: function () {
  3797. return Engine._TEXTUREFORMAT_LUMINANCE;
  3798. },
  3799. enumerable: true,
  3800. configurable: true
  3801. });
  3802. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  3803. get: function () {
  3804. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  3805. },
  3806. enumerable: true,
  3807. configurable: true
  3808. });
  3809. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  3810. get: function () {
  3811. return Engine._TEXTUREFORMAT_RGB;
  3812. },
  3813. enumerable: true,
  3814. configurable: true
  3815. });
  3816. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  3817. get: function () {
  3818. return Engine._TEXTUREFORMAT_RGBA;
  3819. },
  3820. enumerable: true,
  3821. configurable: true
  3822. });
  3823. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  3824. get: function () {
  3825. return Engine._TEXTURETYPE_UNSIGNED_INT;
  3826. },
  3827. enumerable: true,
  3828. configurable: true
  3829. });
  3830. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  3831. get: function () {
  3832. return Engine._TEXTURETYPE_FLOAT;
  3833. },
  3834. enumerable: true,
  3835. configurable: true
  3836. });
  3837. Object.defineProperty(Engine, "Version", {
  3838. get: function () {
  3839. return "2.0.0";
  3840. },
  3841. enumerable: true,
  3842. configurable: true
  3843. });
  3844. Engine.prototype.getGlInfo = function () {
  3845. return {
  3846. vendor: this._glVendor,
  3847. renderer: this._glRenderer,
  3848. version: this._glVersion
  3849. };
  3850. };
  3851. Engine.prototype.getAspectRatio = function (camera) {
  3852. var viewport = camera.viewport;
  3853. return (this.getRenderWidth() * viewport.width) / (this.getRenderHeight() * viewport.height);
  3854. };
  3855. Engine.prototype.getRenderWidth = function () {
  3856. if (this._currentRenderTarget) {
  3857. return this._currentRenderTarget._width;
  3858. }
  3859. return this._renderingCanvas.width;
  3860. };
  3861. Engine.prototype.getRenderHeight = function () {
  3862. if (this._currentRenderTarget) {
  3863. return this._currentRenderTarget._height;
  3864. }
  3865. return this._renderingCanvas.height;
  3866. };
  3867. Engine.prototype.getRenderingCanvas = function () {
  3868. return this._renderingCanvas;
  3869. };
  3870. Engine.prototype.getRenderingCanvasClientRect = function () {
  3871. return this._renderingCanvas.getBoundingClientRect();
  3872. };
  3873. Engine.prototype.setHardwareScalingLevel = function (level) {
  3874. this._hardwareScalingLevel = level;
  3875. this.resize();
  3876. };
  3877. Engine.prototype.getHardwareScalingLevel = function () {
  3878. return this._hardwareScalingLevel;
  3879. };
  3880. Engine.prototype.getLoadedTexturesCache = function () {
  3881. return this._loadedTexturesCache;
  3882. };
  3883. Engine.prototype.getCaps = function () {
  3884. return this._caps;
  3885. };
  3886. Object.defineProperty(Engine.prototype, "drawCalls", {
  3887. get: function () {
  3888. return this._drawCalls;
  3889. },
  3890. enumerable: true,
  3891. configurable: true
  3892. });
  3893. // Methods
  3894. Engine.prototype.resetDrawCalls = function () {
  3895. this._drawCalls = 0;
  3896. };
  3897. Engine.prototype.setDepthFunctionToGreater = function () {
  3898. this._depthCullingState.depthFunc = this._gl.GREATER;
  3899. };
  3900. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  3901. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  3902. };
  3903. Engine.prototype.setDepthFunctionToLess = function () {
  3904. this._depthCullingState.depthFunc = this._gl.LESS;
  3905. };
  3906. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  3907. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  3908. };
  3909. /**
  3910. * stop executing a render loop function and remove it from the execution array
  3911. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  3912. */
  3913. Engine.prototype.stopRenderLoop = function (renderFunction) {
  3914. if (!renderFunction) {
  3915. this._activeRenderLoops = [];
  3916. return;
  3917. }
  3918. var index = this._activeRenderLoops.indexOf(renderFunction);
  3919. if (index >= 0) {
  3920. this._activeRenderLoops.splice(index, 1);
  3921. }
  3922. };
  3923. Engine.prototype._renderLoop = function () {
  3924. var _this = this;
  3925. var shouldRender = true;
  3926. if (!this.renderEvenInBackground && this._windowIsBackground) {
  3927. shouldRender = false;
  3928. }
  3929. if (shouldRender) {
  3930. // Start new frame
  3931. this.beginFrame();
  3932. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  3933. var renderFunction = this._activeRenderLoops[index];
  3934. renderFunction();
  3935. }
  3936. // Present
  3937. this.endFrame();
  3938. }
  3939. if (this._activeRenderLoops.length > 0) {
  3940. // Register new frame
  3941. BABYLON.Tools.QueueNewFrame(function () {
  3942. _this._renderLoop();
  3943. });
  3944. }
  3945. else {
  3946. this._renderingQueueLaunched = false;
  3947. }
  3948. };
  3949. /**
  3950. * Register and execute a render loop. The engine can have more than one render function.
  3951. * @param {Function} renderFunction - the function to continuesly execute starting the next render loop.
  3952. * @example
  3953. * engine.runRenderLoop(function () {
  3954. * scene.render()
  3955. * })
  3956. */
  3957. Engine.prototype.runRenderLoop = function (renderFunction) {
  3958. var _this = this;
  3959. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  3960. return;
  3961. }
  3962. this._activeRenderLoops.push(renderFunction);
  3963. if (!this._renderingQueueLaunched) {
  3964. this._renderingQueueLaunched = true;
  3965. BABYLON.Tools.QueueNewFrame(function () {
  3966. _this._renderLoop();
  3967. });
  3968. }
  3969. };
  3970. /**
  3971. * Toggle full screen mode.
  3972. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  3973. */
  3974. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  3975. if (this.isFullscreen) {
  3976. BABYLON.Tools.ExitFullscreen();
  3977. }
  3978. else {
  3979. this._pointerLockRequested = requestPointerLock;
  3980. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  3981. }
  3982. };
  3983. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  3984. this.applyStates();
  3985. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  3986. if (this._depthCullingState.depthMask) {
  3987. this._gl.clearDepth(1.0);
  3988. }
  3989. var mode = 0;
  3990. if (backBuffer)
  3991. mode |= this._gl.COLOR_BUFFER_BIT;
  3992. if (depthStencil && this._depthCullingState.depthMask)
  3993. mode |= this._gl.DEPTH_BUFFER_BIT;
  3994. this._gl.clear(mode);
  3995. };
  3996. /**
  3997. * Set the WebGL's viewport
  3998. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  3999. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  4000. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  4001. */
  4002. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  4003. var width = requiredWidth || this._renderingCanvas.width;
  4004. var height = requiredHeight || this._renderingCanvas.height;
  4005. var x = viewport.x || 0;
  4006. var y = viewport.y || 0;
  4007. this._cachedViewport = viewport;
  4008. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  4009. };
  4010. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  4011. this._cachedViewport = null;
  4012. this._gl.viewport(x, y, width, height);
  4013. };
  4014. Engine.prototype.beginFrame = function () {
  4015. this._measureFps();
  4016. };
  4017. Engine.prototype.endFrame = function () {
  4018. //this.flushFramebuffer();
  4019. };
  4020. /**
  4021. * resize the view according to the canvas' size.
  4022. * @example
  4023. * window.addEventListener("resize", function () {
  4024. * engine.resize();
  4025. * });
  4026. */
  4027. Engine.prototype.resize = function () {
  4028. this.setSize(this._renderingCanvas.clientWidth / this._hardwareScalingLevel, this._renderingCanvas.clientHeight / this._hardwareScalingLevel);
  4029. };
  4030. /**
  4031. * force a specific size of the canvas
  4032. * @param {number} width - the new canvas' width
  4033. * @param {number} height - the new canvas' height
  4034. */
  4035. Engine.prototype.setSize = function (width, height) {
  4036. this._renderingCanvas.width = width;
  4037. this._renderingCanvas.height = height;
  4038. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  4039. };
  4040. Engine.prototype.bindFramebuffer = function (texture) {
  4041. this._currentRenderTarget = texture;
  4042. var gl = this._gl;
  4043. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  4044. this._gl.viewport(0, 0, texture._width, texture._height);
  4045. this.wipeCaches();
  4046. };
  4047. Engine.prototype.unBindFramebuffer = function (texture) {
  4048. this._currentRenderTarget = null;
  4049. if (texture.generateMipMaps) {
  4050. var gl = this._gl;
  4051. gl.bindTexture(gl.TEXTURE_2D, texture);
  4052. gl.generateMipmap(gl.TEXTURE_2D);
  4053. gl.bindTexture(gl.TEXTURE_2D, null);
  4054. }
  4055. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  4056. };
  4057. Engine.prototype.flushFramebuffer = function () {
  4058. this._gl.flush();
  4059. };
  4060. Engine.prototype.restoreDefaultFramebuffer = function () {
  4061. this._currentRenderTarget = null;
  4062. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  4063. this.setViewport(this._cachedViewport);
  4064. this.wipeCaches();
  4065. };
  4066. // VBOs
  4067. Engine.prototype._resetVertexBufferBinding = function () {
  4068. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  4069. this._cachedVertexBuffers = null;
  4070. };
  4071. Engine.prototype.createVertexBuffer = function (vertices) {
  4072. var vbo = this._gl.createBuffer();
  4073. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  4074. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  4075. this._resetVertexBufferBinding();
  4076. vbo.references = 1;
  4077. return vbo;
  4078. };
  4079. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  4080. var vbo = this._gl.createBuffer();
  4081. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  4082. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  4083. this._resetVertexBufferBinding();
  4084. vbo.references = 1;
  4085. return vbo;
  4086. };
  4087. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset) {
  4088. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  4089. if (offset === undefined) {
  4090. offset = 0;
  4091. }
  4092. if (vertices instanceof Float32Array) {
  4093. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  4094. }
  4095. else {
  4096. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  4097. }
  4098. this._resetVertexBufferBinding();
  4099. };
  4100. Engine.prototype._resetIndexBufferBinding = function () {
  4101. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  4102. this._cachedIndexBuffer = null;
  4103. };
  4104. Engine.prototype.createIndexBuffer = function (indices) {
  4105. var vbo = this._gl.createBuffer();
  4106. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  4107. // Check for 32 bits indices
  4108. var arrayBuffer;
  4109. var need32Bits = false;
  4110. if (this._caps.uintIndices) {
  4111. for (var index = 0; index < indices.length; index++) {
  4112. if (indices[index] > 65535) {
  4113. need32Bits = true;
  4114. break;
  4115. }
  4116. }
  4117. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  4118. }
  4119. else {
  4120. arrayBuffer = new Uint16Array(indices);
  4121. }
  4122. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  4123. this._resetIndexBufferBinding();
  4124. vbo.references = 1;
  4125. vbo.is32Bits = need32Bits;
  4126. return vbo;
  4127. };
  4128. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  4129. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  4130. this._cachedVertexBuffers = vertexBuffer;
  4131. this._cachedEffectForVertexBuffers = effect;
  4132. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  4133. var offset = 0;
  4134. for (var index = 0; index < vertexDeclaration.length; index++) {
  4135. var order = effect.getAttributeLocation(index);
  4136. if (order >= 0) {
  4137. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  4138. }
  4139. offset += vertexDeclaration[index] * 4;
  4140. }
  4141. }
  4142. if (this._cachedIndexBuffer !== indexBuffer) {
  4143. this._cachedIndexBuffer = indexBuffer;
  4144. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  4145. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  4146. }
  4147. };
  4148. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  4149. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  4150. this._cachedVertexBuffers = vertexBuffers;
  4151. this._cachedEffectForVertexBuffers = effect;
  4152. var attributes = effect.getAttributesNames();
  4153. for (var index = 0; index < attributes.length; index++) {
  4154. var order = effect.getAttributeLocation(index);
  4155. if (order >= 0) {
  4156. var vertexBuffer = vertexBuffers[attributes[index]];
  4157. if (!vertexBuffer) {
  4158. continue;
  4159. }
  4160. var stride = vertexBuffer.getStrideSize();
  4161. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  4162. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  4163. }
  4164. }
  4165. }
  4166. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  4167. this._cachedIndexBuffer = indexBuffer;
  4168. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  4169. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  4170. }
  4171. };
  4172. Engine.prototype._releaseBuffer = function (buffer) {
  4173. buffer.references--;
  4174. if (buffer.references === 0) {
  4175. this._gl.deleteBuffer(buffer);
  4176. return true;
  4177. }
  4178. return false;
  4179. };
  4180. Engine.prototype.createInstancesBuffer = function (capacity) {
  4181. var buffer = this._gl.createBuffer();
  4182. buffer.capacity = capacity;
  4183. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  4184. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  4185. return buffer;
  4186. };
  4187. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  4188. this._gl.deleteBuffer(buffer);
  4189. };
  4190. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  4191. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  4192. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  4193. for (var index = 0; index < 4; index++) {
  4194. var offsetLocation = offsetLocations[index];
  4195. this._gl.enableVertexAttribArray(offsetLocation);
  4196. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  4197. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  4198. }
  4199. };
  4200. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  4201. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  4202. for (var index = 0; index < 4; index++) {
  4203. var offsetLocation = offsetLocations[index];
  4204. this._gl.disableVertexAttribArray(offsetLocation);
  4205. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  4206. }
  4207. };
  4208. Engine.prototype.applyStates = function () {
  4209. this._depthCullingState.apply(this._gl);
  4210. this._alphaState.apply(this._gl);
  4211. };
  4212. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  4213. // Apply states
  4214. this.applyStates();
  4215. this._drawCalls++;
  4216. // Render
  4217. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  4218. if (instancesCount) {
  4219. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * 2, instancesCount);
  4220. return;
  4221. }
  4222. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * 2);
  4223. };
  4224. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  4225. // Apply states
  4226. this.applyStates();
  4227. this._drawCalls++;
  4228. if (instancesCount) {
  4229. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  4230. return;
  4231. }
  4232. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  4233. };
  4234. // Shaders
  4235. Engine.prototype._releaseEffect = function (effect) {
  4236. if (this._compiledEffects[effect._key]) {
  4237. delete this._compiledEffects[effect._key];
  4238. if (effect.getProgram()) {
  4239. this._gl.deleteProgram(effect.getProgram());
  4240. }
  4241. }
  4242. };
  4243. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  4244. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  4245. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  4246. var name = vertex + "+" + fragment + "@" + defines;
  4247. if (this._compiledEffects[name]) {
  4248. return this._compiledEffects[name];
  4249. }
  4250. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  4251. effect._key = name;
  4252. this._compiledEffects[name] = effect;
  4253. return effect;
  4254. };
  4255. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  4256. if (uniformsNames === void 0) { uniformsNames = []; }
  4257. if (samplers === void 0) { samplers = []; }
  4258. if (defines === void 0) { defines = ""; }
  4259. return this.createEffect({
  4260. vertex: "particles",
  4261. fragmentElement: fragmentName
  4262. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  4263. };
  4264. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  4265. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  4266. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  4267. var shaderProgram = this._gl.createProgram();
  4268. this._gl.attachShader(shaderProgram, vertexShader);
  4269. this._gl.attachShader(shaderProgram, fragmentShader);
  4270. this._gl.linkProgram(shaderProgram);
  4271. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  4272. if (!linked) {
  4273. var error = this._gl.getProgramInfoLog(shaderProgram);
  4274. if (error) {
  4275. throw new Error(error);
  4276. }
  4277. }
  4278. this._gl.deleteShader(vertexShader);
  4279. this._gl.deleteShader(fragmentShader);
  4280. return shaderProgram;
  4281. };
  4282. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  4283. var results = [];
  4284. for (var index = 0; index < uniformsNames.length; index++) {
  4285. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  4286. }
  4287. return results;
  4288. };
  4289. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  4290. var results = [];
  4291. for (var index = 0; index < attributesNames.length; index++) {
  4292. try {
  4293. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  4294. }
  4295. catch (e) {
  4296. results.push(-1);
  4297. }
  4298. }
  4299. return results;
  4300. };
  4301. Engine.prototype.enableEffect = function (effect) {
  4302. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  4303. if (effect && effect.onBind) {
  4304. effect.onBind(effect);
  4305. }
  4306. return;
  4307. }
  4308. this._vertexAttribArrays = this._vertexAttribArrays || [];
  4309. // Use program
  4310. this._gl.useProgram(effect.getProgram());
  4311. for (var i in this._vertexAttribArrays) {
  4312. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  4313. continue;
  4314. }
  4315. this._vertexAttribArrays[i] = false;
  4316. this._gl.disableVertexAttribArray(i);
  4317. }
  4318. var attributesCount = effect.getAttributesCount();
  4319. for (var index = 0; index < attributesCount; index++) {
  4320. // Attributes
  4321. var order = effect.getAttributeLocation(index);
  4322. if (order >= 0) {
  4323. this._vertexAttribArrays[order] = true;
  4324. this._gl.enableVertexAttribArray(order);
  4325. }
  4326. }
  4327. this._currentEffect = effect;
  4328. if (effect.onBind) {
  4329. effect.onBind(effect);
  4330. }
  4331. };
  4332. Engine.prototype.setArray = function (uniform, array) {
  4333. if (!uniform)
  4334. return;
  4335. this._gl.uniform1fv(uniform, array);
  4336. };
  4337. Engine.prototype.setArray2 = function (uniform, array) {
  4338. if (!uniform || array.length % 2 !== 0)
  4339. return;
  4340. this._gl.uniform2fv(uniform, array);
  4341. };
  4342. Engine.prototype.setArray3 = function (uniform, array) {
  4343. if (!uniform || array.length % 3 !== 0)
  4344. return;
  4345. this._gl.uniform3fv(uniform, array);
  4346. };
  4347. Engine.prototype.setArray4 = function (uniform, array) {
  4348. if (!uniform || array.length % 4 !== 0)
  4349. return;
  4350. this._gl.uniform4fv(uniform, array);
  4351. };
  4352. Engine.prototype.setMatrices = function (uniform, matrices) {
  4353. if (!uniform)
  4354. return;
  4355. this._gl.uniformMatrix4fv(uniform, false, matrices);
  4356. };
  4357. Engine.prototype.setMatrix = function (uniform, matrix) {
  4358. if (!uniform)
  4359. return;
  4360. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  4361. };
  4362. Engine.prototype.setFloat = function (uniform, value) {
  4363. if (!uniform)
  4364. return;
  4365. this._gl.uniform1f(uniform, value);
  4366. };
  4367. Engine.prototype.setFloat2 = function (uniform, x, y) {
  4368. if (!uniform)
  4369. return;
  4370. this._gl.uniform2f(uniform, x, y);
  4371. };
  4372. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  4373. if (!uniform)
  4374. return;
  4375. this._gl.uniform3f(uniform, x, y, z);
  4376. };
  4377. Engine.prototype.setBool = function (uniform, bool) {
  4378. if (!uniform)
  4379. return;
  4380. this._gl.uniform1i(uniform, bool);
  4381. };
  4382. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  4383. if (!uniform)
  4384. return;
  4385. this._gl.uniform4f(uniform, x, y, z, w);
  4386. };
  4387. Engine.prototype.setColor3 = function (uniform, color3) {
  4388. if (!uniform)
  4389. return;
  4390. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  4391. };
  4392. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  4393. if (!uniform)
  4394. return;
  4395. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  4396. };
  4397. // States
  4398. Engine.prototype.setState = function (culling, force) {
  4399. // Culling
  4400. if (this._depthCullingState.cull !== culling || force) {
  4401. if (culling) {
  4402. this._depthCullingState.cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  4403. this._depthCullingState.cull = true;
  4404. }
  4405. else {
  4406. this._depthCullingState.cull = false;
  4407. }
  4408. }
  4409. };
  4410. Engine.prototype.setDepthBuffer = function (enable) {
  4411. this._depthCullingState.depthTest = enable;
  4412. };
  4413. Engine.prototype.getDepthWrite = function () {
  4414. return this._depthCullingState.depthMask;
  4415. };
  4416. Engine.prototype.setDepthWrite = function (enable) {
  4417. this._depthCullingState.depthMask = enable;
  4418. };
  4419. Engine.prototype.setColorWrite = function (enable) {
  4420. this._gl.colorMask(enable, enable, enable, enable);
  4421. };
  4422. Engine.prototype.setAlphaMode = function (mode) {
  4423. switch (mode) {
  4424. case Engine.ALPHA_DISABLE:
  4425. this.setDepthWrite(true);
  4426. this._alphaState.alphaBlend = false;
  4427. break;
  4428. case Engine.ALPHA_COMBINE:
  4429. this.setDepthWrite(false);
  4430. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  4431. this._alphaState.alphaBlend = true;
  4432. break;
  4433. case Engine.ALPHA_ADD:
  4434. this.setDepthWrite(false);
  4435. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  4436. this._alphaState.alphaBlend = true;
  4437. break;
  4438. }
  4439. this._alphaMode = mode;
  4440. };
  4441. Engine.prototype.getAlphaMode = function () {
  4442. return this._alphaMode;
  4443. };
  4444. Engine.prototype.setAlphaTesting = function (enable) {
  4445. this._alphaTest = enable;
  4446. };
  4447. Engine.prototype.getAlphaTesting = function () {
  4448. return this._alphaTest;
  4449. };
  4450. // Textures
  4451. Engine.prototype.wipeCaches = function () {
  4452. this._activeTexturesCache = [];
  4453. this._currentEffect = null;
  4454. this._depthCullingState.reset();
  4455. this._alphaState.reset();
  4456. this._cachedVertexBuffers = null;
  4457. this._cachedIndexBuffer = null;
  4458. this._cachedEffectForVertexBuffers = null;
  4459. };
  4460. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  4461. var gl = this._gl;
  4462. gl.bindTexture(gl.TEXTURE_2D, texture);
  4463. var magFilter = gl.NEAREST;
  4464. var minFilter = gl.NEAREST;
  4465. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  4466. magFilter = gl.LINEAR;
  4467. minFilter = gl.LINEAR;
  4468. }
  4469. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  4470. magFilter = gl.LINEAR;
  4471. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  4472. }
  4473. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  4474. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  4475. gl.bindTexture(gl.TEXTURE_2D, null);
  4476. texture.samplingMode = samplingMode;
  4477. };
  4478. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  4479. var _this = this;
  4480. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  4481. if (onLoad === void 0) { onLoad = null; }
  4482. if (onError === void 0) { onError = null; }
  4483. if (buffer === void 0) { buffer = null; }
  4484. var texture = this._gl.createTexture();
  4485. var extension;
  4486. var fromData = false;
  4487. if (url.substr(0, 5) === "data:") {
  4488. fromData = true;
  4489. }
  4490. if (!fromData)
  4491. extension = url.substr(url.length - 4, 4).toLowerCase();
  4492. else {
  4493. var oldUrl = url;
  4494. fromData = oldUrl.split(':');
  4495. url = oldUrl;
  4496. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  4497. }
  4498. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  4499. var isTGA = (extension === ".tga");
  4500. scene._addPendingData(texture);
  4501. texture.url = url;
  4502. texture.noMipmap = noMipmap;
  4503. texture.references = 1;
  4504. this._loadedTexturesCache.push(texture);
  4505. var onerror = function () {
  4506. scene._removePendingData(texture);
  4507. if (onError) {
  4508. onError();
  4509. }
  4510. };
  4511. if (isTGA) {
  4512. var callback = function (arrayBuffer) {
  4513. var data = new Uint8Array(arrayBuffer);
  4514. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  4515. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  4516. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  4517. if (onLoad) {
  4518. onLoad();
  4519. }
  4520. }, samplingMode);
  4521. };
  4522. if (!(fromData instanceof Array))
  4523. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  4524. callback(arrayBuffer);
  4525. }, onerror, scene.database, true);
  4526. else
  4527. callback(buffer);
  4528. }
  4529. else if (isDDS) {
  4530. callback = function (data) {
  4531. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  4532. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  4533. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  4534. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  4535. if (onLoad) {
  4536. onLoad();
  4537. }
  4538. }, samplingMode);
  4539. };
  4540. if (!(fromData instanceof Array))
  4541. BABYLON.Tools.LoadFile(url, function (data) {
  4542. callback(data);
  4543. }, onerror, scene.database, true);
  4544. else
  4545. callback(buffer);
  4546. }
  4547. else {
  4548. var onload = function (img) {
  4549. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  4550. var isPot = (img.width === potWidth && img.height === potHeight);
  4551. if (!isPot) {
  4552. _this._workingCanvas.width = potWidth;
  4553. _this._workingCanvas.height = potHeight;
  4554. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  4555. _this._workingContext.imageSmoothingEnabled = false;
  4556. _this._workingContext.mozImageSmoothingEnabled = false;
  4557. _this._workingContext.oImageSmoothingEnabled = false;
  4558. _this._workingContext.webkitImageSmoothingEnabled = false;
  4559. _this._workingContext.msImageSmoothingEnabled = false;
  4560. }
  4561. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  4562. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  4563. _this._workingContext.imageSmoothingEnabled = true;
  4564. _this._workingContext.mozImageSmoothingEnabled = true;
  4565. _this._workingContext.oImageSmoothingEnabled = true;
  4566. _this._workingContext.webkitImageSmoothingEnabled = true;
  4567. _this._workingContext.msImageSmoothingEnabled = true;
  4568. }
  4569. }
  4570. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  4571. if (onLoad) {
  4572. onLoad();
  4573. }
  4574. }, samplingMode);
  4575. };
  4576. if (!(fromData instanceof Array))
  4577. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  4578. else
  4579. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  4580. }
  4581. return texture;
  4582. };
  4583. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode) {
  4584. var texture = this._gl.createTexture();
  4585. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4586. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  4587. // Format
  4588. var internalFormat = this._gl.RGBA;
  4589. switch (format) {
  4590. case Engine.TEXTUREFORMAT_ALPHA:
  4591. internalFormat = this._gl.ALPHA;
  4592. break;
  4593. case Engine.TEXTUREFORMAT_LUMINANCE:
  4594. internalFormat = this._gl.LUMINANCE;
  4595. break;
  4596. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  4597. internalFormat = this._gl.LUMINANCE_ALPHA;
  4598. break;
  4599. case Engine.TEXTUREFORMAT_RGB:
  4600. internalFormat = this._gl.RGB;
  4601. break;
  4602. case Engine.TEXTUREFORMAT_RGBA:
  4603. internalFormat = this._gl.RGBA;
  4604. break;
  4605. }
  4606. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, width, height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  4607. if (generateMipMaps) {
  4608. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  4609. }
  4610. // Filters
  4611. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  4612. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  4613. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  4614. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4615. this._activeTexturesCache = [];
  4616. texture._baseWidth = width;
  4617. texture._baseHeight = height;
  4618. texture._width = width;
  4619. texture._height = height;
  4620. texture.isReady = true;
  4621. texture.references = 1;
  4622. texture.samplingMode = samplingMode;
  4623. this._loadedTexturesCache.push(texture);
  4624. return texture;
  4625. };
  4626. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  4627. var texture = this._gl.createTexture();
  4628. width = BABYLON.Tools.GetExponantOfTwo(width, this._caps.maxTextureSize);
  4629. height = BABYLON.Tools.GetExponantOfTwo(height, this._caps.maxTextureSize);
  4630. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4631. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  4632. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  4633. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  4634. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4635. this._activeTexturesCache = [];
  4636. texture._baseWidth = width;
  4637. texture._baseHeight = height;
  4638. texture._width = width;
  4639. texture._height = height;
  4640. texture.isReady = false;
  4641. texture.generateMipMaps = generateMipMaps;
  4642. texture.references = 1;
  4643. texture.samplingMode = samplingMode;
  4644. this._loadedTexturesCache.push(texture);
  4645. return texture;
  4646. };
  4647. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  4648. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4649. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  4650. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  4651. if (texture.generateMipMaps) {
  4652. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  4653. }
  4654. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4655. this._activeTexturesCache = [];
  4656. texture.isReady = true;
  4657. };
  4658. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  4659. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4660. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  4661. // Scale the video if it is a NPOT using the current working canvas
  4662. if (video.videoWidth !== texture._width || video.videoHeight !== texture._height) {
  4663. if (!texture._workingCanvas) {
  4664. texture._workingCanvas = document.createElement("canvas");
  4665. texture._workingContext = texture._workingCanvas.getContext("2d");
  4666. texture._workingCanvas.width = texture._width;
  4667. texture._workingCanvas.height = texture._height;
  4668. }
  4669. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  4670. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  4671. }
  4672. else {
  4673. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  4674. }
  4675. if (texture.generateMipMaps) {
  4676. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  4677. }
  4678. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4679. this._activeTexturesCache = [];
  4680. texture.isReady = true;
  4681. };
  4682. Engine.prototype.createRenderTargetTexture = function (size, options) {
  4683. // old version had a "generateMipMaps" arg instead of options.
  4684. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  4685. // in the same way, generateDepthBuffer is defaulted to true
  4686. var generateMipMaps = false;
  4687. var generateDepthBuffer = true;
  4688. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  4689. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  4690. if (options !== undefined) {
  4691. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipmaps;
  4692. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  4693. type = options.type === undefined ? type : options.type;
  4694. if (options.samplingMode !== undefined) {
  4695. samplingMode = options.samplingMode;
  4696. }
  4697. if (type === Engine.TEXTURETYPE_FLOAT) {
  4698. // if floating point (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  4699. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  4700. }
  4701. }
  4702. var gl = this._gl;
  4703. var texture = gl.createTexture();
  4704. gl.bindTexture(gl.TEXTURE_2D, texture);
  4705. var width = size.width || size;
  4706. var height = size.height || size;
  4707. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  4708. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  4709. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  4710. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  4711. }
  4712. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  4713. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  4714. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4715. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4716. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  4717. var depthBuffer;
  4718. // Create the depth buffer
  4719. if (generateDepthBuffer) {
  4720. depthBuffer = gl.createRenderbuffer();
  4721. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  4722. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  4723. }
  4724. // Create the framebuffer
  4725. var framebuffer = gl.createFramebuffer();
  4726. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  4727. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  4728. if (generateDepthBuffer) {
  4729. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  4730. }
  4731. // Unbind
  4732. gl.bindTexture(gl.TEXTURE_2D, null);
  4733. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  4734. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  4735. texture._framebuffer = framebuffer;
  4736. if (generateDepthBuffer) {
  4737. texture._depthBuffer = depthBuffer;
  4738. }
  4739. texture._width = width;
  4740. texture._height = height;
  4741. texture.isReady = true;
  4742. texture.generateMipMaps = generateMipMaps;
  4743. texture.references = 1;
  4744. texture.samplingMode = samplingMode;
  4745. this._activeTexturesCache = [];
  4746. this._loadedTexturesCache.push(texture);
  4747. return texture;
  4748. };
  4749. Engine.prototype.createCubeTexture = function (rootUrl, scene, extensions, noMipmap) {
  4750. var _this = this;
  4751. var gl = this._gl;
  4752. var texture = gl.createTexture();
  4753. texture.isCube = true;
  4754. texture.url = rootUrl;
  4755. texture.references = 1;
  4756. this._loadedTexturesCache.push(texture);
  4757. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  4758. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  4759. if (isDDS) {
  4760. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  4761. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  4762. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  4763. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  4764. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  4765. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  4766. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  4767. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  4768. }
  4769. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  4770. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  4771. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4772. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4773. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  4774. _this._activeTexturesCache = [];
  4775. texture._width = info.width;
  4776. texture._height = info.height;
  4777. texture.isReady = true;
  4778. }, null, null, true);
  4779. }
  4780. else {
  4781. cascadeLoad(rootUrl, scene, function (imgs) {
  4782. var width = BABYLON.Tools.GetExponantOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  4783. var height = width;
  4784. _this._workingCanvas.width = width;
  4785. _this._workingCanvas.height = height;
  4786. var faces = [
  4787. gl.TEXTURE_CUBE_MAP_POSITIVE_X,
  4788. gl.TEXTURE_CUBE_MAP_POSITIVE_Y,
  4789. gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  4790. gl.TEXTURE_CUBE_MAP_NEGATIVE_X,
  4791. gl.TEXTURE_CUBE_MAP_NEGATIVE_Y,
  4792. gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  4793. ];
  4794. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  4795. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  4796. for (var index = 0; index < faces.length; index++) {
  4797. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  4798. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  4799. }
  4800. if (!noMipmap) {
  4801. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  4802. }
  4803. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  4804. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  4805. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4806. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4807. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  4808. _this._activeTexturesCache = [];
  4809. texture._width = width;
  4810. texture._height = height;
  4811. texture.isReady = true;
  4812. }, extensions);
  4813. }
  4814. return texture;
  4815. };
  4816. Engine.prototype._releaseTexture = function (texture) {
  4817. var gl = this._gl;
  4818. if (texture._framebuffer) {
  4819. gl.deleteFramebuffer(texture._framebuffer);
  4820. }
  4821. if (texture._depthBuffer) {
  4822. gl.deleteRenderbuffer(texture._depthBuffer);
  4823. }
  4824. gl.deleteTexture(texture);
  4825. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  4826. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  4827. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4828. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  4829. this._activeTexturesCache[channel] = null;
  4830. }
  4831. var index = this._loadedTexturesCache.indexOf(texture);
  4832. if (index !== -1) {
  4833. this._loadedTexturesCache.splice(index, 1);
  4834. }
  4835. };
  4836. Engine.prototype.bindSamplers = function (effect) {
  4837. this._gl.useProgram(effect.getProgram());
  4838. var samplers = effect.getSamplers();
  4839. for (var index = 0; index < samplers.length; index++) {
  4840. var uniform = effect.getUniform(samplers[index]);
  4841. this._gl.uniform1i(uniform, index);
  4842. }
  4843. this._currentEffect = null;
  4844. };
  4845. Engine.prototype._bindTexture = function (channel, texture) {
  4846. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  4847. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4848. this._activeTexturesCache[channel] = null;
  4849. };
  4850. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  4851. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  4852. };
  4853. Engine.prototype.setTexture = function (channel, texture) {
  4854. if (channel < 0) {
  4855. return;
  4856. }
  4857. // Not ready?
  4858. if (!texture || !texture.isReady()) {
  4859. if (this._activeTexturesCache[channel] != null) {
  4860. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  4861. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4862. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  4863. this._activeTexturesCache[channel] = null;
  4864. }
  4865. return;
  4866. }
  4867. // Video
  4868. if (texture instanceof BABYLON.VideoTexture) {
  4869. if (texture.update()) {
  4870. this._activeTexturesCache[channel] = null;
  4871. }
  4872. }
  4873. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  4874. texture.delayLoad();
  4875. return;
  4876. }
  4877. if (this._activeTexturesCache[channel] === texture) {
  4878. return;
  4879. }
  4880. this._activeTexturesCache[channel] = texture;
  4881. var internalTexture = texture.getInternalTexture();
  4882. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  4883. if (internalTexture.isCube) {
  4884. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  4885. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  4886. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  4887. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  4888. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  4889. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  4890. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  4891. }
  4892. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  4893. }
  4894. else {
  4895. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  4896. if (internalTexture._cachedWrapU !== texture.wrapU) {
  4897. internalTexture._cachedWrapU = texture.wrapU;
  4898. switch (texture.wrapU) {
  4899. case BABYLON.Texture.WRAP_ADDRESSMODE:
  4900. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  4901. break;
  4902. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  4903. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  4904. break;
  4905. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  4906. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  4907. break;
  4908. }
  4909. }
  4910. if (internalTexture._cachedWrapV !== texture.wrapV) {
  4911. internalTexture._cachedWrapV = texture.wrapV;
  4912. switch (texture.wrapV) {
  4913. case BABYLON.Texture.WRAP_ADDRESSMODE:
  4914. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  4915. break;
  4916. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  4917. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  4918. break;
  4919. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  4920. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  4921. break;
  4922. }
  4923. }
  4924. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  4925. }
  4926. };
  4927. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  4928. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  4929. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== texture.anisotropicFilteringLevel) {
  4930. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(texture.anisotropicFilteringLevel, this._caps.maxAnisotropy));
  4931. texture._cachedAnisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  4932. }
  4933. };
  4934. Engine.prototype.readPixels = function (x, y, width, height) {
  4935. var data = new Uint8Array(height * width * 4);
  4936. this._gl.readPixels(0, 0, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  4937. return data;
  4938. };
  4939. // Dispose
  4940. Engine.prototype.dispose = function () {
  4941. this.hideLoadingUI();
  4942. this.stopRenderLoop();
  4943. while (this.scenes.length) {
  4944. this.scenes[0].dispose();
  4945. }
  4946. // Release audio engine
  4947. Engine.audioEngine.dispose();
  4948. for (var name in this._compiledEffects) {
  4949. this._gl.deleteProgram(this._compiledEffects[name]._program);
  4950. }
  4951. for (var i in this._vertexAttribArrays) {
  4952. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  4953. continue;
  4954. }
  4955. this._gl.disableVertexAttribArray(i);
  4956. }
  4957. // Events
  4958. window.removeEventListener("blur", this._onBlur);
  4959. window.removeEventListener("focus", this._onFocus);
  4960. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  4961. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  4962. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  4963. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  4964. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  4965. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  4966. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  4967. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  4968. };
  4969. // Loading screen
  4970. Engine.prototype.displayLoadingUI = function () {
  4971. var _this = this;
  4972. this._loadingDiv = document.createElement("div");
  4973. this._loadingDiv.style.opacity = "0";
  4974. this._loadingDiv.style.transition = "opacity 1.5s ease";
  4975. // Loading text
  4976. this._loadingTextDiv = document.createElement("div");
  4977. this._loadingTextDiv.style.position = "absolute";
  4978. this._loadingTextDiv.style.left = "0";
  4979. this._loadingTextDiv.style.top = "50%";
  4980. this._loadingTextDiv.style.marginTop = "80px";
  4981. this._loadingTextDiv.style.width = "100%";
  4982. this._loadingTextDiv.style.height = "20px";
  4983. this._loadingTextDiv.style.fontFamily = "Arial";
  4984. this._loadingTextDiv.style.fontSize = "14px";
  4985. this._loadingTextDiv.style.color = "white";
  4986. this._loadingTextDiv.style.textAlign = "center";
  4987. this._loadingTextDiv.innerHTML = "Loading";
  4988. this._loadingDiv.appendChild(this._loadingTextDiv);
  4989. // Loading img
  4990. var imgBack = new Image();
  4991. 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==";
  4992. imgBack.style.position = "absolute";
  4993. imgBack.style.left = "50%";
  4994. imgBack.style.top = "50%";
  4995. imgBack.style.marginLeft = "-50px";
  4996. imgBack.style.marginTop = "-50px";
  4997. imgBack.style.transition = "transform 1.0s ease";
  4998. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  4999. var deg = 360;
  5000. var onTransitionEnd = function () {
  5001. deg += 360;
  5002. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  5003. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  5004. };
  5005. imgBack.addEventListener("transitionend", onTransitionEnd);
  5006. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  5007. this._loadingDiv.appendChild(imgBack);
  5008. // front image
  5009. var imgFront = new Image();
  5010. 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=";
  5011. imgFront.style.position = "absolute";
  5012. imgFront.style.left = "50%";
  5013. imgFront.style.top = "50%";
  5014. imgFront.style.marginLeft = "-50px";
  5015. imgFront.style.marginTop = "-50px";
  5016. this._loadingDiv.appendChild(imgFront);
  5017. // Resize
  5018. this._resizeLoadingUI = function () {
  5019. var canvasRect = _this.getRenderingCanvasClientRect();
  5020. _this._loadingDiv.style.position = "absolute";
  5021. _this._loadingDiv.style.left = canvasRect.left + "px";
  5022. _this._loadingDiv.style.top = canvasRect.top + "px";
  5023. _this._loadingDiv.style.width = canvasRect.width + "px";
  5024. _this._loadingDiv.style.height = canvasRect.height + "px";
  5025. };
  5026. this._resizeLoadingUI();
  5027. window.addEventListener("resize", this._resizeLoadingUI);
  5028. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  5029. document.body.appendChild(this._loadingDiv);
  5030. setTimeout(function () {
  5031. _this._loadingDiv.style.opacity = "1";
  5032. imgBack.style.transform = "rotateZ(360deg)";
  5033. imgBack.style.webkitTransform = "rotateZ(360deg)";
  5034. }, 0);
  5035. };
  5036. Object.defineProperty(Engine.prototype, "loadingUIText", {
  5037. set: function (text) {
  5038. if (!this._loadingDiv) {
  5039. return;
  5040. }
  5041. this._loadingTextDiv.innerHTML = text;
  5042. },
  5043. enumerable: true,
  5044. configurable: true
  5045. });
  5046. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  5047. get: function () {
  5048. return this._loadingDivBackgroundColor;
  5049. },
  5050. set: function (color) {
  5051. this._loadingDivBackgroundColor = color;
  5052. if (!this._loadingDiv) {
  5053. return;
  5054. }
  5055. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  5056. },
  5057. enumerable: true,
  5058. configurable: true
  5059. });
  5060. Engine.prototype.hideLoadingUI = function () {
  5061. var _this = this;
  5062. if (!this._loadingDiv) {
  5063. return;
  5064. }
  5065. var onTransitionEnd = function () {
  5066. if (!_this._loadingDiv) {
  5067. return;
  5068. }
  5069. document.body.removeChild(_this._loadingDiv);
  5070. window.removeEventListener("resize", _this._resizeLoadingUI);
  5071. _this._loadingDiv = null;
  5072. };
  5073. this._loadingDiv.style.opacity = "0";
  5074. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  5075. };
  5076. // FPS
  5077. Engine.prototype.getFps = function () {
  5078. return this.fps;
  5079. };
  5080. Engine.prototype.getDeltaTime = function () {
  5081. return this.deltaTime;
  5082. };
  5083. Engine.prototype._measureFps = function () {
  5084. this.previousFramesDuration.push(BABYLON.Tools.Now);
  5085. var length = this.previousFramesDuration.length;
  5086. if (length >= 2) {
  5087. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  5088. }
  5089. if (length >= this.fpsRange) {
  5090. if (length > this.fpsRange) {
  5091. this.previousFramesDuration.splice(0, 1);
  5092. length = this.previousFramesDuration.length;
  5093. }
  5094. var sum = 0;
  5095. for (var id = 0; id < length - 1; id++) {
  5096. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  5097. }
  5098. this.fps = 1000.0 / (sum / (length - 1));
  5099. }
  5100. };
  5101. // Statics
  5102. Engine.isSupported = function () {
  5103. try {
  5104. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  5105. if (navigator.isCocoonJS) {
  5106. return true;
  5107. }
  5108. var tempcanvas = document.createElement("canvas");
  5109. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  5110. return gl != null && !!window.WebGLRenderingContext;
  5111. }
  5112. catch (e) {
  5113. return false;
  5114. }
  5115. };
  5116. // Const statics
  5117. Engine._ALPHA_DISABLE = 0;
  5118. Engine._ALPHA_ADD = 1;
  5119. Engine._ALPHA_COMBINE = 2;
  5120. Engine._DELAYLOADSTATE_NONE = 0;
  5121. Engine._DELAYLOADSTATE_LOADED = 1;
  5122. Engine._DELAYLOADSTATE_LOADING = 2;
  5123. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  5124. Engine._TEXTUREFORMAT_ALPHA = 0;
  5125. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  5126. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  5127. Engine._TEXTUREFORMAT_RGB = 4;
  5128. Engine._TEXTUREFORMAT_RGBA = 4;
  5129. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  5130. Engine._TEXTURETYPE_FLOAT = 1;
  5131. // Updatable statics so stick with vars here
  5132. Engine.Epsilon = 0.001;
  5133. Engine.CollisionsEpsilon = 0.001;
  5134. Engine.ShadersRepository = "Babylon/Shaders/";
  5135. return Engine;
  5136. })();
  5137. BABYLON.Engine = Engine;
  5138. })(BABYLON || (BABYLON = {}));
  5139. //# sourceMappingURL=babylon.engine.js.mapvar BABYLON;
  5140. (function (BABYLON) {
  5141. /**
  5142. * Node is the basic class for all scene objects (Mesh, Light Camera).
  5143. */
  5144. var Node = (function () {
  5145. /**
  5146. * @constructor
  5147. * @param {string} name - the name and id to be given to this node
  5148. * @param {BABYLON.Scene} the scene this node will be added to
  5149. */
  5150. function Node(name, scene) {
  5151. this.state = "";
  5152. this.animations = new Array();
  5153. this._childrenFlag = -1;
  5154. this._isEnabled = true;
  5155. this._isReady = true;
  5156. this._currentRenderId = -1;
  5157. this.name = name;
  5158. this.id = name;
  5159. this._scene = scene;
  5160. this._initCache();
  5161. }
  5162. Node.prototype.getScene = function () {
  5163. return this._scene;
  5164. };
  5165. Node.prototype.getEngine = function () {
  5166. return this._scene.getEngine();
  5167. };
  5168. // override it in derived class
  5169. Node.prototype.getWorldMatrix = function () {
  5170. return BABYLON.Matrix.Identity();
  5171. };
  5172. // override it in derived class if you add new variables to the cache
  5173. // and call the parent class method
  5174. Node.prototype._initCache = function () {
  5175. this._cache = {};
  5176. this._cache.parent = undefined;
  5177. };
  5178. Node.prototype.updateCache = function (force) {
  5179. if (!force && this.isSynchronized())
  5180. return;
  5181. this._cache.parent = this.parent;
  5182. this._updateCache();
  5183. };
  5184. // override it in derived class if you add new variables to the cache
  5185. // and call the parent class method if !ignoreParentClass
  5186. Node.prototype._updateCache = function (ignoreParentClass) {
  5187. };
  5188. // override it in derived class if you add new variables to the cache
  5189. Node.prototype._isSynchronized = function () {
  5190. return true;
  5191. };
  5192. Node.prototype.isSynchronizedWithParent = function () {
  5193. return this.parent ? this.parent._currentRenderId <= this._currentRenderId : true;
  5194. };
  5195. Node.prototype.isSynchronized = function (updateCache) {
  5196. var check = this.hasNewParent();
  5197. check = check || !this.isSynchronizedWithParent();
  5198. check = check || !this._isSynchronized();
  5199. if (updateCache)
  5200. this.updateCache(true);
  5201. return !check;
  5202. };
  5203. Node.prototype.hasNewParent = function (update) {
  5204. if (this._cache.parent === this.parent)
  5205. return false;
  5206. if (update)
  5207. this._cache.parent = this.parent;
  5208. return true;
  5209. };
  5210. /**
  5211. * Is this node ready to be used/rendered
  5212. * @return {boolean} is it ready
  5213. */
  5214. Node.prototype.isReady = function () {
  5215. return this._isReady;
  5216. };
  5217. /**
  5218. * Is this node enabled.
  5219. * If the node has a parent and is enabled, the parent will be inspected as well.
  5220. * @return {boolean} whether this node (and its parent) is enabled.
  5221. * @see setEnabled
  5222. */
  5223. Node.prototype.isEnabled = function () {
  5224. if (!this._isEnabled) {
  5225. return false;
  5226. }
  5227. if (this.parent) {
  5228. return this.parent.isEnabled();
  5229. }
  5230. return true;
  5231. };
  5232. /**
  5233. * Set the enabled state of this node.
  5234. * @param {boolean} value - the new enabled state
  5235. * @see isEnabled
  5236. */
  5237. Node.prototype.setEnabled = function (value) {
  5238. this._isEnabled = value;
  5239. };
  5240. /**
  5241. * Is this node a descendant of the given node.
  5242. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  5243. * @param {BABYLON.Node} ancestor - The parent node to inspect
  5244. * @see parent
  5245. */
  5246. Node.prototype.isDescendantOf = function (ancestor) {
  5247. if (this.parent) {
  5248. if (this.parent === ancestor) {
  5249. return true;
  5250. }
  5251. return this.parent.isDescendantOf(ancestor);
  5252. }
  5253. return false;
  5254. };
  5255. Node.prototype._getDescendants = function (list, results) {
  5256. for (var index = 0; index < list.length; index++) {
  5257. var item = list[index];
  5258. if (item.isDescendantOf(this)) {
  5259. results.push(item);
  5260. }
  5261. }
  5262. };
  5263. /**
  5264. * Will return all nodes that have this node as parent.
  5265. * @return {BABYLON.Node[]} all children nodes of all types.
  5266. */
  5267. Node.prototype.getDescendants = function () {
  5268. var results = [];
  5269. this._getDescendants(this._scene.meshes, results);
  5270. this._getDescendants(this._scene.lights, results);
  5271. this._getDescendants(this._scene.cameras, results);
  5272. return results;
  5273. };
  5274. Node.prototype._setReady = function (state) {
  5275. if (state == this._isReady) {
  5276. return;
  5277. }
  5278. if (!state) {
  5279. this._isReady = false;
  5280. return;
  5281. }
  5282. this._isReady = true;
  5283. if (this.onReady) {
  5284. this.onReady(this);
  5285. }
  5286. };
  5287. return Node;
  5288. })();
  5289. BABYLON.Node = Node;
  5290. })(BABYLON || (BABYLON = {}));
  5291. //# sourceMappingURL=babylon.node.js.mapvar BABYLON;
  5292. (function (BABYLON) {
  5293. var BoundingSphere = (function () {
  5294. function BoundingSphere(minimum, maximum) {
  5295. this.minimum = minimum;
  5296. this.maximum = maximum;
  5297. this._tempRadiusVector = BABYLON.Vector3.Zero();
  5298. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  5299. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  5300. this.radius = distance * 0.5;
  5301. this.centerWorld = BABYLON.Vector3.Zero();
  5302. this._update(BABYLON.Matrix.Identity());
  5303. }
  5304. // Methods
  5305. BoundingSphere.prototype._update = function (world) {
  5306. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  5307. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  5308. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  5309. };
  5310. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  5311. for (var i = 0; i < 6; i++) {
  5312. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  5313. return false;
  5314. }
  5315. return true;
  5316. };
  5317. BoundingSphere.prototype.intersectsPoint = function (point) {
  5318. var x = this.centerWorld.x - point.x;
  5319. var y = this.centerWorld.y - point.y;
  5320. var z = this.centerWorld.z - point.z;
  5321. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  5322. if (Math.abs(this.radiusWorld - distance) < BABYLON.Engine.Epsilon)
  5323. return false;
  5324. return true;
  5325. };
  5326. // Statics
  5327. BoundingSphere.Intersects = function (sphere0, sphere1) {
  5328. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  5329. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  5330. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  5331. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  5332. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  5333. return false;
  5334. return true;
  5335. };
  5336. return BoundingSphere;
  5337. })();
  5338. BABYLON.BoundingSphere = BoundingSphere;
  5339. })(BABYLON || (BABYLON = {}));
  5340. //# sourceMappingURL=babylon.boundingSphere.js.mapvar BABYLON;
  5341. (function (BABYLON) {
  5342. var BoundingBox = (function () {
  5343. function BoundingBox(minimum, maximum) {
  5344. this.minimum = minimum;
  5345. this.maximum = maximum;
  5346. this.vectors = new Array();
  5347. this.vectorsWorld = new Array();
  5348. // Bounding vectors
  5349. this.vectors.push(this.minimum.clone());
  5350. this.vectors.push(this.maximum.clone());
  5351. this.vectors.push(this.minimum.clone());
  5352. this.vectors[2].x = this.maximum.x;
  5353. this.vectors.push(this.minimum.clone());
  5354. this.vectors[3].y = this.maximum.y;
  5355. this.vectors.push(this.minimum.clone());
  5356. this.vectors[4].z = this.maximum.z;
  5357. this.vectors.push(this.maximum.clone());
  5358. this.vectors[5].z = this.minimum.z;
  5359. this.vectors.push(this.maximum.clone());
  5360. this.vectors[6].x = this.minimum.x;
  5361. this.vectors.push(this.maximum.clone());
  5362. this.vectors[7].y = this.minimum.y;
  5363. // OBB
  5364. this.center = this.maximum.add(this.minimum).scale(0.5);
  5365. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  5366. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  5367. for (var index = 0; index < this.vectors.length; index++) {
  5368. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  5369. }
  5370. this.minimumWorld = BABYLON.Vector3.Zero();
  5371. this.maximumWorld = BABYLON.Vector3.Zero();
  5372. this._update(BABYLON.Matrix.Identity());
  5373. }
  5374. // Methods
  5375. BoundingBox.prototype.getWorldMatrix = function () {
  5376. return this._worldMatrix;
  5377. };
  5378. BoundingBox.prototype._update = function (world) {
  5379. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  5380. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  5381. for (var index = 0; index < this.vectors.length; index++) {
  5382. var v = this.vectorsWorld[index];
  5383. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  5384. if (v.x < this.minimumWorld.x)
  5385. this.minimumWorld.x = v.x;
  5386. if (v.y < this.minimumWorld.y)
  5387. this.minimumWorld.y = v.y;
  5388. if (v.z < this.minimumWorld.z)
  5389. this.minimumWorld.z = v.z;
  5390. if (v.x > this.maximumWorld.x)
  5391. this.maximumWorld.x = v.x;
  5392. if (v.y > this.maximumWorld.y)
  5393. this.maximumWorld.y = v.y;
  5394. if (v.z > this.maximumWorld.z)
  5395. this.maximumWorld.z = v.z;
  5396. }
  5397. // OBB
  5398. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  5399. this.center.scaleInPlace(0.5);
  5400. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  5401. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  5402. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  5403. this._worldMatrix = world;
  5404. };
  5405. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  5406. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  5407. };
  5408. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  5409. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  5410. };
  5411. BoundingBox.prototype.intersectsPoint = function (point) {
  5412. var delta = BABYLON.Engine.Epsilon;
  5413. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  5414. return false;
  5415. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  5416. return false;
  5417. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  5418. return false;
  5419. return true;
  5420. };
  5421. BoundingBox.prototype.intersectsSphere = function (sphere) {
  5422. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  5423. };
  5424. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  5425. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  5426. return false;
  5427. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  5428. return false;
  5429. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  5430. return false;
  5431. return true;
  5432. };
  5433. // Statics
  5434. BoundingBox.Intersects = function (box0, box1) {
  5435. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  5436. return false;
  5437. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  5438. return false;
  5439. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  5440. return false;
  5441. return true;
  5442. };
  5443. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  5444. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  5445. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  5446. return (num <= (sphereRadius * sphereRadius));
  5447. };
  5448. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  5449. for (var p = 0; p < 6; p++) {
  5450. for (var i = 0; i < 8; i++) {
  5451. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  5452. return false;
  5453. }
  5454. }
  5455. }
  5456. return true;
  5457. };
  5458. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  5459. for (var p = 0; p < 6; p++) {
  5460. var inCount = 8;
  5461. for (var i = 0; i < 8; i++) {
  5462. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  5463. --inCount;
  5464. }
  5465. else {
  5466. break;
  5467. }
  5468. }
  5469. if (inCount === 0)
  5470. return false;
  5471. }
  5472. return true;
  5473. };
  5474. return BoundingBox;
  5475. })();
  5476. BABYLON.BoundingBox = BoundingBox;
  5477. })(BABYLON || (BABYLON = {}));
  5478. //# sourceMappingURL=babylon.boundingBox.js.mapvar BABYLON;
  5479. (function (BABYLON) {
  5480. var computeBoxExtents = function (axis, box) {
  5481. var p = BABYLON.Vector3.Dot(box.center, axis);
  5482. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  5483. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  5484. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  5485. var r = r0 + r1 + r2;
  5486. return {
  5487. min: p - r,
  5488. max: p + r
  5489. };
  5490. };
  5491. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  5492. var axisOverlap = function (axis, box0, box1) {
  5493. var result0 = computeBoxExtents(axis, box0);
  5494. var result1 = computeBoxExtents(axis, box1);
  5495. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  5496. };
  5497. var BoundingInfo = (function () {
  5498. function BoundingInfo(minimum, maximum) {
  5499. this.minimum = minimum;
  5500. this.maximum = maximum;
  5501. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  5502. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  5503. }
  5504. // Methods
  5505. BoundingInfo.prototype._update = function (world) {
  5506. this.boundingBox._update(world);
  5507. this.boundingSphere._update(world);
  5508. };
  5509. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  5510. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  5511. return false;
  5512. return this.boundingBox.isInFrustum(frustumPlanes);
  5513. };
  5514. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  5515. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  5516. };
  5517. BoundingInfo.prototype._checkCollision = function (collider) {
  5518. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  5519. };
  5520. BoundingInfo.prototype.intersectsPoint = function (point) {
  5521. if (!this.boundingSphere.centerWorld) {
  5522. return false;
  5523. }
  5524. if (!this.boundingSphere.intersectsPoint(point)) {
  5525. return false;
  5526. }
  5527. if (!this.boundingBox.intersectsPoint(point)) {
  5528. return false;
  5529. }
  5530. return true;
  5531. };
  5532. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  5533. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  5534. return false;
  5535. }
  5536. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  5537. return false;
  5538. }
  5539. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  5540. return false;
  5541. }
  5542. if (!precise) {
  5543. return true;
  5544. }
  5545. var box0 = this.boundingBox;
  5546. var box1 = boundingInfo.boundingBox;
  5547. if (!axisOverlap(box0.directions[0], box0, box1))
  5548. return false;
  5549. if (!axisOverlap(box0.directions[1], box0, box1))
  5550. return false;
  5551. if (!axisOverlap(box0.directions[2], box0, box1))
  5552. return false;
  5553. if (!axisOverlap(box1.directions[0], box0, box1))
  5554. return false;
  5555. if (!axisOverlap(box1.directions[1], box0, box1))
  5556. return false;
  5557. if (!axisOverlap(box1.directions[2], box0, box1))
  5558. return false;
  5559. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  5560. return false;
  5561. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  5562. return false;
  5563. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  5564. return false;
  5565. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  5566. return false;
  5567. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  5568. return false;
  5569. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  5570. return false;
  5571. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  5572. return false;
  5573. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  5574. return false;
  5575. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  5576. return false;
  5577. return true;
  5578. };
  5579. return BoundingInfo;
  5580. })();
  5581. BABYLON.BoundingInfo = BoundingInfo;
  5582. })(BABYLON || (BABYLON = {}));
  5583. //# sourceMappingURL=babylon.boundingInfo.js.map
  5584. var BABYLON;
  5585. (function (BABYLON) {
  5586. var Light = (function (_super) {
  5587. __extends(Light, _super);
  5588. function Light(name, scene) {
  5589. _super.call(this, name, scene);
  5590. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  5591. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  5592. this.intensity = 1.0;
  5593. this.range = Number.MAX_VALUE;
  5594. this.includedOnlyMeshes = new Array();
  5595. this.excludedMeshes = new Array();
  5596. this._excludedMeshesIds = new Array();
  5597. this._includedOnlyMeshesIds = new Array();
  5598. scene.lights.push(this);
  5599. }
  5600. Light.prototype.getShadowGenerator = function () {
  5601. return this._shadowGenerator;
  5602. };
  5603. Light.prototype.getAbsolutePosition = function () {
  5604. return BABYLON.Vector3.Zero();
  5605. };
  5606. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  5607. };
  5608. Light.prototype._getWorldMatrix = function () {
  5609. return BABYLON.Matrix.Identity();
  5610. };
  5611. Light.prototype.canAffectMesh = function (mesh) {
  5612. if (!mesh) {
  5613. return true;
  5614. }
  5615. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  5616. return false;
  5617. }
  5618. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  5619. return false;
  5620. }
  5621. return true;
  5622. };
  5623. Light.prototype.getWorldMatrix = function () {
  5624. this._currentRenderId = this.getScene().getRenderId();
  5625. var worldMatrix = this._getWorldMatrix();
  5626. if (this.parent && this.parent.getWorldMatrix) {
  5627. if (!this._parentedWorldMatrix) {
  5628. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  5629. }
  5630. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  5631. return this._parentedWorldMatrix;
  5632. }
  5633. return worldMatrix;
  5634. };
  5635. Light.prototype.dispose = function () {
  5636. if (this._shadowGenerator) {
  5637. this._shadowGenerator.dispose();
  5638. this._shadowGenerator = null;
  5639. }
  5640. // Remove from scene
  5641. var index = this.getScene().lights.indexOf(this);
  5642. this.getScene().lights.splice(index, 1);
  5643. };
  5644. return Light;
  5645. })(BABYLON.Node);
  5646. BABYLON.Light = Light;
  5647. })(BABYLON || (BABYLON = {}));
  5648. //# sourceMappingURL=babylon.light.js.map
  5649. var BABYLON;
  5650. (function (BABYLON) {
  5651. var PointLight = (function (_super) {
  5652. __extends(PointLight, _super);
  5653. function PointLight(name, position, scene) {
  5654. _super.call(this, name, scene);
  5655. this.position = position;
  5656. }
  5657. PointLight.prototype.getAbsolutePosition = function () {
  5658. return this._transformedPosition ? this._transformedPosition : this.position;
  5659. };
  5660. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  5661. if (this.parent && this.parent.getWorldMatrix) {
  5662. if (!this._transformedPosition) {
  5663. this._transformedPosition = BABYLON.Vector3.Zero();
  5664. }
  5665. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this._transformedPosition);
  5666. effect.setFloat4(positionUniformName, this._transformedPosition.x, this._transformedPosition.y, this._transformedPosition.z, 0);
  5667. return;
  5668. }
  5669. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  5670. };
  5671. PointLight.prototype.getShadowGenerator = function () {
  5672. return null;
  5673. };
  5674. PointLight.prototype._getWorldMatrix = function () {
  5675. if (!this._worldMatrix) {
  5676. this._worldMatrix = BABYLON.Matrix.Identity();
  5677. }
  5678. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  5679. return this._worldMatrix;
  5680. };
  5681. return PointLight;
  5682. })(BABYLON.Light);
  5683. BABYLON.PointLight = PointLight;
  5684. })(BABYLON || (BABYLON = {}));
  5685. //# sourceMappingURL=babylon.pointLight.js.map
  5686. var BABYLON;
  5687. (function (BABYLON) {
  5688. var SpotLight = (function (_super) {
  5689. __extends(SpotLight, _super);
  5690. function SpotLight(name, position, direction, angle, exponent, scene) {
  5691. _super.call(this, name, scene);
  5692. this.position = position;
  5693. this.direction = direction;
  5694. this.angle = angle;
  5695. this.exponent = exponent;
  5696. }
  5697. SpotLight.prototype.getAbsolutePosition = function () {
  5698. return this.transformedPosition ? this.transformedPosition : this.position;
  5699. };
  5700. SpotLight.prototype.setDirectionToTarget = function (target) {
  5701. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  5702. return this.direction;
  5703. };
  5704. SpotLight.prototype.computeTransformedPosition = function () {
  5705. if (this.parent && this.parent.getWorldMatrix) {
  5706. if (!this.transformedPosition) {
  5707. this.transformedPosition = BABYLON.Vector3.Zero();
  5708. }
  5709. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  5710. return true;
  5711. }
  5712. return false;
  5713. };
  5714. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  5715. var normalizeDirection;
  5716. if (this.parent && this.parent.getWorldMatrix) {
  5717. if (!this._transformedDirection) {
  5718. this._transformedDirection = BABYLON.Vector3.Zero();
  5719. }
  5720. this.computeTransformedPosition();
  5721. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  5722. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  5723. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  5724. }
  5725. else {
  5726. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  5727. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  5728. }
  5729. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  5730. };
  5731. SpotLight.prototype._getWorldMatrix = function () {
  5732. if (!this._worldMatrix) {
  5733. this._worldMatrix = BABYLON.Matrix.Identity();
  5734. }
  5735. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  5736. return this._worldMatrix;
  5737. };
  5738. return SpotLight;
  5739. })(BABYLON.Light);
  5740. BABYLON.SpotLight = SpotLight;
  5741. })(BABYLON || (BABYLON = {}));
  5742. //# sourceMappingURL=babylon.spotLight.js.map
  5743. var BABYLON;
  5744. (function (BABYLON) {
  5745. var DirectionalLight = (function (_super) {
  5746. __extends(DirectionalLight, _super);
  5747. function DirectionalLight(name, direction, scene) {
  5748. _super.call(this, name, scene);
  5749. this.direction = direction;
  5750. this.position = direction.scale(-1);
  5751. }
  5752. DirectionalLight.prototype.getAbsolutePosition = function () {
  5753. return this.transformedPosition ? this.transformedPosition : this.position;
  5754. };
  5755. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  5756. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  5757. return this.direction;
  5758. };
  5759. DirectionalLight.prototype.computeTransformedPosition = function () {
  5760. if (this.parent && this.parent.getWorldMatrix) {
  5761. if (!this.transformedPosition) {
  5762. this.transformedPosition = BABYLON.Vector3.Zero();
  5763. }
  5764. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  5765. return true;
  5766. }
  5767. return false;
  5768. };
  5769. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  5770. if (this.parent && this.parent.getWorldMatrix) {
  5771. if (!this._transformedDirection) {
  5772. this._transformedDirection = BABYLON.Vector3.Zero();
  5773. }
  5774. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  5775. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  5776. return;
  5777. }
  5778. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  5779. };
  5780. DirectionalLight.prototype._getWorldMatrix = function () {
  5781. if (!this._worldMatrix) {
  5782. this._worldMatrix = BABYLON.Matrix.Identity();
  5783. }
  5784. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  5785. return this._worldMatrix;
  5786. };
  5787. return DirectionalLight;
  5788. })(BABYLON.Light);
  5789. BABYLON.DirectionalLight = DirectionalLight;
  5790. })(BABYLON || (BABYLON = {}));
  5791. //# sourceMappingURL=babylon.directionalLight.js.mapvar BABYLON;
  5792. (function (BABYLON) {
  5793. var ShadowGenerator = (function () {
  5794. function ShadowGenerator(mapSize, light) {
  5795. var _this = this;
  5796. // Members
  5797. this.filter = ShadowGenerator.FILTER_NONE;
  5798. this._darkness = 0;
  5799. this._transparencyShadow = false;
  5800. this._viewMatrix = BABYLON.Matrix.Zero();
  5801. this._projectionMatrix = BABYLON.Matrix.Zero();
  5802. this._transformMatrix = BABYLON.Matrix.Zero();
  5803. this._worldViewProjection = BABYLON.Matrix.Zero();
  5804. this._light = light;
  5805. this._scene = light.getScene();
  5806. light._shadowGenerator = this;
  5807. // Render target
  5808. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false);
  5809. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  5810. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  5811. this._shadowMap.renderParticles = false;
  5812. // Custom render function
  5813. var renderSubMesh = function (subMesh) {
  5814. var mesh = subMesh.getRenderingMesh();
  5815. var scene = _this._scene;
  5816. var engine = scene.getEngine();
  5817. // Culling
  5818. engine.setState(subMesh.getMaterial().backFaceCulling);
  5819. // Managing instances
  5820. var batch = mesh._getInstancesRenderList(subMesh._id);
  5821. if (batch.mustReturn) {
  5822. return;
  5823. }
  5824. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  5825. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  5826. engine.enableEffect(_this._effect);
  5827. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  5828. var material = subMesh.getMaterial();
  5829. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  5830. // Alpha test
  5831. if (material && material.needAlphaTesting()) {
  5832. var alphaTexture = material.getAlphaTestTexture();
  5833. _this._effect.setTexture("diffuseSampler", alphaTexture);
  5834. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  5835. }
  5836. // Bones
  5837. if (mesh.useBones) {
  5838. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  5839. }
  5840. // Draw
  5841. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  5842. }
  5843. else {
  5844. // Need to reset refresh rate of the shadowMap
  5845. _this._shadowMap.resetRefreshCounter();
  5846. }
  5847. };
  5848. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  5849. var index;
  5850. for (index = 0; index < opaqueSubMeshes.length; index++) {
  5851. renderSubMesh(opaqueSubMeshes.data[index]);
  5852. }
  5853. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  5854. renderSubMesh(alphaTestSubMeshes.data[index]);
  5855. }
  5856. if (_this._transparencyShadow) {
  5857. for (index = 0; index < transparentSubMeshes.length; index++) {
  5858. renderSubMesh(transparentSubMeshes.data[index]);
  5859. }
  5860. }
  5861. };
  5862. }
  5863. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  5864. // Static
  5865. get: function () {
  5866. return ShadowGenerator._FILTER_NONE;
  5867. },
  5868. enumerable: true,
  5869. configurable: true
  5870. });
  5871. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  5872. get: function () {
  5873. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  5874. },
  5875. enumerable: true,
  5876. configurable: true
  5877. });
  5878. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  5879. get: function () {
  5880. return ShadowGenerator._FILTER_POISSONSAMPLING;
  5881. },
  5882. enumerable: true,
  5883. configurable: true
  5884. });
  5885. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  5886. get: function () {
  5887. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP;
  5888. },
  5889. set: function (value) {
  5890. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  5891. },
  5892. enumerable: true,
  5893. configurable: true
  5894. });
  5895. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  5896. get: function () {
  5897. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  5898. },
  5899. set: function (value) {
  5900. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  5901. },
  5902. enumerable: true,
  5903. configurable: true
  5904. });
  5905. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  5906. var defines = [];
  5907. if (this.useVarianceShadowMap) {
  5908. defines.push("#define VSM");
  5909. }
  5910. var attribs = [BABYLON.VertexBuffer.PositionKind];
  5911. var mesh = subMesh.getMesh();
  5912. var material = subMesh.getMaterial();
  5913. // Alpha test
  5914. if (material && material.needAlphaTesting()) {
  5915. defines.push("#define ALPHATEST");
  5916. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  5917. attribs.push(BABYLON.VertexBuffer.UVKind);
  5918. defines.push("#define UV1");
  5919. }
  5920. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  5921. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  5922. defines.push("#define UV2");
  5923. }
  5924. }
  5925. // Bones
  5926. if (mesh.useBones) {
  5927. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  5928. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  5929. defines.push("#define BONES");
  5930. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  5931. }
  5932. // Instances
  5933. if (useInstances) {
  5934. defines.push("#define INSTANCES");
  5935. attribs.push("world0");
  5936. attribs.push("world1");
  5937. attribs.push("world2");
  5938. attribs.push("world3");
  5939. }
  5940. // Get correct effect
  5941. var join = defines.join("\n");
  5942. if (this._cachedDefines !== join) {
  5943. this._cachedDefines = join;
  5944. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  5945. }
  5946. return this._effect.isReady();
  5947. };
  5948. ShadowGenerator.prototype.getShadowMap = function () {
  5949. return this._shadowMap;
  5950. };
  5951. ShadowGenerator.prototype.getLight = function () {
  5952. return this._light;
  5953. };
  5954. // Methods
  5955. ShadowGenerator.prototype.getTransformMatrix = function () {
  5956. var lightPosition = this._light.position;
  5957. var lightDirection = this._light.direction;
  5958. if (this._light.computeTransformedPosition()) {
  5959. lightPosition = this._light.transformedPosition;
  5960. }
  5961. if (!this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !lightDirection.equals(this._cachedDirection)) {
  5962. this._cachedPosition = lightPosition.clone();
  5963. this._cachedDirection = lightDirection.clone();
  5964. var activeCamera = this._scene.activeCamera;
  5965. BABYLON.Matrix.LookAtLHToRef(lightPosition, this._light.position.add(lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  5966. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2.0, 1.0, activeCamera.minZ, activeCamera.maxZ, this._projectionMatrix);
  5967. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  5968. }
  5969. return this._transformMatrix;
  5970. };
  5971. ShadowGenerator.prototype.getDarkness = function () {
  5972. return this._darkness;
  5973. };
  5974. ShadowGenerator.prototype.setDarkness = function (darkness) {
  5975. if (darkness >= 1.0)
  5976. this._darkness = 1.0;
  5977. else if (darkness <= 0.0)
  5978. this._darkness = 0.0;
  5979. else
  5980. this._darkness = darkness;
  5981. };
  5982. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  5983. this._transparencyShadow = hasShadow;
  5984. };
  5985. ShadowGenerator.prototype.dispose = function () {
  5986. this._shadowMap.dispose();
  5987. };
  5988. ShadowGenerator._FILTER_NONE = 0;
  5989. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  5990. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  5991. return ShadowGenerator;
  5992. })();
  5993. BABYLON.ShadowGenerator = ShadowGenerator;
  5994. })(BABYLON || (BABYLON = {}));
  5995. //# sourceMappingURL=babylon.shadowGenerator.js.map
  5996. var BABYLON;
  5997. (function (BABYLON) {
  5998. var HemisphericLight = (function (_super) {
  5999. __extends(HemisphericLight, _super);
  6000. function HemisphericLight(name, direction, scene) {
  6001. _super.call(this, name, scene);
  6002. this.direction = direction;
  6003. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  6004. }
  6005. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  6006. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  6007. return this.direction;
  6008. };
  6009. HemisphericLight.prototype.getShadowGenerator = function () {
  6010. return null;
  6011. };
  6012. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  6013. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  6014. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  6015. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  6016. };
  6017. HemisphericLight.prototype._getWorldMatrix = function () {
  6018. if (!this._worldMatrix) {
  6019. this._worldMatrix = BABYLON.Matrix.Identity();
  6020. }
  6021. return this._worldMatrix;
  6022. };
  6023. return HemisphericLight;
  6024. })(BABYLON.Light);
  6025. BABYLON.HemisphericLight = HemisphericLight;
  6026. })(BABYLON || (BABYLON = {}));
  6027. //# sourceMappingURL=babylon.hemisphericLight.js.mapvar BABYLON;
  6028. (function (BABYLON) {
  6029. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  6030. if (boxMin.x > sphereCenter.x + sphereRadius)
  6031. return false;
  6032. if (sphereCenter.x - sphereRadius > boxMax.x)
  6033. return false;
  6034. if (boxMin.y > sphereCenter.y + sphereRadius)
  6035. return false;
  6036. if (sphereCenter.y - sphereRadius > boxMax.y)
  6037. return false;
  6038. if (boxMin.z > sphereCenter.z + sphereRadius)
  6039. return false;
  6040. if (sphereCenter.z - sphereRadius > boxMax.z)
  6041. return false;
  6042. return true;
  6043. };
  6044. var getLowestRoot = function (a, b, c, maxR) {
  6045. var determinant = b * b - 4.0 * a * c;
  6046. var result = { root: 0, found: false };
  6047. if (determinant < 0)
  6048. return result;
  6049. var sqrtD = Math.sqrt(determinant);
  6050. var r1 = (-b - sqrtD) / (2.0 * a);
  6051. var r2 = (-b + sqrtD) / (2.0 * a);
  6052. if (r1 > r2) {
  6053. var temp = r2;
  6054. r2 = r1;
  6055. r1 = temp;
  6056. }
  6057. if (r1 > 0 && r1 < maxR) {
  6058. result.root = r1;
  6059. result.found = true;
  6060. return result;
  6061. }
  6062. if (r2 > 0 && r2 < maxR) {
  6063. result.root = r2;
  6064. result.found = true;
  6065. return result;
  6066. }
  6067. return result;
  6068. };
  6069. var Collider = (function () {
  6070. function Collider() {
  6071. this.radius = new BABYLON.Vector3(1, 1, 1);
  6072. this.retry = 0;
  6073. this.basePointWorld = BABYLON.Vector3.Zero();
  6074. this.velocityWorld = BABYLON.Vector3.Zero();
  6075. this.normalizedVelocity = BABYLON.Vector3.Zero();
  6076. this._collisionPoint = BABYLON.Vector3.Zero();
  6077. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  6078. this._tempVector = BABYLON.Vector3.Zero();
  6079. this._tempVector2 = BABYLON.Vector3.Zero();
  6080. this._tempVector3 = BABYLON.Vector3.Zero();
  6081. this._tempVector4 = BABYLON.Vector3.Zero();
  6082. this._edge = BABYLON.Vector3.Zero();
  6083. this._baseToVertex = BABYLON.Vector3.Zero();
  6084. this._destinationPoint = BABYLON.Vector3.Zero();
  6085. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  6086. this._displacementVector = BABYLON.Vector3.Zero();
  6087. }
  6088. // Methods
  6089. Collider.prototype._initialize = function (source, dir, e) {
  6090. this.velocity = dir;
  6091. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  6092. this.basePoint = source;
  6093. source.multiplyToRef(this.radius, this.basePointWorld);
  6094. dir.multiplyToRef(this.radius, this.velocityWorld);
  6095. this.velocityWorldLength = this.velocityWorld.length();
  6096. this.epsilon = e;
  6097. this.collisionFound = false;
  6098. };
  6099. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  6100. pa.subtractToRef(point, this._tempVector);
  6101. pb.subtractToRef(point, this._tempVector2);
  6102. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  6103. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  6104. if (d < 0)
  6105. return false;
  6106. pc.subtractToRef(point, this._tempVector3);
  6107. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  6108. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  6109. if (d < 0)
  6110. return false;
  6111. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  6112. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  6113. return d >= 0;
  6114. };
  6115. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  6116. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  6117. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  6118. if (distance > this.velocityWorldLength + max + sphereRadius) {
  6119. return false;
  6120. }
  6121. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  6122. return false;
  6123. return true;
  6124. };
  6125. Collider.prototype._testTriangle = function (faceIndex, subMesh, p1, p2, p3) {
  6126. var t0;
  6127. var embeddedInPlane = false;
  6128. if (!subMesh._trianglePlanes) {
  6129. subMesh._trianglePlanes = [];
  6130. }
  6131. if (!subMesh._trianglePlanes[faceIndex]) {
  6132. subMesh._trianglePlanes[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  6133. subMesh._trianglePlanes[faceIndex].copyFromPoints(p1, p2, p3);
  6134. }
  6135. var trianglePlane = subMesh._trianglePlanes[faceIndex];
  6136. if ((!subMesh.getMaterial()) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  6137. return;
  6138. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  6139. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  6140. if (normalDotVelocity == 0) {
  6141. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  6142. return;
  6143. embeddedInPlane = true;
  6144. t0 = 0;
  6145. }
  6146. else {
  6147. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  6148. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  6149. if (t0 > t1) {
  6150. var temp = t1;
  6151. t1 = t0;
  6152. t0 = temp;
  6153. }
  6154. if (t0 > 1.0 || t1 < 0.0)
  6155. return;
  6156. if (t0 < 0)
  6157. t0 = 0;
  6158. if (t0 > 1.0)
  6159. t0 = 1.0;
  6160. }
  6161. this._collisionPoint.copyFromFloats(0, 0, 0);
  6162. var found = false;
  6163. var t = 1.0;
  6164. if (!embeddedInPlane) {
  6165. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  6166. this.velocity.scaleToRef(t0, this._tempVector);
  6167. this._planeIntersectionPoint.addInPlace(this._tempVector);
  6168. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  6169. found = true;
  6170. t = t0;
  6171. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  6172. }
  6173. }
  6174. if (!found) {
  6175. var velocitySquaredLength = this.velocity.lengthSquared();
  6176. var a = velocitySquaredLength;
  6177. this.basePoint.subtractToRef(p1, this._tempVector);
  6178. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  6179. var c = this._tempVector.lengthSquared() - 1.0;
  6180. var lowestRoot = getLowestRoot(a, b, c, t);
  6181. if (lowestRoot.found) {
  6182. t = lowestRoot.root;
  6183. found = true;
  6184. this._collisionPoint.copyFrom(p1);
  6185. }
  6186. this.basePoint.subtractToRef(p2, this._tempVector);
  6187. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  6188. c = this._tempVector.lengthSquared() - 1.0;
  6189. lowestRoot = getLowestRoot(a, b, c, t);
  6190. if (lowestRoot.found) {
  6191. t = lowestRoot.root;
  6192. found = true;
  6193. this._collisionPoint.copyFrom(p2);
  6194. }
  6195. this.basePoint.subtractToRef(p3, this._tempVector);
  6196. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  6197. c = this._tempVector.lengthSquared() - 1.0;
  6198. lowestRoot = getLowestRoot(a, b, c, t);
  6199. if (lowestRoot.found) {
  6200. t = lowestRoot.root;
  6201. found = true;
  6202. this._collisionPoint.copyFrom(p3);
  6203. }
  6204. p2.subtractToRef(p1, this._edge);
  6205. p1.subtractToRef(this.basePoint, this._baseToVertex);
  6206. var edgeSquaredLength = this._edge.lengthSquared();
  6207. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  6208. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  6209. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  6210. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  6211. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  6212. lowestRoot = getLowestRoot(a, b, c, t);
  6213. if (lowestRoot.found) {
  6214. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  6215. if (f >= 0.0 && f <= 1.0) {
  6216. t = lowestRoot.root;
  6217. found = true;
  6218. this._edge.scaleInPlace(f);
  6219. p1.addToRef(this._edge, this._collisionPoint);
  6220. }
  6221. }
  6222. p3.subtractToRef(p2, this._edge);
  6223. p2.subtractToRef(this.basePoint, this._baseToVertex);
  6224. edgeSquaredLength = this._edge.lengthSquared();
  6225. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  6226. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  6227. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  6228. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  6229. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  6230. lowestRoot = getLowestRoot(a, b, c, t);
  6231. if (lowestRoot.found) {
  6232. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  6233. if (f >= 0.0 && f <= 1.0) {
  6234. t = lowestRoot.root;
  6235. found = true;
  6236. this._edge.scaleInPlace(f);
  6237. p2.addToRef(this._edge, this._collisionPoint);
  6238. }
  6239. }
  6240. p1.subtractToRef(p3, this._edge);
  6241. p3.subtractToRef(this.basePoint, this._baseToVertex);
  6242. edgeSquaredLength = this._edge.lengthSquared();
  6243. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  6244. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  6245. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  6246. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  6247. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  6248. lowestRoot = getLowestRoot(a, b, c, t);
  6249. if (lowestRoot.found) {
  6250. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  6251. if (f >= 0.0 && f <= 1.0) {
  6252. t = lowestRoot.root;
  6253. found = true;
  6254. this._edge.scaleInPlace(f);
  6255. p3.addToRef(this._edge, this._collisionPoint);
  6256. }
  6257. }
  6258. }
  6259. if (found) {
  6260. var distToCollision = t * this.velocity.length();
  6261. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  6262. if (!this.intersectionPoint) {
  6263. this.intersectionPoint = this._collisionPoint.clone();
  6264. }
  6265. else {
  6266. this.intersectionPoint.copyFrom(this._collisionPoint);
  6267. }
  6268. this.nearestDistance = distToCollision;
  6269. this.collisionFound = true;
  6270. this.collidedMesh = subMesh.getMesh();
  6271. }
  6272. }
  6273. };
  6274. Collider.prototype._collide = function (subMesh, pts, indices, indexStart, indexEnd, decal) {
  6275. for (var i = indexStart; i < indexEnd; i += 3) {
  6276. var p1 = pts[indices[i] - decal];
  6277. var p2 = pts[indices[i + 1] - decal];
  6278. var p3 = pts[indices[i + 2] - decal];
  6279. this._testTriangle(i, subMesh, p3, p2, p1);
  6280. }
  6281. };
  6282. Collider.prototype._getResponse = function (pos, vel) {
  6283. pos.addToRef(vel, this._destinationPoint);
  6284. vel.scaleInPlace((this.nearestDistance / vel.length()));
  6285. this.basePoint.addToRef(vel, pos);
  6286. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  6287. this._slidePlaneNormal.normalize();
  6288. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  6289. pos.addInPlace(this._displacementVector);
  6290. this.intersectionPoint.addInPlace(this._displacementVector);
  6291. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  6292. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  6293. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  6294. };
  6295. return Collider;
  6296. })();
  6297. BABYLON.Collider = Collider;
  6298. })(BABYLON || (BABYLON = {}));
  6299. //# sourceMappingURL=babylon.collider.js.map
  6300. var BABYLON;
  6301. (function (BABYLON) {
  6302. var Camera = (function (_super) {
  6303. __extends(Camera, _super);
  6304. function Camera(name, position, scene) {
  6305. _super.call(this, name, scene);
  6306. this.position = position;
  6307. // Members
  6308. this.upVector = BABYLON.Vector3.Up();
  6309. this.orthoLeft = null;
  6310. this.orthoRight = null;
  6311. this.orthoBottom = null;
  6312. this.orthoTop = null;
  6313. this.fov = 0.8;
  6314. this.minZ = 1.0;
  6315. this.maxZ = 10000.0;
  6316. this.inertia = 0.9;
  6317. this.mode = Camera.PERSPECTIVE_CAMERA;
  6318. this.isIntermediate = false;
  6319. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  6320. this.subCameras = [];
  6321. this.layerMask = 0xFFFFFFFF;
  6322. this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  6323. this._computedViewMatrix = BABYLON.Matrix.Identity();
  6324. this._projectionMatrix = new BABYLON.Matrix();
  6325. this._postProcesses = new Array();
  6326. this._postProcessesTakenIndices = [];
  6327. this._activeMeshes = new BABYLON.SmartArray(256);
  6328. scene.cameras.push(this);
  6329. if (!scene.activeCamera) {
  6330. scene.activeCamera = this;
  6331. }
  6332. }
  6333. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  6334. get: function () {
  6335. return Camera._PERSPECTIVE_CAMERA;
  6336. },
  6337. enumerable: true,
  6338. configurable: true
  6339. });
  6340. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  6341. get: function () {
  6342. return Camera._ORTHOGRAPHIC_CAMERA;
  6343. },
  6344. enumerable: true,
  6345. configurable: true
  6346. });
  6347. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  6348. get: function () {
  6349. return Camera._FOVMODE_VERTICAL_FIXED;
  6350. },
  6351. enumerable: true,
  6352. configurable: true
  6353. });
  6354. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  6355. get: function () {
  6356. return Camera._FOVMODE_HORIZONTAL_FIXED;
  6357. },
  6358. enumerable: true,
  6359. configurable: true
  6360. });
  6361. Camera.prototype.getActiveMeshes = function () {
  6362. return this._activeMeshes;
  6363. };
  6364. Camera.prototype.isActiveMesh = function (mesh) {
  6365. return (this._activeMeshes.indexOf(mesh) !== -1);
  6366. };
  6367. //Cache
  6368. Camera.prototype._initCache = function () {
  6369. _super.prototype._initCache.call(this);
  6370. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6371. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6372. this._cache.mode = undefined;
  6373. this._cache.minZ = undefined;
  6374. this._cache.maxZ = undefined;
  6375. this._cache.fov = undefined;
  6376. this._cache.aspectRatio = undefined;
  6377. this._cache.orthoLeft = undefined;
  6378. this._cache.orthoRight = undefined;
  6379. this._cache.orthoBottom = undefined;
  6380. this._cache.orthoTop = undefined;
  6381. this._cache.renderWidth = undefined;
  6382. this._cache.renderHeight = undefined;
  6383. };
  6384. Camera.prototype._updateCache = function (ignoreParentClass) {
  6385. if (!ignoreParentClass) {
  6386. _super.prototype._updateCache.call(this);
  6387. }
  6388. var engine = this.getEngine();
  6389. this._cache.position.copyFrom(this.position);
  6390. this._cache.upVector.copyFrom(this.upVector);
  6391. this._cache.mode = this.mode;
  6392. this._cache.minZ = this.minZ;
  6393. this._cache.maxZ = this.maxZ;
  6394. this._cache.fov = this.fov;
  6395. this._cache.aspectRatio = engine.getAspectRatio(this);
  6396. this._cache.orthoLeft = this.orthoLeft;
  6397. this._cache.orthoRight = this.orthoRight;
  6398. this._cache.orthoBottom = this.orthoBottom;
  6399. this._cache.orthoTop = this.orthoTop;
  6400. this._cache.renderWidth = engine.getRenderWidth();
  6401. this._cache.renderHeight = engine.getRenderHeight();
  6402. };
  6403. Camera.prototype._updateFromScene = function () {
  6404. this.updateCache();
  6405. this._update();
  6406. };
  6407. // Synchronized
  6408. Camera.prototype._isSynchronized = function () {
  6409. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  6410. };
  6411. Camera.prototype._isSynchronizedViewMatrix = function () {
  6412. if (!_super.prototype._isSynchronized.call(this))
  6413. return false;
  6414. return this._cache.position.equals(this.position) && this._cache.upVector.equals(this.upVector) && this.isSynchronizedWithParent();
  6415. };
  6416. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  6417. var check = this._cache.mode === this.mode && this._cache.minZ === this.minZ && this._cache.maxZ === this.maxZ;
  6418. if (!check) {
  6419. return false;
  6420. }
  6421. var engine = this.getEngine();
  6422. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  6423. check = this._cache.fov === this.fov && this._cache.aspectRatio === engine.getAspectRatio(this);
  6424. }
  6425. else {
  6426. 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();
  6427. }
  6428. return check;
  6429. };
  6430. // Controls
  6431. Camera.prototype.attachControl = function (element) {
  6432. };
  6433. Camera.prototype.detachControl = function (element) {
  6434. };
  6435. Camera.prototype._update = function () {
  6436. };
  6437. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  6438. if (insertAt === void 0) { insertAt = null; }
  6439. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  6440. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  6441. return 0;
  6442. }
  6443. if (insertAt == null || insertAt < 0) {
  6444. this._postProcesses.push(postProcess);
  6445. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  6446. return this._postProcesses.length - 1;
  6447. }
  6448. var add = 0;
  6449. if (this._postProcesses[insertAt]) {
  6450. var start = this._postProcesses.length - 1;
  6451. for (var i = start; i >= insertAt + 1; --i) {
  6452. this._postProcesses[i + 1] = this._postProcesses[i];
  6453. }
  6454. add = 1;
  6455. }
  6456. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  6457. if (this._postProcessesTakenIndices[i] < insertAt) {
  6458. continue;
  6459. }
  6460. start = this._postProcessesTakenIndices.length - 1;
  6461. for (var j = start; j >= i; --j) {
  6462. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  6463. }
  6464. this._postProcessesTakenIndices[i] = insertAt;
  6465. break;
  6466. }
  6467. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) == -1) {
  6468. this._postProcessesTakenIndices.push(insertAt);
  6469. }
  6470. var result = insertAt + add;
  6471. this._postProcesses[result] = postProcess;
  6472. return result;
  6473. };
  6474. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  6475. if (atIndices === void 0) { atIndices = null; }
  6476. var result = [];
  6477. if (!atIndices) {
  6478. var length = this._postProcesses.length;
  6479. for (var i = 0; i < length; i++) {
  6480. if (this._postProcesses[i] !== postProcess) {
  6481. continue;
  6482. }
  6483. delete this._postProcesses[i];
  6484. var index = this._postProcessesTakenIndices.indexOf(i);
  6485. this._postProcessesTakenIndices.splice(index, 1);
  6486. }
  6487. }
  6488. else {
  6489. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  6490. for (i = 0; i < atIndices.length; i++) {
  6491. var foundPostProcess = this._postProcesses[atIndices[i]];
  6492. if (foundPostProcess !== postProcess) {
  6493. result.push(i);
  6494. continue;
  6495. }
  6496. delete this._postProcesses[atIndices[i]];
  6497. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  6498. this._postProcessesTakenIndices.splice(index, 1);
  6499. }
  6500. }
  6501. return result;
  6502. };
  6503. Camera.prototype.getWorldMatrix = function () {
  6504. if (!this._worldMatrix) {
  6505. this._worldMatrix = BABYLON.Matrix.Identity();
  6506. }
  6507. var viewMatrix = this.getViewMatrix();
  6508. viewMatrix.invertToRef(this._worldMatrix);
  6509. return this._worldMatrix;
  6510. };
  6511. Camera.prototype._getViewMatrix = function () {
  6512. return BABYLON.Matrix.Identity();
  6513. };
  6514. Camera.prototype.getViewMatrix = function () {
  6515. this._computedViewMatrix = this._computeViewMatrix();
  6516. if (!this.parent || !this.parent.getWorldMatrix || this.isSynchronized()) {
  6517. return this._computedViewMatrix;
  6518. }
  6519. if (!this._worldMatrix) {
  6520. this._worldMatrix = BABYLON.Matrix.Identity();
  6521. }
  6522. this._computedViewMatrix.invertToRef(this._worldMatrix);
  6523. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  6524. this._computedViewMatrix.invert();
  6525. this._currentRenderId = this.getScene().getRenderId();
  6526. return this._computedViewMatrix;
  6527. };
  6528. Camera.prototype._computeViewMatrix = function (force) {
  6529. if (!force && this._isSynchronizedViewMatrix()) {
  6530. return this._computedViewMatrix;
  6531. }
  6532. this._computedViewMatrix = this._getViewMatrix();
  6533. if (!this.parent || !this.parent.getWorldMatrix) {
  6534. this._currentRenderId = this.getScene().getRenderId();
  6535. }
  6536. return this._computedViewMatrix;
  6537. };
  6538. Camera.prototype.getProjectionMatrix = function (force) {
  6539. if (!force && this._isSynchronizedProjectionMatrix()) {
  6540. return this._projectionMatrix;
  6541. }
  6542. var engine = this.getEngine();
  6543. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  6544. if (this.minZ <= 0) {
  6545. this.minZ = 0.1;
  6546. }
  6547. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode);
  6548. return this._projectionMatrix;
  6549. }
  6550. var halfWidth = engine.getRenderWidth() / 2.0;
  6551. var halfHeight = engine.getRenderHeight() / 2.0;
  6552. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  6553. return this._projectionMatrix;
  6554. };
  6555. Camera.prototype.dispose = function () {
  6556. // Remove from scene
  6557. var index = this.getScene().cameras.indexOf(this);
  6558. this.getScene().cameras.splice(index, 1);
  6559. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  6560. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  6561. }
  6562. };
  6563. // Statics
  6564. Camera._PERSPECTIVE_CAMERA = 0;
  6565. Camera._ORTHOGRAPHIC_CAMERA = 1;
  6566. Camera._FOVMODE_VERTICAL_FIXED = 0;
  6567. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  6568. return Camera;
  6569. })(BABYLON.Node);
  6570. BABYLON.Camera = Camera;
  6571. })(BABYLON || (BABYLON = {}));
  6572. //# sourceMappingURL=babylon.camera.js.map
  6573. var BABYLON;
  6574. (function (BABYLON) {
  6575. var TargetCamera = (function (_super) {
  6576. __extends(TargetCamera, _super);
  6577. function TargetCamera(name, position, scene) {
  6578. _super.call(this, name, position, scene);
  6579. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  6580. this.cameraRotation = new BABYLON.Vector2(0, 0);
  6581. this.rotation = new BABYLON.Vector3(0, 0, 0);
  6582. this.speed = 2.0;
  6583. this.noRotationConstraint = false;
  6584. this.lockedTarget = null;
  6585. this._currentTarget = BABYLON.Vector3.Zero();
  6586. this._viewMatrix = BABYLON.Matrix.Zero();
  6587. this._camMatrix = BABYLON.Matrix.Zero();
  6588. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  6589. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  6590. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  6591. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  6592. this._lookAtTemp = BABYLON.Matrix.Zero();
  6593. this._tempMatrix = BABYLON.Matrix.Zero();
  6594. }
  6595. TargetCamera.prototype._getLockedTargetPosition = function () {
  6596. if (!this.lockedTarget) {
  6597. return null;
  6598. }
  6599. return this.lockedTarget.position || this.lockedTarget;
  6600. };
  6601. // Cache
  6602. TargetCamera.prototype._initCache = function () {
  6603. _super.prototype._initCache.call(this);
  6604. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6605. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6606. };
  6607. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  6608. if (!ignoreParentClass) {
  6609. _super.prototype._updateCache.call(this);
  6610. }
  6611. var lockedTargetPosition = this._getLockedTargetPosition();
  6612. if (!lockedTargetPosition) {
  6613. this._cache.lockedTarget = null;
  6614. }
  6615. else {
  6616. if (!this._cache.lockedTarget) {
  6617. this._cache.lockedTarget = lockedTargetPosition.clone();
  6618. }
  6619. else {
  6620. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  6621. }
  6622. }
  6623. this._cache.rotation.copyFrom(this.rotation);
  6624. };
  6625. // Synchronized
  6626. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  6627. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  6628. return false;
  6629. }
  6630. var lockedTargetPosition = this._getLockedTargetPosition();
  6631. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition) && this._cache.rotation.equals(this.rotation);
  6632. };
  6633. // Methods
  6634. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  6635. var engine = this.getEngine();
  6636. return this.speed * ((engine.getDeltaTime() / (engine.getFps() * 10.0)));
  6637. };
  6638. // Target
  6639. TargetCamera.prototype.setTarget = function (target) {
  6640. this.upVector.normalize();
  6641. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  6642. this._camMatrix.invert();
  6643. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  6644. var vDir = target.subtract(this.position);
  6645. if (vDir.x >= 0.0) {
  6646. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  6647. }
  6648. else {
  6649. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  6650. }
  6651. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  6652. if (isNaN(this.rotation.x)) {
  6653. this.rotation.x = 0;
  6654. }
  6655. if (isNaN(this.rotation.y)) {
  6656. this.rotation.y = 0;
  6657. }
  6658. if (isNaN(this.rotation.z)) {
  6659. this.rotation.z = 0;
  6660. }
  6661. };
  6662. TargetCamera.prototype.getTarget = function () {
  6663. return this._currentTarget;
  6664. };
  6665. TargetCamera.prototype._decideIfNeedsToMove = function () {
  6666. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  6667. };
  6668. TargetCamera.prototype._updatePosition = function () {
  6669. this.position.addInPlace(this.cameraDirection);
  6670. };
  6671. TargetCamera.prototype._update = function () {
  6672. var needToMove = this._decideIfNeedsToMove();
  6673. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  6674. // Move
  6675. if (needToMove) {
  6676. this._updatePosition();
  6677. }
  6678. // Rotate
  6679. if (needToRotate) {
  6680. this.rotation.x += this.cameraRotation.x;
  6681. this.rotation.y += this.cameraRotation.y;
  6682. if (!this.noRotationConstraint) {
  6683. var limit = (Math.PI / 2) * 0.95;
  6684. if (this.rotation.x > limit)
  6685. this.rotation.x = limit;
  6686. if (this.rotation.x < -limit)
  6687. this.rotation.x = -limit;
  6688. }
  6689. }
  6690. // Inertia
  6691. if (needToMove) {
  6692. if (Math.abs(this.cameraDirection.x) < BABYLON.Engine.Epsilon) {
  6693. this.cameraDirection.x = 0;
  6694. }
  6695. if (Math.abs(this.cameraDirection.y) < BABYLON.Engine.Epsilon) {
  6696. this.cameraDirection.y = 0;
  6697. }
  6698. if (Math.abs(this.cameraDirection.z) < BABYLON.Engine.Epsilon) {
  6699. this.cameraDirection.z = 0;
  6700. }
  6701. this.cameraDirection.scaleInPlace(this.inertia);
  6702. }
  6703. if (needToRotate) {
  6704. if (Math.abs(this.cameraRotation.x) < BABYLON.Engine.Epsilon) {
  6705. this.cameraRotation.x = 0;
  6706. }
  6707. if (Math.abs(this.cameraRotation.y) < BABYLON.Engine.Epsilon) {
  6708. this.cameraRotation.y = 0;
  6709. }
  6710. this.cameraRotation.scaleInPlace(this.inertia);
  6711. }
  6712. };
  6713. TargetCamera.prototype._getViewMatrix = function () {
  6714. if (!this.lockedTarget) {
  6715. // Compute
  6716. if (this.upVector.x != 0 || this.upVector.y != 1.0 || this.upVector.z != 0) {
  6717. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  6718. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  6719. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  6720. this._lookAtTemp.invert();
  6721. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  6722. }
  6723. else {
  6724. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  6725. }
  6726. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  6727. // Computing target and final matrix
  6728. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  6729. }
  6730. else {
  6731. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  6732. }
  6733. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  6734. return this._viewMatrix;
  6735. };
  6736. return TargetCamera;
  6737. })(BABYLON.Camera);
  6738. BABYLON.TargetCamera = TargetCamera;
  6739. })(BABYLON || (BABYLON = {}));
  6740. //# sourceMappingURL=babylon.targetCamera.js.map
  6741. var BABYLON;
  6742. (function (BABYLON) {
  6743. var FollowCamera = (function (_super) {
  6744. __extends(FollowCamera, _super);
  6745. function FollowCamera(name, position, scene) {
  6746. _super.call(this, name, position, scene);
  6747. this.radius = 12;
  6748. this.rotationOffset = 0;
  6749. this.heightOffset = 4;
  6750. this.cameraAcceleration = 0.05;
  6751. this.maxCameraSpeed = 20;
  6752. }
  6753. FollowCamera.prototype.getRadians = function (degrees) {
  6754. return degrees * Math.PI / 180;
  6755. };
  6756. FollowCamera.prototype.follow = function (cameraTarget) {
  6757. if (!cameraTarget)
  6758. return;
  6759. var radians = this.getRadians(this.rotationOffset) + cameraTarget.rotation.y;
  6760. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  6761. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  6762. var dx = targetX - this.position.x;
  6763. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  6764. var dz = (targetZ) - this.position.z;
  6765. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  6766. var vy = dy * this.cameraAcceleration;
  6767. var vz = dz * this.cameraAcceleration * 2;
  6768. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  6769. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  6770. }
  6771. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  6772. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  6773. }
  6774. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  6775. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  6776. }
  6777. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  6778. this.setTarget(cameraTarget.position);
  6779. };
  6780. FollowCamera.prototype._update = function () {
  6781. _super.prototype._update.call(this);
  6782. this.follow(this.target);
  6783. };
  6784. return FollowCamera;
  6785. })(BABYLON.TargetCamera);
  6786. BABYLON.FollowCamera = FollowCamera;
  6787. })(BABYLON || (BABYLON = {}));
  6788. //# sourceMappingURL=babylon.followCamera.js.map
  6789. var BABYLON;
  6790. (function (BABYLON) {
  6791. var FreeCamera = (function (_super) {
  6792. __extends(FreeCamera, _super);
  6793. function FreeCamera(name, position, scene) {
  6794. _super.call(this, name, position, scene);
  6795. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  6796. this.keysUp = [38];
  6797. this.keysDown = [40];
  6798. this.keysLeft = [37];
  6799. this.keysRight = [39];
  6800. this.checkCollisions = false;
  6801. this.applyGravity = false;
  6802. this.angularSensibility = 2000.0;
  6803. this._keys = [];
  6804. this._collider = new BABYLON.Collider();
  6805. this._needMoveForGravity = true;
  6806. this._oldPosition = BABYLON.Vector3.Zero();
  6807. this._diffPosition = BABYLON.Vector3.Zero();
  6808. this._newPosition = BABYLON.Vector3.Zero();
  6809. }
  6810. // Controls
  6811. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  6812. var _this = this;
  6813. var previousPosition;
  6814. var engine = this.getEngine();
  6815. if (this._attachedElement) {
  6816. return;
  6817. }
  6818. this._attachedElement = element;
  6819. if (this._onMouseDown === undefined) {
  6820. this._onMouseDown = function (evt) {
  6821. previousPosition = {
  6822. x: evt.clientX,
  6823. y: evt.clientY
  6824. };
  6825. if (!noPreventDefault) {
  6826. evt.preventDefault();
  6827. }
  6828. };
  6829. this._onMouseUp = function (evt) {
  6830. previousPosition = null;
  6831. if (!noPreventDefault) {
  6832. evt.preventDefault();
  6833. }
  6834. };
  6835. this._onMouseOut = function (evt) {
  6836. previousPosition = null;
  6837. _this._keys = [];
  6838. if (!noPreventDefault) {
  6839. evt.preventDefault();
  6840. }
  6841. };
  6842. this._onMouseMove = function (evt) {
  6843. if (!previousPosition && !engine.isPointerLock) {
  6844. return;
  6845. }
  6846. var offsetX;
  6847. var offsetY;
  6848. if (!engine.isPointerLock) {
  6849. offsetX = evt.clientX - previousPosition.x;
  6850. offsetY = evt.clientY - previousPosition.y;
  6851. }
  6852. else {
  6853. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  6854. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  6855. }
  6856. _this.cameraRotation.y += offsetX / _this.angularSensibility;
  6857. _this.cameraRotation.x += offsetY / _this.angularSensibility;
  6858. previousPosition = {
  6859. x: evt.clientX,
  6860. y: evt.clientY
  6861. };
  6862. if (!noPreventDefault) {
  6863. evt.preventDefault();
  6864. }
  6865. };
  6866. this._onKeyDown = function (evt) {
  6867. 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) {
  6868. var index = _this._keys.indexOf(evt.keyCode);
  6869. if (index === -1) {
  6870. _this._keys.push(evt.keyCode);
  6871. }
  6872. if (!noPreventDefault) {
  6873. evt.preventDefault();
  6874. }
  6875. }
  6876. };
  6877. this._onKeyUp = function (evt) {
  6878. 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) {
  6879. var index = _this._keys.indexOf(evt.keyCode);
  6880. if (index >= 0) {
  6881. _this._keys.splice(index, 1);
  6882. }
  6883. if (!noPreventDefault) {
  6884. evt.preventDefault();
  6885. }
  6886. }
  6887. };
  6888. this._onLostFocus = function () {
  6889. _this._keys = [];
  6890. };
  6891. this._reset = function () {
  6892. _this._keys = [];
  6893. previousPosition = null;
  6894. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  6895. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  6896. };
  6897. }
  6898. element.addEventListener("mousedown", this._onMouseDown, false);
  6899. element.addEventListener("mouseup", this._onMouseUp, false);
  6900. element.addEventListener("mouseout", this._onMouseOut, false);
  6901. element.addEventListener("mousemove", this._onMouseMove, false);
  6902. BABYLON.Tools.RegisterTopRootEvents([
  6903. { name: "keydown", handler: this._onKeyDown },
  6904. { name: "keyup", handler: this._onKeyUp },
  6905. { name: "blur", handler: this._onLostFocus }
  6906. ]);
  6907. };
  6908. FreeCamera.prototype.detachControl = function (element) {
  6909. if (this._attachedElement != element) {
  6910. return;
  6911. }
  6912. element.removeEventListener("mousedown", this._onMouseDown);
  6913. element.removeEventListener("mouseup", this._onMouseUp);
  6914. element.removeEventListener("mouseout", this._onMouseOut);
  6915. element.removeEventListener("mousemove", this._onMouseMove);
  6916. BABYLON.Tools.UnregisterTopRootEvents([
  6917. { name: "keydown", handler: this._onKeyDown },
  6918. { name: "keyup", handler: this._onKeyUp },
  6919. { name: "blur", handler: this._onLostFocus }
  6920. ]);
  6921. this._attachedElement = null;
  6922. if (this._reset) {
  6923. this._reset();
  6924. }
  6925. };
  6926. FreeCamera.prototype._collideWithWorld = function (velocity) {
  6927. var globalPosition;
  6928. if (this.parent) {
  6929. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  6930. }
  6931. else {
  6932. globalPosition = this.position;
  6933. }
  6934. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  6935. this._collider.radius = this.ellipsoid;
  6936. this.getScene()._getNewPosition(this._oldPosition, velocity, this._collider, 3, this._newPosition);
  6937. this._newPosition.subtractToRef(this._oldPosition, this._diffPosition);
  6938. if (this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  6939. this.position.addInPlace(this._diffPosition);
  6940. if (this.onCollide) {
  6941. this.onCollide(this._collider.collidedMesh);
  6942. }
  6943. }
  6944. };
  6945. FreeCamera.prototype._checkInputs = function () {
  6946. if (!this._localDirection) {
  6947. this._localDirection = BABYLON.Vector3.Zero();
  6948. this._transformedDirection = BABYLON.Vector3.Zero();
  6949. }
  6950. for (var index = 0; index < this._keys.length; index++) {
  6951. var keyCode = this._keys[index];
  6952. var speed = this._computeLocalCameraSpeed();
  6953. if (this.keysLeft.indexOf(keyCode) !== -1) {
  6954. this._localDirection.copyFromFloats(-speed, 0, 0);
  6955. }
  6956. else if (this.keysUp.indexOf(keyCode) !== -1) {
  6957. this._localDirection.copyFromFloats(0, 0, speed);
  6958. }
  6959. else if (this.keysRight.indexOf(keyCode) !== -1) {
  6960. this._localDirection.copyFromFloats(speed, 0, 0);
  6961. }
  6962. else if (this.keysDown.indexOf(keyCode) !== -1) {
  6963. this._localDirection.copyFromFloats(0, 0, -speed);
  6964. }
  6965. this.getViewMatrix().invertToRef(this._cameraTransformMatrix);
  6966. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  6967. this.cameraDirection.addInPlace(this._transformedDirection);
  6968. }
  6969. };
  6970. FreeCamera.prototype._decideIfNeedsToMove = function () {
  6971. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  6972. };
  6973. FreeCamera.prototype._updatePosition = function () {
  6974. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  6975. this._collideWithWorld(this.cameraDirection);
  6976. if (this.applyGravity) {
  6977. var oldPosition = this.position;
  6978. this._collideWithWorld(this.getScene().gravity);
  6979. this._needMoveForGravity = (BABYLON.Vector3.DistanceSquared(oldPosition, this.position) != 0);
  6980. }
  6981. }
  6982. else {
  6983. this.position.addInPlace(this.cameraDirection);
  6984. }
  6985. };
  6986. FreeCamera.prototype._update = function () {
  6987. this._checkInputs();
  6988. _super.prototype._update.call(this);
  6989. };
  6990. return FreeCamera;
  6991. })(BABYLON.TargetCamera);
  6992. BABYLON.FreeCamera = FreeCamera;
  6993. })(BABYLON || (BABYLON = {}));
  6994. //# sourceMappingURL=babylon.freeCamera.js.map
  6995. var BABYLON;
  6996. (function (BABYLON) {
  6997. // We're mainly based on the logic defined into the FreeCamera code
  6998. var TouchCamera = (function (_super) {
  6999. __extends(TouchCamera, _super);
  7000. function TouchCamera(name, position, scene) {
  7001. _super.call(this, name, position, scene);
  7002. this._offsetX = null;
  7003. this._offsetY = null;
  7004. this._pointerCount = 0;
  7005. this._pointerPressed = [];
  7006. this.angularSensibility = 200000.0;
  7007. this.moveSensibility = 500.0;
  7008. }
  7009. TouchCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  7010. var _this = this;
  7011. var previousPosition;
  7012. if (this._attachedCanvas) {
  7013. return;
  7014. }
  7015. this._attachedCanvas = canvas;
  7016. if (this._onPointerDown === undefined) {
  7017. this._onPointerDown = function (evt) {
  7018. if (!noPreventDefault) {
  7019. evt.preventDefault();
  7020. }
  7021. _this._pointerPressed.push(evt.pointerId);
  7022. if (_this._pointerPressed.length !== 1) {
  7023. return;
  7024. }
  7025. previousPosition = {
  7026. x: evt.clientX,
  7027. y: evt.clientY
  7028. };
  7029. };
  7030. this._onPointerUp = function (evt) {
  7031. if (!noPreventDefault) {
  7032. evt.preventDefault();
  7033. }
  7034. var index = _this._pointerPressed.indexOf(evt.pointerId);
  7035. if (index === -1) {
  7036. return;
  7037. }
  7038. _this._pointerPressed.splice(index, 1);
  7039. if (index != 0) {
  7040. return;
  7041. }
  7042. previousPosition = null;
  7043. _this._offsetX = null;
  7044. _this._offsetY = null;
  7045. };
  7046. this._onPointerMove = function (evt) {
  7047. if (!noPreventDefault) {
  7048. evt.preventDefault();
  7049. }
  7050. if (!previousPosition) {
  7051. return;
  7052. }
  7053. var index = _this._pointerPressed.indexOf(evt.pointerId);
  7054. if (index != 0) {
  7055. return;
  7056. }
  7057. _this._offsetX = evt.clientX - previousPosition.x;
  7058. _this._offsetY = -(evt.clientY - previousPosition.y);
  7059. };
  7060. this._onLostFocus = function () {
  7061. _this._offsetX = null;
  7062. _this._offsetY = null;
  7063. };
  7064. }
  7065. canvas.addEventListener("pointerdown", this._onPointerDown);
  7066. canvas.addEventListener("pointerup", this._onPointerUp);
  7067. canvas.addEventListener("pointerout", this._onPointerUp);
  7068. canvas.addEventListener("pointermove", this._onPointerMove);
  7069. BABYLON.Tools.RegisterTopRootEvents([
  7070. { name: "blur", handler: this._onLostFocus }
  7071. ]);
  7072. };
  7073. TouchCamera.prototype.detachControl = function (canvas) {
  7074. if (this._attachedCanvas != canvas) {
  7075. return;
  7076. }
  7077. canvas.removeEventListener("pointerdown", this._onPointerDown);
  7078. canvas.removeEventListener("pointerup", this._onPointerUp);
  7079. canvas.removeEventListener("pointerout", this._onPointerUp);
  7080. canvas.removeEventListener("pointermove", this._onPointerMove);
  7081. BABYLON.Tools.UnregisterTopRootEvents([
  7082. { name: "blur", handler: this._onLostFocus }
  7083. ]);
  7084. this._attachedCanvas = null;
  7085. };
  7086. TouchCamera.prototype._checkInputs = function () {
  7087. if (!this._offsetX) {
  7088. return;
  7089. }
  7090. this.cameraRotation.y += this._offsetX / this.angularSensibility;
  7091. if (this._pointerPressed.length > 1) {
  7092. this.cameraRotation.x += -this._offsetY / this.angularSensibility;
  7093. }
  7094. else {
  7095. var speed = this._computeLocalCameraSpeed();
  7096. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  7097. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  7098. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  7099. }
  7100. };
  7101. return TouchCamera;
  7102. })(BABYLON.FreeCamera);
  7103. BABYLON.TouchCamera = TouchCamera;
  7104. })(BABYLON || (BABYLON = {}));
  7105. //# sourceMappingURL=babylon.touchCamera.js.map
  7106. var BABYLON;
  7107. (function (BABYLON) {
  7108. // We're mainly based on the logic defined into the FreeCamera code
  7109. var DeviceOrientationCamera = (function (_super) {
  7110. __extends(DeviceOrientationCamera, _super);
  7111. function DeviceOrientationCamera(name, position, scene) {
  7112. var _this = this;
  7113. _super.call(this, name, position, scene);
  7114. this._offsetX = null;
  7115. this._offsetY = null;
  7116. this._orientationGamma = 0;
  7117. this._orientationBeta = 0;
  7118. this._initialOrientationGamma = 0;
  7119. this._initialOrientationBeta = 0;
  7120. this.angularSensibility = 10000.0;
  7121. this.moveSensibility = 50.0;
  7122. window.addEventListener("resize", function () {
  7123. _this._initialOrientationGamma = null;
  7124. }, false);
  7125. }
  7126. DeviceOrientationCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  7127. var _this = this;
  7128. if (this._attachedCanvas) {
  7129. return;
  7130. }
  7131. this._attachedCanvas = canvas;
  7132. if (!this._orientationChanged) {
  7133. this._orientationChanged = function (evt) {
  7134. if (!_this._initialOrientationGamma) {
  7135. _this._initialOrientationGamma = evt.gamma;
  7136. _this._initialOrientationBeta = evt.beta;
  7137. }
  7138. _this._orientationGamma = evt.gamma;
  7139. _this._orientationBeta = evt.beta;
  7140. _this._offsetY = (_this._initialOrientationBeta - _this._orientationBeta);
  7141. _this._offsetX = (_this._initialOrientationGamma - _this._orientationGamma);
  7142. };
  7143. }
  7144. window.addEventListener("deviceorientation", this._orientationChanged);
  7145. };
  7146. DeviceOrientationCamera.prototype.detachControl = function (canvas) {
  7147. if (this._attachedCanvas != canvas) {
  7148. return;
  7149. }
  7150. window.removeEventListener("deviceorientation", this._orientationChanged);
  7151. this._attachedCanvas = null;
  7152. this._orientationGamma = 0;
  7153. this._orientationBeta = 0;
  7154. this._initialOrientationGamma = 0;
  7155. this._initialOrientationBeta = 0;
  7156. };
  7157. DeviceOrientationCamera.prototype._checkInputs = function () {
  7158. if (!this._offsetX) {
  7159. return;
  7160. }
  7161. this.cameraRotation.y -= this._offsetX / this.angularSensibility;
  7162. var speed = this._computeLocalCameraSpeed();
  7163. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  7164. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  7165. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  7166. };
  7167. return DeviceOrientationCamera;
  7168. })(BABYLON.FreeCamera);
  7169. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  7170. })(BABYLON || (BABYLON = {}));
  7171. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  7172. var BABYLON;
  7173. (function (BABYLON) {
  7174. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  7175. var ArcRotateCamera = (function (_super) {
  7176. __extends(ArcRotateCamera, _super);
  7177. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  7178. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  7179. this.alpha = alpha;
  7180. this.beta = beta;
  7181. this.radius = radius;
  7182. this.target = target;
  7183. this.inertialAlphaOffset = 0;
  7184. this.inertialBetaOffset = 0;
  7185. this.inertialRadiusOffset = 0;
  7186. this.lowerAlphaLimit = null;
  7187. this.upperAlphaLimit = null;
  7188. this.lowerBetaLimit = 0.01;
  7189. this.upperBetaLimit = Math.PI;
  7190. this.lowerRadiusLimit = null;
  7191. this.upperRadiusLimit = null;
  7192. this.angularSensibility = 1000.0;
  7193. this.wheelPrecision = 3.0;
  7194. this.keysUp = [38];
  7195. this.keysDown = [40];
  7196. this.keysLeft = [37];
  7197. this.keysRight = [39];
  7198. this.zoomOnFactor = 1;
  7199. this.targetScreenOffset = BABYLON.Vector2.Zero();
  7200. this._keys = [];
  7201. this._viewMatrix = new BABYLON.Matrix();
  7202. this.checkCollisions = false;
  7203. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  7204. this._collider = new BABYLON.Collider();
  7205. this._previousPosition = BABYLON.Vector3.Zero();
  7206. this._collisionVelocity = BABYLON.Vector3.Zero();
  7207. this._newPosition = BABYLON.Vector3.Zero();
  7208. // Pinch
  7209. // value for pinch step scaling
  7210. // set to 20 by default
  7211. this.pinchPrecision = 20;
  7212. this.getViewMatrix();
  7213. }
  7214. ArcRotateCamera.prototype._getTargetPosition = function () {
  7215. return this.target.position || this.target;
  7216. };
  7217. // Cache
  7218. ArcRotateCamera.prototype._initCache = function () {
  7219. _super.prototype._initCache.call(this);
  7220. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7221. this._cache.alpha = undefined;
  7222. this._cache.beta = undefined;
  7223. this._cache.radius = undefined;
  7224. this._cache.targetScreenOffset = undefined;
  7225. };
  7226. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  7227. if (!ignoreParentClass) {
  7228. _super.prototype._updateCache.call(this);
  7229. }
  7230. this._cache.target.copyFrom(this._getTargetPosition());
  7231. this._cache.alpha = this.alpha;
  7232. this._cache.beta = this.beta;
  7233. this._cache.radius = this.radius;
  7234. this._cache.targetScreenOffset = this.targetScreenOffset.clone();
  7235. };
  7236. // Synchronized
  7237. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  7238. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  7239. return false;
  7240. 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);
  7241. };
  7242. // Methods
  7243. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault) {
  7244. var _this = this;
  7245. var previousPosition;
  7246. var pointerId;
  7247. // to know if pinch started
  7248. var pinchStarted = false;
  7249. // two pinch point on X
  7250. // that will use for find if user action is pinch open or pinch close
  7251. var pinchPointX1, pinchPointX2;
  7252. if (this._attachedElement) {
  7253. return;
  7254. }
  7255. this._attachedElement = element;
  7256. var engine = this.getEngine();
  7257. if (this._onPointerDown === undefined) {
  7258. this._onPointerDown = function (evt) {
  7259. if (pointerId) {
  7260. return;
  7261. }
  7262. pointerId = evt.pointerId;
  7263. previousPosition = {
  7264. x: evt.clientX,
  7265. y: evt.clientY
  7266. };
  7267. if (!noPreventDefault) {
  7268. evt.preventDefault();
  7269. }
  7270. };
  7271. this._onPointerUp = function (evt) {
  7272. previousPosition = null;
  7273. pointerId = null;
  7274. if (!noPreventDefault) {
  7275. evt.preventDefault();
  7276. }
  7277. };
  7278. this._onPointerMove = function (evt) {
  7279. if (!previousPosition) {
  7280. return;
  7281. }
  7282. if (pointerId !== evt.pointerId) {
  7283. return;
  7284. }
  7285. // return pinch is started
  7286. if (pinchStarted) {
  7287. return;
  7288. }
  7289. var offsetX = evt.clientX - previousPosition.x;
  7290. var offsetY = evt.clientY - previousPosition.y;
  7291. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  7292. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  7293. previousPosition = {
  7294. x: evt.clientX,
  7295. y: evt.clientY
  7296. };
  7297. if (!noPreventDefault) {
  7298. evt.preventDefault();
  7299. }
  7300. };
  7301. this._onMouseMove = function (evt) {
  7302. if (!engine.isPointerLock) {
  7303. return;
  7304. }
  7305. // return pinch is started
  7306. if (pinchStarted) {
  7307. return;
  7308. }
  7309. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  7310. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  7311. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  7312. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  7313. if (!noPreventDefault) {
  7314. evt.preventDefault();
  7315. }
  7316. };
  7317. this._wheel = function (event) {
  7318. var delta = 0;
  7319. if (event.wheelDelta) {
  7320. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  7321. }
  7322. else if (event.detail) {
  7323. delta = -event.detail / _this.wheelPrecision;
  7324. }
  7325. if (delta)
  7326. _this.inertialRadiusOffset += delta;
  7327. if (event.preventDefault) {
  7328. if (!noPreventDefault) {
  7329. event.preventDefault();
  7330. }
  7331. }
  7332. };
  7333. this._onKeyDown = function (evt) {
  7334. 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) {
  7335. var index = _this._keys.indexOf(evt.keyCode);
  7336. if (index === -1) {
  7337. _this._keys.push(evt.keyCode);
  7338. }
  7339. if (evt.preventDefault) {
  7340. if (!noPreventDefault) {
  7341. evt.preventDefault();
  7342. }
  7343. }
  7344. }
  7345. };
  7346. this._onKeyUp = function (evt) {
  7347. 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) {
  7348. var index = _this._keys.indexOf(evt.keyCode);
  7349. if (index >= 0) {
  7350. _this._keys.splice(index, 1);
  7351. }
  7352. if (evt.preventDefault) {
  7353. if (!noPreventDefault) {
  7354. evt.preventDefault();
  7355. }
  7356. }
  7357. }
  7358. };
  7359. this._onLostFocus = function () {
  7360. _this._keys = [];
  7361. pointerId = null;
  7362. };
  7363. this._onGestureStart = function (e) {
  7364. if (window.MSGesture === undefined) {
  7365. return;
  7366. }
  7367. if (!_this._MSGestureHandler) {
  7368. _this._MSGestureHandler = new MSGesture();
  7369. _this._MSGestureHandler.target = element;
  7370. }
  7371. _this._MSGestureHandler.addPointer(e.pointerId);
  7372. };
  7373. this._onGesture = function (e) {
  7374. _this.radius *= e.scale;
  7375. if (e.preventDefault) {
  7376. if (!noPreventDefault) {
  7377. e.stopPropagation();
  7378. e.preventDefault();
  7379. }
  7380. }
  7381. };
  7382. this._reset = function () {
  7383. _this._keys = [];
  7384. _this.inertialAlphaOffset = 0;
  7385. _this.inertialBetaOffset = 0;
  7386. _this.inertialRadiusOffset = 0;
  7387. previousPosition = null;
  7388. pointerId = null;
  7389. };
  7390. this._touchStart = function (event) {
  7391. if (event.touches.length === 2) {
  7392. //-- start pinch if two fingers on the screen
  7393. pinchStarted = true;
  7394. _this._pinchStart(event);
  7395. }
  7396. };
  7397. this._touchMove = function (event) {
  7398. if (pinchStarted) {
  7399. //-- make scaling
  7400. _this._pinchMove(event);
  7401. }
  7402. };
  7403. this._touchEnd = function (event) {
  7404. if (pinchStarted) {
  7405. //-- end of pinch
  7406. _this._pinchEnd(event);
  7407. }
  7408. };
  7409. this._pinchStart = function (event) {
  7410. // save origin touch point
  7411. pinchPointX1 = event.touches[0].clientX;
  7412. pinchPointX2 = event.touches[1].clientX;
  7413. // block the camera
  7414. // if not it rotate around target during pinch
  7415. pinchStarted = true;
  7416. };
  7417. this._pinchMove = function (event) {
  7418. // variable for new camera's radius
  7419. var delta = 0;
  7420. // variables to know if pinch open or pinch close
  7421. var direction = 1;
  7422. var distanceXOrigine, distanceXNow;
  7423. if (event.touches.length !== 2)
  7424. return;
  7425. // calculate absolute distances of the two fingers
  7426. distanceXOrigine = Math.abs(pinchPointX1 - pinchPointX2);
  7427. distanceXNow = Math.abs(event.touches[0].clientX - event.touches[1].clientX);
  7428. // if distanceXNow < distanceXOrigine -> pinch close so direction = -1
  7429. if (distanceXNow < distanceXOrigine) {
  7430. direction = -1;
  7431. }
  7432. // calculate new radius
  7433. delta = (_this.pinchPrecision / (_this.wheelPrecision * 40)) * direction;
  7434. // set new radius
  7435. _this.inertialRadiusOffset -= delta;
  7436. // save origin touch point
  7437. pinchPointX1 = event.touches[0].clientX;
  7438. pinchPointX2 = event.touches[1].clientX;
  7439. };
  7440. this._pinchEnd = function (event) {
  7441. // cancel pinch and deblock camera rotation
  7442. pinchStarted = false;
  7443. };
  7444. }
  7445. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  7446. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  7447. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  7448. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  7449. element.addEventListener("mousemove", this._onMouseMove, false);
  7450. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  7451. element.addEventListener("MSGestureChange", this._onGesture, false);
  7452. element.addEventListener('mousewheel', this._wheel, false);
  7453. element.addEventListener('DOMMouseScroll', this._wheel, false);
  7454. // pinch
  7455. element.addEventListener('touchstart', this._touchStart, false);
  7456. element.addEventListener('touchmove', this._touchMove, false);
  7457. element.addEventListener('touchend', this._touchEnd, false);
  7458. BABYLON.Tools.RegisterTopRootEvents([
  7459. { name: "keydown", handler: this._onKeyDown },
  7460. { name: "keyup", handler: this._onKeyUp },
  7461. { name: "blur", handler: this._onLostFocus }
  7462. ]);
  7463. };
  7464. ArcRotateCamera.prototype.detachControl = function (element) {
  7465. if (this._attachedElement != element) {
  7466. return;
  7467. }
  7468. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  7469. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  7470. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  7471. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  7472. element.removeEventListener("mousemove", this._onMouseMove);
  7473. element.removeEventListener("MSPointerDown", this._onGestureStart);
  7474. element.removeEventListener("MSGestureChange", this._onGesture);
  7475. element.removeEventListener('mousewheel', this._wheel);
  7476. element.removeEventListener('DOMMouseScroll', this._wheel);
  7477. // pinch
  7478. element.removeEventListener('touchstart', this._touchStart);
  7479. element.removeEventListener('touchmove', this._touchMove);
  7480. element.removeEventListener('touchend', this._touchEnd);
  7481. BABYLON.Tools.UnregisterTopRootEvents([
  7482. { name: "keydown", handler: this._onKeyDown },
  7483. { name: "keyup", handler: this._onKeyUp },
  7484. { name: "blur", handler: this._onLostFocus }
  7485. ]);
  7486. this._MSGestureHandler = null;
  7487. this._attachedElement = null;
  7488. if (this._reset) {
  7489. this._reset();
  7490. }
  7491. };
  7492. ArcRotateCamera.prototype._update = function () {
  7493. for (var index = 0; index < this._keys.length; index++) {
  7494. var keyCode = this._keys[index];
  7495. if (this.keysLeft.indexOf(keyCode) !== -1) {
  7496. this.inertialAlphaOffset -= 0.01;
  7497. }
  7498. else if (this.keysUp.indexOf(keyCode) !== -1) {
  7499. this.inertialBetaOffset -= 0.01;
  7500. }
  7501. else if (this.keysRight.indexOf(keyCode) !== -1) {
  7502. this.inertialAlphaOffset += 0.01;
  7503. }
  7504. else if (this.keysDown.indexOf(keyCode) !== -1) {
  7505. this.inertialBetaOffset += 0.01;
  7506. }
  7507. }
  7508. // Inertia
  7509. if (this.inertialAlphaOffset != 0 || this.inertialBetaOffset != 0 || this.inertialRadiusOffset != 0) {
  7510. this.alpha += this.inertialAlphaOffset;
  7511. this.beta += this.inertialBetaOffset;
  7512. this.radius -= this.inertialRadiusOffset;
  7513. this.inertialAlphaOffset *= this.inertia;
  7514. this.inertialBetaOffset *= this.inertia;
  7515. this.inertialRadiusOffset *= this.inertia;
  7516. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Engine.Epsilon)
  7517. this.inertialAlphaOffset = 0;
  7518. if (Math.abs(this.inertialBetaOffset) < BABYLON.Engine.Epsilon)
  7519. this.inertialBetaOffset = 0;
  7520. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Engine.Epsilon)
  7521. this.inertialRadiusOffset = 0;
  7522. }
  7523. // Limits
  7524. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  7525. this.alpha = this.lowerAlphaLimit;
  7526. }
  7527. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  7528. this.alpha = this.upperAlphaLimit;
  7529. }
  7530. if (this.lowerBetaLimit && this.beta < this.lowerBetaLimit) {
  7531. this.beta = this.lowerBetaLimit;
  7532. }
  7533. if (this.upperBetaLimit && this.beta > this.upperBetaLimit) {
  7534. this.beta = this.upperBetaLimit;
  7535. }
  7536. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  7537. this.radius = this.lowerRadiusLimit;
  7538. }
  7539. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  7540. this.radius = this.upperRadiusLimit;
  7541. }
  7542. };
  7543. ArcRotateCamera.prototype.setPosition = function (position) {
  7544. var radiusv3 = position.subtract(this._getTargetPosition());
  7545. this.radius = radiusv3.length();
  7546. // Alpha
  7547. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  7548. if (radiusv3.z < 0) {
  7549. this.alpha = 2 * Math.PI - this.alpha;
  7550. }
  7551. // Beta
  7552. this.beta = Math.acos(radiusv3.y / this.radius);
  7553. };
  7554. ArcRotateCamera.prototype._getViewMatrix = function () {
  7555. // Compute
  7556. var cosa = Math.cos(this.alpha);
  7557. var sina = Math.sin(this.alpha);
  7558. var cosb = Math.cos(this.beta);
  7559. var sinb = Math.sin(this.beta);
  7560. var target = this._getTargetPosition();
  7561. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this.position);
  7562. if (this.checkCollisions) {
  7563. this._collider.radius = this.collisionRadius;
  7564. this.position.subtractToRef(this._previousPosition, this._collisionVelocity);
  7565. this.getScene()._getNewPosition(this._previousPosition, this._collisionVelocity, this._collider, 3, this._newPosition);
  7566. if (!this._newPosition.equalsWithEpsilon(this.position)) {
  7567. this.position.copyFrom(this._previousPosition);
  7568. this.alpha = this._previousAlpha;
  7569. this.beta = this._previousBeta;
  7570. this.radius = this._previousRadius;
  7571. if (this.onCollide) {
  7572. this.onCollide(this._collider.collidedMesh);
  7573. }
  7574. }
  7575. }
  7576. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._viewMatrix);
  7577. this._previousAlpha = this.alpha;
  7578. this._previousBeta = this.beta;
  7579. this._previousRadius = this.radius;
  7580. this._previousPosition.copyFrom(this.position);
  7581. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  7582. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  7583. return this._viewMatrix;
  7584. };
  7585. ArcRotateCamera.prototype.zoomOn = function (meshes) {
  7586. meshes = meshes || this.getScene().meshes;
  7587. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  7588. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  7589. this.radius = distance * this.zoomOnFactor;
  7590. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance });
  7591. };
  7592. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance) {
  7593. var meshesOrMinMaxVector;
  7594. var distance;
  7595. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  7596. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  7597. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  7598. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  7599. }
  7600. else {
  7601. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  7602. distance = meshesOrMinMaxVectorAndDistance.distance;
  7603. }
  7604. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  7605. this.maxZ = distance * 2;
  7606. };
  7607. return ArcRotateCamera;
  7608. })(BABYLON.Camera);
  7609. BABYLON.ArcRotateCamera = ArcRotateCamera;
  7610. })(BABYLON || (BABYLON = {}));
  7611. //# sourceMappingURL=babylon.arcRotateCamera.js.mapvar BABYLON;
  7612. (function (BABYLON) {
  7613. /**
  7614. * Represents a scene to be rendered by the engine.
  7615. * @see http://doc.babylonjs.com/page.php?p=21911
  7616. */
  7617. var Scene = (function () {
  7618. /**
  7619. * @constructor
  7620. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  7621. */
  7622. function Scene(engine) {
  7623. // Members
  7624. this.autoClear = true;
  7625. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  7626. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  7627. this.forceWireframe = false;
  7628. this.forcePointsCloud = false;
  7629. this.forceShowBoundingBoxes = false;
  7630. this.animationsEnabled = true;
  7631. 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
  7632. // Fog
  7633. /**
  7634. * is fog enabled on this scene.
  7635. * @type {boolean}
  7636. */
  7637. this.fogEnabled = true;
  7638. this.fogMode = Scene.FOGMODE_NONE;
  7639. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  7640. this.fogDensity = 0.1;
  7641. this.fogStart = 0;
  7642. this.fogEnd = 1000.0;
  7643. // Lights
  7644. /**
  7645. * is shadow enabled on this scene.
  7646. * @type {boolean}
  7647. */
  7648. this.shadowsEnabled = true;
  7649. /**
  7650. * is light enabled on this scene.
  7651. * @type {boolean}
  7652. */
  7653. this.lightsEnabled = true;
  7654. /**
  7655. * All of the lights added to this scene.
  7656. * @see BABYLON.Light
  7657. * @type {BABYLON.Light[]}
  7658. */
  7659. this.lights = new Array();
  7660. // Cameras
  7661. /**
  7662. * All of the cameras added to this scene.
  7663. * @see BABYLON.Camera
  7664. * @type {BABYLON.Camera[]}
  7665. */
  7666. this.cameras = new Array();
  7667. this.activeCameras = new Array();
  7668. // Meshes
  7669. /**
  7670. * All of the (abstract) meshes added to this scene.
  7671. * @see BABYLON.AbstractMesh
  7672. * @type {BABYLON.AbstractMesh[]}
  7673. */
  7674. this.meshes = new Array();
  7675. // Geometries
  7676. this._geometries = new Array();
  7677. this.materials = new Array();
  7678. this.multiMaterials = new Array();
  7679. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  7680. // Textures
  7681. this.texturesEnabled = true;
  7682. this.textures = new Array();
  7683. // Particles
  7684. this.particlesEnabled = true;
  7685. this.particleSystems = new Array();
  7686. // Sprites
  7687. this.spritesEnabled = true;
  7688. this.spriteManagers = new Array();
  7689. // Layers
  7690. this.layers = new Array();
  7691. // Skeletons
  7692. this.skeletonsEnabled = true;
  7693. this.skeletons = new Array();
  7694. // Lens flares
  7695. this.lensFlaresEnabled = true;
  7696. this.lensFlareSystems = new Array();
  7697. // Collisions
  7698. this.collisionsEnabled = true;
  7699. this.gravity = new BABYLON.Vector3(0, -9.0, 0);
  7700. // Postprocesses
  7701. this.postProcessesEnabled = true;
  7702. // Customs render targets
  7703. this.renderTargetsEnabled = true;
  7704. this.customRenderTargets = new Array();
  7705. // Imported meshes
  7706. this.importedMeshesFiles = new Array();
  7707. this._actionManagers = new Array();
  7708. this._meshesForIntersections = new BABYLON.SmartArray(256);
  7709. // Procedural textures
  7710. this.proceduralTexturesEnabled = true;
  7711. this._proceduralTextures = new Array();
  7712. this.soundTracks = new Array();
  7713. this._totalVertices = 0;
  7714. this._activeVertices = 0;
  7715. this._activeParticles = 0;
  7716. this._lastFrameDuration = 0;
  7717. this._evaluateActiveMeshesDuration = 0;
  7718. this._renderTargetsDuration = 0;
  7719. this._particlesDuration = 0;
  7720. this._renderDuration = 0;
  7721. this._spritesDuration = 0;
  7722. this._animationRatio = 0;
  7723. this._renderId = 0;
  7724. this._executeWhenReadyTimeoutId = -1;
  7725. this._toBeDisposed = new BABYLON.SmartArray(256);
  7726. this._onReadyCallbacks = new Array();
  7727. this._pendingData = []; //ANY
  7728. this._onBeforeRenderCallbacks = new Array();
  7729. this._onAfterRenderCallbacks = new Array();
  7730. this._activeMeshes = new BABYLON.SmartArray(256);
  7731. this._processedMaterials = new BABYLON.SmartArray(256);
  7732. this._renderTargets = new BABYLON.SmartArray(256);
  7733. this._activeParticleSystems = new BABYLON.SmartArray(256);
  7734. this._activeSkeletons = new BABYLON.SmartArray(32);
  7735. this._activeBones = 0;
  7736. this._activeAnimatables = new Array();
  7737. this._transformMatrix = BABYLON.Matrix.Zero();
  7738. this._scaledPosition = BABYLON.Vector3.Zero();
  7739. this._scaledVelocity = BABYLON.Vector3.Zero();
  7740. this._engine = engine;
  7741. engine.scenes.push(this);
  7742. this._renderingManager = new BABYLON.RenderingManager(this);
  7743. this.postProcessManager = new BABYLON.PostProcessManager(this);
  7744. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  7745. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  7746. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  7747. this.attachControl();
  7748. this._debugLayer = new BABYLON.DebugLayer(this);
  7749. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  7750. }
  7751. Object.defineProperty(Scene, "FOGMODE_NONE", {
  7752. get: function () {
  7753. return Scene._FOGMODE_NONE;
  7754. },
  7755. enumerable: true,
  7756. configurable: true
  7757. });
  7758. Object.defineProperty(Scene, "FOGMODE_EXP", {
  7759. get: function () {
  7760. return Scene._FOGMODE_EXP;
  7761. },
  7762. enumerable: true,
  7763. configurable: true
  7764. });
  7765. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  7766. get: function () {
  7767. return Scene._FOGMODE_EXP2;
  7768. },
  7769. enumerable: true,
  7770. configurable: true
  7771. });
  7772. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  7773. get: function () {
  7774. return Scene._FOGMODE_LINEAR;
  7775. },
  7776. enumerable: true,
  7777. configurable: true
  7778. });
  7779. Object.defineProperty(Scene.prototype, "debugLayer", {
  7780. // Properties
  7781. get: function () {
  7782. return this._debugLayer;
  7783. },
  7784. enumerable: true,
  7785. configurable: true
  7786. });
  7787. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  7788. /**
  7789. * The mesh that is currently under the pointer.
  7790. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  7791. */
  7792. get: function () {
  7793. return this._meshUnderPointer;
  7794. },
  7795. enumerable: true,
  7796. configurable: true
  7797. });
  7798. Object.defineProperty(Scene.prototype, "pointerX", {
  7799. /**
  7800. * Current on-screen X position of the pointer
  7801. * @return {number} X position of the pointer
  7802. */
  7803. get: function () {
  7804. return this._pointerX;
  7805. },
  7806. enumerable: true,
  7807. configurable: true
  7808. });
  7809. Object.defineProperty(Scene.prototype, "pointerY", {
  7810. /**
  7811. * Current on-screen Y position of the pointer
  7812. * @return {number} Y position of the pointer
  7813. */
  7814. get: function () {
  7815. return this._pointerY;
  7816. },
  7817. enumerable: true,
  7818. configurable: true
  7819. });
  7820. Scene.prototype.getCachedMaterial = function () {
  7821. return this._cachedMaterial;
  7822. };
  7823. Scene.prototype.getBoundingBoxRenderer = function () {
  7824. return this._boundingBoxRenderer;
  7825. };
  7826. Scene.prototype.getOutlineRenderer = function () {
  7827. return this._outlineRenderer;
  7828. };
  7829. Scene.prototype.getEngine = function () {
  7830. return this._engine;
  7831. };
  7832. Scene.prototype.getTotalVertices = function () {
  7833. return this._totalVertices;
  7834. };
  7835. Scene.prototype.getActiveVertices = function () {
  7836. return this._activeVertices;
  7837. };
  7838. Scene.prototype.getActiveParticles = function () {
  7839. return this._activeParticles;
  7840. };
  7841. Scene.prototype.getActiveBones = function () {
  7842. return this._activeBones;
  7843. };
  7844. // Stats
  7845. Scene.prototype.getLastFrameDuration = function () {
  7846. return this._lastFrameDuration;
  7847. };
  7848. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  7849. return this._evaluateActiveMeshesDuration;
  7850. };
  7851. Scene.prototype.getActiveMeshes = function () {
  7852. return this._activeMeshes;
  7853. };
  7854. Scene.prototype.getRenderTargetsDuration = function () {
  7855. return this._renderTargetsDuration;
  7856. };
  7857. Scene.prototype.getRenderDuration = function () {
  7858. return this._renderDuration;
  7859. };
  7860. Scene.prototype.getParticlesDuration = function () {
  7861. return this._particlesDuration;
  7862. };
  7863. Scene.prototype.getSpritesDuration = function () {
  7864. return this._spritesDuration;
  7865. };
  7866. Scene.prototype.getAnimationRatio = function () {
  7867. return this._animationRatio;
  7868. };
  7869. Scene.prototype.getRenderId = function () {
  7870. return this._renderId;
  7871. };
  7872. Scene.prototype.incrementRenderId = function () {
  7873. this._renderId++;
  7874. };
  7875. Scene.prototype._updatePointerPosition = function (evt) {
  7876. var canvasRect = this._engine.getRenderingCanvasClientRect();
  7877. this._pointerX = evt.clientX - canvasRect.left;
  7878. this._pointerY = evt.clientY - canvasRect.top;
  7879. if (this.cameraToUseForPointers) {
  7880. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  7881. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  7882. }
  7883. };
  7884. // Pointers handling
  7885. Scene.prototype.attachControl = function () {
  7886. var _this = this;
  7887. this._onPointerMove = function (evt) {
  7888. var canvas = _this._engine.getRenderingCanvas();
  7889. _this._updatePointerPosition(evt);
  7890. 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);
  7891. if (pickResult.hit) {
  7892. _this._meshUnderPointer = pickResult.pickedMesh;
  7893. _this.setPointerOverMesh(pickResult.pickedMesh);
  7894. canvas.style.cursor = "pointer";
  7895. }
  7896. else {
  7897. _this.setPointerOverMesh(null);
  7898. canvas.style.cursor = "";
  7899. _this._meshUnderPointer = null;
  7900. }
  7901. };
  7902. this._onPointerDown = function (evt) {
  7903. var predicate = null;
  7904. if (!_this.onPointerDown) {
  7905. predicate = function (mesh) {
  7906. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPickTriggers;
  7907. };
  7908. }
  7909. _this._updatePointerPosition(evt);
  7910. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  7911. if (pickResult.hit) {
  7912. if (pickResult.pickedMesh.actionManager) {
  7913. switch (evt.button) {
  7914. case 0:
  7915. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  7916. break;
  7917. case 1:
  7918. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  7919. break;
  7920. case 2:
  7921. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  7922. break;
  7923. }
  7924. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  7925. }
  7926. }
  7927. if (_this.onPointerDown) {
  7928. _this.onPointerDown(evt, pickResult);
  7929. }
  7930. };
  7931. this._onKeyDown = function (evt) {
  7932. if (_this.actionManager) {
  7933. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  7934. }
  7935. };
  7936. this._onKeyUp = function (evt) {
  7937. if (_this.actionManager) {
  7938. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  7939. }
  7940. };
  7941. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  7942. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  7943. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  7944. BABYLON.Tools.RegisterTopRootEvents([
  7945. { name: "keydown", handler: this._onKeyDown },
  7946. { name: "keyup", handler: this._onKeyUp }
  7947. ]);
  7948. };
  7949. Scene.prototype.detachControl = function () {
  7950. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  7951. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  7952. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  7953. BABYLON.Tools.UnregisterTopRootEvents([
  7954. { name: "keydown", handler: this._onKeyDown },
  7955. { name: "keyup", handler: this._onKeyUp }
  7956. ]);
  7957. };
  7958. // Ready
  7959. Scene.prototype.isReady = function () {
  7960. if (this._pendingData.length > 0) {
  7961. return false;
  7962. }
  7963. for (var index = 0; index < this._geometries.length; index++) {
  7964. var geometry = this._geometries[index];
  7965. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  7966. return false;
  7967. }
  7968. }
  7969. for (index = 0; index < this.meshes.length; index++) {
  7970. var mesh = this.meshes[index];
  7971. if (!mesh.isReady()) {
  7972. return false;
  7973. }
  7974. var mat = mesh.material;
  7975. if (mat) {
  7976. if (!mat.isReady(mesh)) {
  7977. return false;
  7978. }
  7979. }
  7980. }
  7981. return true;
  7982. };
  7983. Scene.prototype.resetCachedMaterial = function () {
  7984. this._cachedMaterial = null;
  7985. };
  7986. Scene.prototype.registerBeforeRender = function (func) {
  7987. this._onBeforeRenderCallbacks.push(func);
  7988. };
  7989. Scene.prototype.unregisterBeforeRender = function (func) {
  7990. var index = this._onBeforeRenderCallbacks.indexOf(func);
  7991. if (index > -1) {
  7992. this._onBeforeRenderCallbacks.splice(index, 1);
  7993. }
  7994. };
  7995. Scene.prototype.registerAfterRender = function (func) {
  7996. this._onAfterRenderCallbacks.push(func);
  7997. };
  7998. Scene.prototype.unregisterAfterRender = function (func) {
  7999. var index = this._onAfterRenderCallbacks.indexOf(func);
  8000. if (index > -1) {
  8001. this._onAfterRenderCallbacks.splice(index, 1);
  8002. }
  8003. };
  8004. Scene.prototype._addPendingData = function (data) {
  8005. this._pendingData.push(data);
  8006. };
  8007. Scene.prototype._removePendingData = function (data) {
  8008. var index = this._pendingData.indexOf(data);
  8009. if (index !== -1) {
  8010. this._pendingData.splice(index, 1);
  8011. }
  8012. };
  8013. Scene.prototype.getWaitingItemsCount = function () {
  8014. return this._pendingData.length;
  8015. };
  8016. /**
  8017. * Registers a function to be executed when the scene is ready.
  8018. * @param {Function} func - the function to be executed.
  8019. */
  8020. Scene.prototype.executeWhenReady = function (func) {
  8021. var _this = this;
  8022. this._onReadyCallbacks.push(func);
  8023. if (this._executeWhenReadyTimeoutId !== -1) {
  8024. return;
  8025. }
  8026. this._executeWhenReadyTimeoutId = setTimeout(function () {
  8027. _this._checkIsReady();
  8028. }, 150);
  8029. };
  8030. Scene.prototype._checkIsReady = function () {
  8031. var _this = this;
  8032. if (this.isReady()) {
  8033. this._onReadyCallbacks.forEach(function (func) {
  8034. func();
  8035. });
  8036. this._onReadyCallbacks = [];
  8037. this._executeWhenReadyTimeoutId = -1;
  8038. return;
  8039. }
  8040. this._executeWhenReadyTimeoutId = setTimeout(function () {
  8041. _this._checkIsReady();
  8042. }, 150);
  8043. };
  8044. // Animations
  8045. /**
  8046. * Will start the animation sequence of a given target
  8047. * @param target - the target
  8048. * @param {number} from - from which frame should animation start
  8049. * @param {number} to - till which frame should animation run.
  8050. * @param {boolean} [loop] - should the animation loop
  8051. * @param {number} [speedRatio] - the speed in which to run the animation
  8052. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  8053. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  8054. * @return {BABYLON.Animatable} the animatable object created for this animation
  8055. * @see BABYLON.Animatable
  8056. * @see http://doc.babylonjs.com/page.php?p=22081
  8057. */
  8058. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  8059. if (speedRatio === undefined) {
  8060. speedRatio = 1.0;
  8061. }
  8062. this.stopAnimation(target);
  8063. if (!animatable) {
  8064. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  8065. }
  8066. // Local animations
  8067. if (target.animations) {
  8068. animatable.appendAnimations(target, target.animations);
  8069. }
  8070. // Children animations
  8071. if (target.getAnimatables) {
  8072. var animatables = target.getAnimatables();
  8073. for (var index = 0; index < animatables.length; index++) {
  8074. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  8075. }
  8076. }
  8077. return animatable;
  8078. };
  8079. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  8080. if (speedRatio === undefined) {
  8081. speedRatio = 1.0;
  8082. }
  8083. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  8084. return animatable;
  8085. };
  8086. Scene.prototype.getAnimatableByTarget = function (target) {
  8087. for (var index = 0; index < this._activeAnimatables.length; index++) {
  8088. if (this._activeAnimatables[index].target === target) {
  8089. return this._activeAnimatables[index];
  8090. }
  8091. }
  8092. return null;
  8093. };
  8094. /**
  8095. * Will stop the animation of the given target
  8096. * @param target - the target
  8097. * @see beginAnimation
  8098. */
  8099. Scene.prototype.stopAnimation = function (target) {
  8100. var animatable = this.getAnimatableByTarget(target);
  8101. if (animatable) {
  8102. animatable.stop();
  8103. }
  8104. };
  8105. Scene.prototype._animate = function () {
  8106. if (!this.animationsEnabled) {
  8107. return;
  8108. }
  8109. if (!this._animationStartDate) {
  8110. this._animationStartDate = BABYLON.Tools.Now;
  8111. }
  8112. // Getting time
  8113. var now = BABYLON.Tools.Now;
  8114. var delay = now - this._animationStartDate;
  8115. for (var index = 0; index < this._activeAnimatables.length; index++) {
  8116. if (!this._activeAnimatables[index]._animate(delay)) {
  8117. this._activeAnimatables.splice(index, 1);
  8118. index--;
  8119. }
  8120. }
  8121. };
  8122. // Matrix
  8123. Scene.prototype.getViewMatrix = function () {
  8124. return this._viewMatrix;
  8125. };
  8126. Scene.prototype.getProjectionMatrix = function () {
  8127. return this._projectionMatrix;
  8128. };
  8129. Scene.prototype.getTransformMatrix = function () {
  8130. return this._transformMatrix;
  8131. };
  8132. Scene.prototype.setTransformMatrix = function (view, projection) {
  8133. this._viewMatrix = view;
  8134. this._projectionMatrix = projection;
  8135. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  8136. };
  8137. // Methods
  8138. /**
  8139. * sets the active camera of the scene using its ID
  8140. * @param {string} id - the camera's ID
  8141. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  8142. * @see activeCamera
  8143. */
  8144. Scene.prototype.setActiveCameraByID = function (id) {
  8145. var camera = this.getCameraByID(id);
  8146. if (camera) {
  8147. this.activeCamera = camera;
  8148. return camera;
  8149. }
  8150. return null;
  8151. };
  8152. /**
  8153. * sets the active camera of the scene using its name
  8154. * @param {string} name - the camera's name
  8155. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  8156. * @see activeCamera
  8157. */
  8158. Scene.prototype.setActiveCameraByName = function (name) {
  8159. var camera = this.getCameraByName(name);
  8160. if (camera) {
  8161. this.activeCamera = camera;
  8162. return camera;
  8163. }
  8164. return null;
  8165. };
  8166. /**
  8167. * get a material using its id
  8168. * @param {string} the material's ID
  8169. * @return {BABYLON.Material|null} the material or null if none found.
  8170. */
  8171. Scene.prototype.getMaterialByID = function (id) {
  8172. for (var index = 0; index < this.materials.length; index++) {
  8173. if (this.materials[index].id === id) {
  8174. return this.materials[index];
  8175. }
  8176. }
  8177. return null;
  8178. };
  8179. /**
  8180. * get a material using its name
  8181. * @param {string} the material's name
  8182. * @return {BABYLON.Material|null} the material or null if none found.
  8183. */
  8184. Scene.prototype.getMaterialByName = function (name) {
  8185. for (var index = 0; index < this.materials.length; index++) {
  8186. if (this.materials[index].name === name) {
  8187. return this.materials[index];
  8188. }
  8189. }
  8190. return null;
  8191. };
  8192. Scene.prototype.getCameraByID = function (id) {
  8193. for (var index = 0; index < this.cameras.length; index++) {
  8194. if (this.cameras[index].id === id) {
  8195. return this.cameras[index];
  8196. }
  8197. }
  8198. return null;
  8199. };
  8200. /**
  8201. * get a camera using its name
  8202. * @param {string} the camera's name
  8203. * @return {BABYLON.Camera|null} the camera or null if none found.
  8204. */
  8205. Scene.prototype.getCameraByName = function (name) {
  8206. for (var index = 0; index < this.cameras.length; index++) {
  8207. if (this.cameras[index].name === name) {
  8208. return this.cameras[index];
  8209. }
  8210. }
  8211. return null;
  8212. };
  8213. /**
  8214. * get a light node using its name
  8215. * @param {string} the light's name
  8216. * @return {BABYLON.Light|null} the light or null if none found.
  8217. */
  8218. Scene.prototype.getLightByName = function (name) {
  8219. for (var index = 0; index < this.lights.length; index++) {
  8220. if (this.lights[index].name === name) {
  8221. return this.lights[index];
  8222. }
  8223. }
  8224. return null;
  8225. };
  8226. /**
  8227. * get a light node using its ID
  8228. * @param {string} the light's id
  8229. * @return {BABYLON.Light|null} the light or null if none found.
  8230. */
  8231. Scene.prototype.getLightByID = function (id) {
  8232. for (var index = 0; index < this.lights.length; index++) {
  8233. if (this.lights[index].id === id) {
  8234. return this.lights[index];
  8235. }
  8236. }
  8237. return null;
  8238. };
  8239. /**
  8240. * get a geometry using its ID
  8241. * @param {string} the geometry's id
  8242. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  8243. */
  8244. Scene.prototype.getGeometryByID = function (id) {
  8245. for (var index = 0; index < this._geometries.length; index++) {
  8246. if (this._geometries[index].id === id) {
  8247. return this._geometries[index];
  8248. }
  8249. }
  8250. return null;
  8251. };
  8252. /**
  8253. * add a new geometry to this scene.
  8254. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  8255. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  8256. * @return {boolean} was the geometry added or not
  8257. */
  8258. Scene.prototype.pushGeometry = function (geometry, force) {
  8259. if (!force && this.getGeometryByID(geometry.id)) {
  8260. return false;
  8261. }
  8262. this._geometries.push(geometry);
  8263. return true;
  8264. };
  8265. Scene.prototype.getGeometries = function () {
  8266. return this._geometries;
  8267. };
  8268. /**
  8269. * Get a the first added mesh found of a given ID
  8270. * @param {string} id - the id to search for
  8271. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  8272. */
  8273. Scene.prototype.getMeshByID = function (id) {
  8274. for (var index = 0; index < this.meshes.length; index++) {
  8275. if (this.meshes[index].id === id) {
  8276. return this.meshes[index];
  8277. }
  8278. }
  8279. return null;
  8280. };
  8281. /**
  8282. * Get a the last added mesh found of a given ID
  8283. * @param {string} id - the id to search for
  8284. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  8285. */
  8286. Scene.prototype.getLastMeshByID = function (id) {
  8287. for (var index = this.meshes.length - 1; index >= 0; index--) {
  8288. if (this.meshes[index].id === id) {
  8289. return this.meshes[index];
  8290. }
  8291. }
  8292. return null;
  8293. };
  8294. /**
  8295. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  8296. * @param {string} id - the id to search for
  8297. * @return {BABYLON.Node|null} the node found or null if not found at all.
  8298. */
  8299. Scene.prototype.getLastEntryByID = function (id) {
  8300. for (var index = this.meshes.length - 1; index >= 0; index--) {
  8301. if (this.meshes[index].id === id) {
  8302. return this.meshes[index];
  8303. }
  8304. }
  8305. for (index = this.cameras.length - 1; index >= 0; index--) {
  8306. if (this.cameras[index].id === id) {
  8307. return this.cameras[index];
  8308. }
  8309. }
  8310. for (index = this.lights.length - 1; index >= 0; index--) {
  8311. if (this.lights[index].id === id) {
  8312. return this.lights[index];
  8313. }
  8314. }
  8315. return null;
  8316. };
  8317. Scene.prototype.getNodeByName = function (name) {
  8318. var mesh = this.getMeshByName(name);
  8319. if (mesh) {
  8320. return mesh;
  8321. }
  8322. var light = this.getLightByName(name);
  8323. if (light) {
  8324. return light;
  8325. }
  8326. return this.getCameraByName(name);
  8327. };
  8328. Scene.prototype.getMeshByName = function (name) {
  8329. for (var index = 0; index < this.meshes.length; index++) {
  8330. if (this.meshes[index].name === name) {
  8331. return this.meshes[index];
  8332. }
  8333. }
  8334. return null;
  8335. };
  8336. Scene.prototype.getSoundByName = function (name) {
  8337. for (var index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  8338. if (this.mainSoundTrack.soundCollection[index].name === name) {
  8339. return this.mainSoundTrack.soundCollection[index];
  8340. }
  8341. }
  8342. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  8343. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  8344. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  8345. return this.soundTracks[sdIndex].soundCollection[index];
  8346. }
  8347. }
  8348. }
  8349. return null;
  8350. };
  8351. Scene.prototype.getLastSkeletonByID = function (id) {
  8352. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  8353. if (this.skeletons[index].id === id) {
  8354. return this.skeletons[index];
  8355. }
  8356. }
  8357. return null;
  8358. };
  8359. Scene.prototype.getSkeletonById = function (id) {
  8360. for (var index = 0; index < this.skeletons.length; index++) {
  8361. if (this.skeletons[index].id === id) {
  8362. return this.skeletons[index];
  8363. }
  8364. }
  8365. return null;
  8366. };
  8367. Scene.prototype.getSkeletonByName = function (name) {
  8368. for (var index = 0; index < this.skeletons.length; index++) {
  8369. if (this.skeletons[index].name === name) {
  8370. return this.skeletons[index];
  8371. }
  8372. }
  8373. return null;
  8374. };
  8375. Scene.prototype.isActiveMesh = function (mesh) {
  8376. return (this._activeMeshes.indexOf(mesh) !== -1);
  8377. };
  8378. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  8379. if (mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  8380. var material = subMesh.getMaterial();
  8381. if (mesh.showSubMeshesBoundingBox) {
  8382. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  8383. }
  8384. if (material) {
  8385. // Render targets
  8386. if (material.getRenderTargetTextures) {
  8387. if (this._processedMaterials.indexOf(material) === -1) {
  8388. this._processedMaterials.push(material);
  8389. this._renderTargets.concat(material.getRenderTargetTextures());
  8390. }
  8391. }
  8392. // Dispatch
  8393. this._activeVertices += subMesh.indexCount;
  8394. this._renderingManager.dispatch(subMesh);
  8395. }
  8396. }
  8397. };
  8398. Scene.prototype._evaluateActiveMeshes = function () {
  8399. this.activeCamera._activeMeshes.reset();
  8400. this._activeMeshes.reset();
  8401. this._renderingManager.reset();
  8402. this._processedMaterials.reset();
  8403. this._activeParticleSystems.reset();
  8404. this._activeSkeletons.reset();
  8405. this._boundingBoxRenderer.reset();
  8406. if (!this._frustumPlanes) {
  8407. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  8408. }
  8409. else {
  8410. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  8411. }
  8412. // Meshes
  8413. var meshes;
  8414. var len;
  8415. if (this._selectionOctree) {
  8416. var selection = this._selectionOctree.select(this._frustumPlanes);
  8417. meshes = selection.data;
  8418. len = selection.length;
  8419. }
  8420. else {
  8421. len = this.meshes.length;
  8422. meshes = this.meshes;
  8423. }
  8424. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  8425. var mesh = meshes[meshIndex];
  8426. if (mesh.isBlocked) {
  8427. continue;
  8428. }
  8429. this._totalVertices += mesh.getTotalVertices();
  8430. if (!mesh.isReady()) {
  8431. continue;
  8432. }
  8433. mesh.computeWorldMatrix();
  8434. // Intersections
  8435. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  8436. this._meshesForIntersections.pushNoDuplicate(mesh);
  8437. }
  8438. // Switch to current LOD
  8439. var meshLOD = mesh.getLOD(this.activeCamera);
  8440. if (!meshLOD) {
  8441. continue;
  8442. }
  8443. mesh._preActivate();
  8444. if (mesh.isEnabled() && mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  8445. this._activeMeshes.push(mesh);
  8446. this.activeCamera._activeMeshes.push(mesh);
  8447. mesh._activate(this._renderId);
  8448. this._activeMesh(meshLOD);
  8449. }
  8450. }
  8451. // Particle systems
  8452. var beforeParticlesDate = BABYLON.Tools.Now;
  8453. if (this.particlesEnabled) {
  8454. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  8455. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  8456. var particleSystem = this.particleSystems[particleIndex];
  8457. if (!particleSystem.isStarted()) {
  8458. continue;
  8459. }
  8460. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  8461. this._activeParticleSystems.push(particleSystem);
  8462. particleSystem.animate();
  8463. }
  8464. }
  8465. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  8466. }
  8467. this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  8468. };
  8469. Scene.prototype._activeMesh = function (mesh) {
  8470. if (mesh.skeleton && this.skeletonsEnabled) {
  8471. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  8472. }
  8473. if (mesh.showBoundingBox || this.forceShowBoundingBoxes) {
  8474. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  8475. }
  8476. if (mesh && mesh.subMeshes) {
  8477. // Submeshes Octrees
  8478. var len;
  8479. var subMeshes;
  8480. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  8481. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  8482. len = intersections.length;
  8483. subMeshes = intersections.data;
  8484. }
  8485. else {
  8486. subMeshes = mesh.subMeshes;
  8487. len = subMeshes.length;
  8488. }
  8489. for (var subIndex = 0; subIndex < len; subIndex++) {
  8490. var subMesh = subMeshes[subIndex];
  8491. this._evaluateSubMesh(subMesh, mesh);
  8492. }
  8493. }
  8494. };
  8495. Scene.prototype.updateTransformMatrix = function (force) {
  8496. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  8497. };
  8498. Scene.prototype._renderForCamera = function (camera) {
  8499. var engine = this._engine;
  8500. this.activeCamera = camera;
  8501. if (!this.activeCamera)
  8502. throw new Error("Active camera not set");
  8503. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  8504. // Viewport
  8505. engine.setViewport(this.activeCamera.viewport);
  8506. // Camera
  8507. this._renderId++;
  8508. this.updateTransformMatrix();
  8509. if (this.beforeCameraRender) {
  8510. this.beforeCameraRender(this.activeCamera);
  8511. }
  8512. // Meshes
  8513. var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
  8514. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  8515. this._evaluateActiveMeshes();
  8516. this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
  8517. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  8518. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  8519. var skeleton = this._activeSkeletons.data[skeletonIndex];
  8520. skeleton.prepare();
  8521. }
  8522. // Render targets
  8523. var beforeRenderTargetDate = BABYLON.Tools.Now;
  8524. if (this.renderTargetsEnabled) {
  8525. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  8526. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  8527. var renderTarget = this._renderTargets.data[renderIndex];
  8528. if (renderTarget._shouldRender()) {
  8529. this._renderId++;
  8530. renderTarget.render();
  8531. }
  8532. }
  8533. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  8534. this._renderId++;
  8535. }
  8536. if (this._renderTargets.length > 0) {
  8537. engine.restoreDefaultFramebuffer();
  8538. }
  8539. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  8540. // Prepare Frame
  8541. this.postProcessManager._prepareFrame();
  8542. var beforeRenderDate = BABYLON.Tools.Now;
  8543. // Backgrounds
  8544. if (this.layers.length) {
  8545. engine.setDepthBuffer(false);
  8546. var layerIndex;
  8547. var layer;
  8548. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  8549. layer = this.layers[layerIndex];
  8550. if (layer.isBackground) {
  8551. layer.render();
  8552. }
  8553. }
  8554. engine.setDepthBuffer(true);
  8555. }
  8556. // Render
  8557. BABYLON.Tools.StartPerformanceCounter("Main render");
  8558. this._renderingManager.render(null, null, true, true);
  8559. BABYLON.Tools.EndPerformanceCounter("Main render");
  8560. // Bounding boxes
  8561. this._boundingBoxRenderer.render();
  8562. // Lens flares
  8563. if (this.lensFlaresEnabled) {
  8564. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  8565. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  8566. this.lensFlareSystems[lensFlareSystemIndex].render();
  8567. }
  8568. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  8569. }
  8570. // Foregrounds
  8571. if (this.layers.length) {
  8572. engine.setDepthBuffer(false);
  8573. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  8574. layer = this.layers[layerIndex];
  8575. if (!layer.isBackground) {
  8576. layer.render();
  8577. }
  8578. }
  8579. engine.setDepthBuffer(true);
  8580. }
  8581. this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
  8582. // Finalize frame
  8583. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  8584. // Update camera
  8585. this.activeCamera._updateFromScene();
  8586. // Reset some special arrays
  8587. this._renderTargets.reset();
  8588. if (this.afterCameraRender) {
  8589. this.afterCameraRender(this.activeCamera);
  8590. }
  8591. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  8592. };
  8593. Scene.prototype._processSubCameras = function (camera) {
  8594. if (camera.subCameras.length === 0) {
  8595. this._renderForCamera(camera);
  8596. return;
  8597. }
  8598. for (var index = 0; index < camera.subCameras.length; index++) {
  8599. this._renderForCamera(camera.subCameras[index]);
  8600. }
  8601. this.activeCamera = camera;
  8602. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  8603. // Update camera
  8604. this.activeCamera._updateFromScene();
  8605. };
  8606. Scene.prototype._checkIntersections = function () {
  8607. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  8608. var sourceMesh = this._meshesForIntersections.data[index];
  8609. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  8610. var action = sourceMesh.actionManager.actions[actionIndex];
  8611. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  8612. var parameters = action.getTriggerParameter();
  8613. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  8614. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  8615. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  8616. if (areIntersecting && currentIntersectionInProgress === -1) {
  8617. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  8618. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh));
  8619. sourceMesh._intersectionsInProgress.push(otherMesh);
  8620. }
  8621. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  8622. sourceMesh._intersectionsInProgress.push(otherMesh);
  8623. }
  8624. }
  8625. else if (!areIntersecting && currentIntersectionInProgress > -1 && action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  8626. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh));
  8627. var indexOfOther = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  8628. if (indexOfOther > -1) {
  8629. sourceMesh._intersectionsInProgress.splice(indexOfOther, 1);
  8630. }
  8631. }
  8632. }
  8633. }
  8634. }
  8635. };
  8636. Scene.prototype.render = function () {
  8637. var startDate = BABYLON.Tools.Now;
  8638. this._particlesDuration = 0;
  8639. this._spritesDuration = 0;
  8640. this._activeParticles = 0;
  8641. this._renderDuration = 0;
  8642. this._renderTargetsDuration = 0;
  8643. this._evaluateActiveMeshesDuration = 0;
  8644. this._totalVertices = 0;
  8645. this._activeVertices = 0;
  8646. this._activeBones = 0;
  8647. this.getEngine().resetDrawCalls();
  8648. this._meshesForIntersections.reset();
  8649. this.resetCachedMaterial();
  8650. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  8651. // Actions
  8652. if (this.actionManager) {
  8653. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  8654. }
  8655. // Before render
  8656. if (this.beforeRender) {
  8657. this.beforeRender();
  8658. }
  8659. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  8660. this._onBeforeRenderCallbacks[callbackIndex]();
  8661. }
  8662. // Animations
  8663. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  8664. this._animationRatio = deltaTime * (60.0 / 1000.0);
  8665. this._animate();
  8666. // Physics
  8667. if (this._physicsEngine) {
  8668. BABYLON.Tools.StartPerformanceCounter("Physics");
  8669. this._physicsEngine._runOneStep(deltaTime / 1000.0);
  8670. BABYLON.Tools.EndPerformanceCounter("Physics");
  8671. }
  8672. // Customs render targets
  8673. var beforeRenderTargetDate = BABYLON.Tools.Now;
  8674. var engine = this.getEngine();
  8675. var currentActiveCamera = this.activeCamera;
  8676. if (this.renderTargetsEnabled) {
  8677. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  8678. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  8679. var renderTarget = this.customRenderTargets[customIndex];
  8680. if (renderTarget._shouldRender()) {
  8681. this._renderId++;
  8682. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  8683. if (!this.activeCamera)
  8684. throw new Error("Active camera not set");
  8685. // Viewport
  8686. engine.setViewport(this.activeCamera.viewport);
  8687. // Camera
  8688. this.updateTransformMatrix();
  8689. renderTarget.render();
  8690. }
  8691. }
  8692. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  8693. this._renderId++;
  8694. }
  8695. if (this.customRenderTargets.length > 0) {
  8696. engine.restoreDefaultFramebuffer();
  8697. }
  8698. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  8699. this.activeCamera = currentActiveCamera;
  8700. // Procedural textures
  8701. if (this.proceduralTexturesEnabled) {
  8702. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  8703. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  8704. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  8705. if (proceduralTexture._shouldRender()) {
  8706. proceduralTexture.render();
  8707. }
  8708. }
  8709. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  8710. }
  8711. // Clear
  8712. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  8713. // Shadows
  8714. if (this.shadowsEnabled) {
  8715. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  8716. var light = this.lights[lightIndex];
  8717. var shadowGenerator = light.getShadowGenerator();
  8718. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  8719. this._renderTargets.push(shadowGenerator.getShadowMap());
  8720. }
  8721. }
  8722. }
  8723. // Depth renderer
  8724. if (this._depthRenderer) {
  8725. this._renderTargets.push(this._depthRenderer.getDepthMap());
  8726. }
  8727. // RenderPipeline
  8728. this.postProcessRenderPipelineManager.update();
  8729. // Multi-cameras?
  8730. if (this.activeCameras.length > 0) {
  8731. var currentRenderId = this._renderId;
  8732. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  8733. this._renderId = currentRenderId;
  8734. this._processSubCameras(this.activeCameras[cameraIndex]);
  8735. }
  8736. }
  8737. else {
  8738. if (!this.activeCamera) {
  8739. throw new Error("No camera defined");
  8740. }
  8741. this._processSubCameras(this.activeCamera);
  8742. }
  8743. // Intersection checks
  8744. this._checkIntersections();
  8745. // Update the audio listener attached to the camera
  8746. this._updateAudioParameters();
  8747. // After render
  8748. if (this.afterRender) {
  8749. this.afterRender();
  8750. }
  8751. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  8752. this._onAfterRenderCallbacks[callbackIndex]();
  8753. }
  8754. for (var index = 0; index < this._toBeDisposed.length; index++) {
  8755. this._toBeDisposed.data[index].dispose();
  8756. this._toBeDisposed[index] = null;
  8757. }
  8758. this._toBeDisposed.reset();
  8759. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  8760. this._lastFrameDuration = BABYLON.Tools.Now - startDate;
  8761. };
  8762. Scene.prototype._updateAudioParameters = function () {
  8763. if (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 0) {
  8764. return;
  8765. }
  8766. var listeningCamera;
  8767. var audioEngine = BABYLON.Engine.audioEngine;
  8768. if (this.activeCameras.length > 0) {
  8769. listeningCamera = this.activeCameras[0];
  8770. }
  8771. else {
  8772. listeningCamera = this.activeCamera;
  8773. }
  8774. if (listeningCamera && audioEngine.canUseWebAudio) {
  8775. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  8776. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  8777. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  8778. cameraDirection.normalize();
  8779. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  8780. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  8781. var sound = this.mainSoundTrack.soundCollection[i];
  8782. if (sound.useCustomAttenuation) {
  8783. sound.updateDistanceFromListener();
  8784. }
  8785. }
  8786. for (i = 0; i < this.soundTracks.length; i++) {
  8787. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  8788. sound = this.soundTracks[i].soundCollection[j];
  8789. if (sound.useCustomAttenuation) {
  8790. sound.updateDistanceFromListener();
  8791. }
  8792. }
  8793. }
  8794. }
  8795. };
  8796. Scene.prototype.enableDepthRenderer = function () {
  8797. if (this._depthRenderer) {
  8798. return this._depthRenderer;
  8799. }
  8800. this._depthRenderer = new BABYLON.DepthRenderer(this);
  8801. return this._depthRenderer;
  8802. };
  8803. Scene.prototype.disableDepthRenderer = function () {
  8804. if (!this._depthRenderer) {
  8805. return;
  8806. }
  8807. this._depthRenderer.dispose();
  8808. this._depthRenderer = null;
  8809. };
  8810. Scene.prototype.dispose = function () {
  8811. this.beforeRender = null;
  8812. this.afterRender = null;
  8813. this.skeletons = [];
  8814. this._boundingBoxRenderer.dispose();
  8815. if (this._depthRenderer) {
  8816. this._depthRenderer.dispose();
  8817. }
  8818. // Debug layer
  8819. this.debugLayer.hide();
  8820. // Events
  8821. if (this.onDispose) {
  8822. this.onDispose();
  8823. }
  8824. this._onBeforeRenderCallbacks = [];
  8825. this._onAfterRenderCallbacks = [];
  8826. this.detachControl();
  8827. // Release sounds & sounds tracks
  8828. this.mainSoundTrack.dispose();
  8829. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  8830. this.soundTracks[scIndex].dispose();
  8831. }
  8832. // Detach cameras
  8833. var canvas = this._engine.getRenderingCanvas();
  8834. var index;
  8835. for (index = 0; index < this.cameras.length; index++) {
  8836. this.cameras[index].detachControl(canvas);
  8837. }
  8838. while (this.lights.length) {
  8839. this.lights[0].dispose();
  8840. }
  8841. while (this.meshes.length) {
  8842. this.meshes[0].dispose(true);
  8843. }
  8844. while (this.cameras.length) {
  8845. this.cameras[0].dispose();
  8846. }
  8847. while (this.materials.length) {
  8848. this.materials[0].dispose();
  8849. }
  8850. while (this.particleSystems.length) {
  8851. this.particleSystems[0].dispose();
  8852. }
  8853. while (this.spriteManagers.length) {
  8854. this.spriteManagers[0].dispose();
  8855. }
  8856. while (this.layers.length) {
  8857. this.layers[0].dispose();
  8858. }
  8859. while (this.textures.length) {
  8860. this.textures[0].dispose();
  8861. }
  8862. // Post-processes
  8863. this.postProcessManager.dispose();
  8864. // Physics
  8865. if (this._physicsEngine) {
  8866. this.disablePhysicsEngine();
  8867. }
  8868. // Remove from engine
  8869. index = this._engine.scenes.indexOf(this);
  8870. if (index > -1) {
  8871. this._engine.scenes.splice(index, 1);
  8872. }
  8873. this._engine.wipeCaches();
  8874. };
  8875. // Collisions
  8876. Scene.prototype._getNewPosition = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  8877. if (excludedMesh === void 0) { excludedMesh = null; }
  8878. position.divideToRef(collider.radius, this._scaledPosition);
  8879. velocity.divideToRef(collider.radius, this._scaledVelocity);
  8880. collider.retry = 0;
  8881. collider.initialVelocity = this._scaledVelocity;
  8882. collider.initialPosition = this._scaledPosition;
  8883. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, finalPosition, excludedMesh);
  8884. finalPosition.multiplyInPlace(collider.radius);
  8885. };
  8886. Scene.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  8887. if (excludedMesh === void 0) { excludedMesh = null; }
  8888. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  8889. if (collider.retry >= maximumRetry) {
  8890. finalPosition.copyFrom(position);
  8891. return;
  8892. }
  8893. collider._initialize(position, velocity, closeDistance);
  8894. for (var index = 0; index < this.meshes.length; index++) {
  8895. var mesh = this.meshes[index];
  8896. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  8897. mesh._checkCollision(collider);
  8898. }
  8899. }
  8900. if (!collider.collisionFound) {
  8901. position.addToRef(velocity, finalPosition);
  8902. return;
  8903. }
  8904. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  8905. collider._getResponse(position, velocity);
  8906. }
  8907. if (velocity.length() <= closeDistance) {
  8908. finalPosition.copyFrom(position);
  8909. return;
  8910. }
  8911. collider.retry++;
  8912. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  8913. };
  8914. // Octrees
  8915. Scene.prototype.getWorldExtends = function () {
  8916. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8917. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8918. for (var index = 0; index < this.meshes.length; index++) {
  8919. var mesh = this.meshes[index];
  8920. mesh.computeWorldMatrix(true);
  8921. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  8922. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  8923. BABYLON.Tools.CheckExtends(minBox, min, max);
  8924. BABYLON.Tools.CheckExtends(maxBox, min, max);
  8925. }
  8926. return {
  8927. min: min,
  8928. max: max
  8929. };
  8930. };
  8931. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  8932. if (maxCapacity === void 0) { maxCapacity = 64; }
  8933. if (maxDepth === void 0) { maxDepth = 2; }
  8934. if (!this._selectionOctree) {
  8935. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  8936. }
  8937. var worldExtends = this.getWorldExtends();
  8938. // Update octree
  8939. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  8940. return this._selectionOctree;
  8941. };
  8942. // Picking
  8943. Scene.prototype.createPickingRay = function (x, y, world, camera) {
  8944. var engine = this._engine;
  8945. if (!camera) {
  8946. if (!this.activeCamera)
  8947. throw new Error("Active camera not set");
  8948. camera = this.activeCamera;
  8949. }
  8950. var cameraViewport = camera.viewport;
  8951. var viewport = cameraViewport.toGlobal(engine);
  8952. // Moving coordinates to local viewport world
  8953. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  8954. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  8955. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  8956. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  8957. };
  8958. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  8959. var pickingInfo = null;
  8960. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  8961. var mesh = this.meshes[meshIndex];
  8962. if (predicate) {
  8963. if (!predicate(mesh)) {
  8964. continue;
  8965. }
  8966. }
  8967. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  8968. continue;
  8969. }
  8970. var world = mesh.getWorldMatrix();
  8971. var ray = rayFunction(world);
  8972. var result = mesh.intersects(ray, fastCheck);
  8973. if (!result || !result.hit)
  8974. continue;
  8975. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  8976. continue;
  8977. pickingInfo = result;
  8978. if (fastCheck) {
  8979. break;
  8980. }
  8981. }
  8982. return pickingInfo || new BABYLON.PickingInfo();
  8983. };
  8984. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  8985. var _this = this;
  8986. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  8987. /// <param name="x">X position on screen</param>
  8988. /// <param name="y">Y position on screen</param>
  8989. /// <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>
  8990. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  8991. /// <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>
  8992. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  8993. };
  8994. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  8995. var _this = this;
  8996. return this._internalPick(function (world) {
  8997. if (!_this._pickWithRayInverseMatrix) {
  8998. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  8999. }
  9000. world.invertToRef(_this._pickWithRayInverseMatrix);
  9001. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  9002. }, predicate, fastCheck);
  9003. };
  9004. Scene.prototype.setPointerOverMesh = function (mesh) {
  9005. if (this._pointerOverMesh === mesh) {
  9006. return;
  9007. }
  9008. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  9009. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  9010. }
  9011. this._pointerOverMesh = mesh;
  9012. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  9013. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  9014. }
  9015. };
  9016. Scene.prototype.getPointerOverMesh = function () {
  9017. return this._pointerOverMesh;
  9018. };
  9019. // Physics
  9020. Scene.prototype.getPhysicsEngine = function () {
  9021. return this._physicsEngine;
  9022. };
  9023. Scene.prototype.enablePhysics = function (gravity, plugin) {
  9024. if (this._physicsEngine) {
  9025. return true;
  9026. }
  9027. this._physicsEngine = new BABYLON.PhysicsEngine(plugin);
  9028. if (!this._physicsEngine.isSupported()) {
  9029. this._physicsEngine = null;
  9030. return false;
  9031. }
  9032. this._physicsEngine._initialize(gravity);
  9033. return true;
  9034. };
  9035. Scene.prototype.disablePhysicsEngine = function () {
  9036. if (!this._physicsEngine) {
  9037. return;
  9038. }
  9039. this._physicsEngine.dispose();
  9040. this._physicsEngine = undefined;
  9041. };
  9042. Scene.prototype.isPhysicsEnabled = function () {
  9043. return this._physicsEngine !== undefined;
  9044. };
  9045. Scene.prototype.setGravity = function (gravity) {
  9046. if (!this._physicsEngine) {
  9047. return;
  9048. }
  9049. this._physicsEngine._setGravity(gravity);
  9050. };
  9051. Scene.prototype.createCompoundImpostor = function (parts, options) {
  9052. if (parts.parts) {
  9053. options = parts;
  9054. parts = parts.parts;
  9055. }
  9056. if (!this._physicsEngine) {
  9057. return null;
  9058. }
  9059. for (var index = 0; index < parts.length; index++) {
  9060. var mesh = parts[index].mesh;
  9061. mesh._physicImpostor = parts[index].impostor;
  9062. mesh._physicsMass = options.mass / parts.length;
  9063. mesh._physicsFriction = options.friction;
  9064. mesh._physicRestitution = options.restitution;
  9065. }
  9066. return this._physicsEngine._registerMeshesAsCompound(parts, options);
  9067. };
  9068. Scene.prototype.deleteCompoundImpostor = function (compound) {
  9069. for (var index = 0; index < compound.parts.length; index++) {
  9070. var mesh = compound.parts[index].mesh;
  9071. mesh._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  9072. this._physicsEngine._unregisterMesh(mesh);
  9073. }
  9074. };
  9075. // Misc.
  9076. Scene.prototype.createDefaultCameraOrLight = function () {
  9077. // Light
  9078. if (this.lights.length === 0) {
  9079. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  9080. }
  9081. // Camera
  9082. if (!this.activeCamera) {
  9083. var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  9084. // Compute position
  9085. var worldExtends = this.getWorldExtends();
  9086. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  9087. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  9088. camera.setTarget(worldCenter);
  9089. this.activeCamera = camera;
  9090. }
  9091. };
  9092. // Tags
  9093. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  9094. if (tagsQuery === undefined) {
  9095. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  9096. return list;
  9097. }
  9098. var listByTags = [];
  9099. forEach = forEach || (function (item) {
  9100. return;
  9101. });
  9102. for (var i in list) {
  9103. var item = list[i];
  9104. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  9105. listByTags.push(item);
  9106. forEach(item);
  9107. }
  9108. }
  9109. return listByTags;
  9110. };
  9111. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  9112. return this._getByTags(this.meshes, tagsQuery, forEach);
  9113. };
  9114. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  9115. return this._getByTags(this.cameras, tagsQuery, forEach);
  9116. };
  9117. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  9118. return this._getByTags(this.lights, tagsQuery, forEach);
  9119. };
  9120. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  9121. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  9122. };
  9123. // Statics
  9124. Scene._FOGMODE_NONE = 0;
  9125. Scene._FOGMODE_EXP = 1;
  9126. Scene._FOGMODE_EXP2 = 2;
  9127. Scene._FOGMODE_LINEAR = 3;
  9128. Scene.MinDeltaTime = 1.0;
  9129. Scene.MaxDeltaTime = 1000.0;
  9130. return Scene;
  9131. })();
  9132. BABYLON.Scene = Scene;
  9133. })(BABYLON || (BABYLON = {}));
  9134. //# sourceMappingURL=babylon.scene.js.mapvar BABYLON;
  9135. (function (BABYLON) {
  9136. var VertexBuffer = (function () {
  9137. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride) {
  9138. if (engine instanceof BABYLON.Mesh) {
  9139. this._engine = engine.getScene().getEngine();
  9140. }
  9141. else {
  9142. this._engine = engine;
  9143. }
  9144. this._updatable = updatable;
  9145. this._data = data;
  9146. if (!postponeInternalCreation) {
  9147. this.create();
  9148. }
  9149. this._kind = kind;
  9150. if (stride) {
  9151. this._strideSize = stride;
  9152. return;
  9153. }
  9154. switch (kind) {
  9155. case VertexBuffer.PositionKind:
  9156. this._strideSize = 3;
  9157. break;
  9158. case VertexBuffer.NormalKind:
  9159. this._strideSize = 3;
  9160. break;
  9161. case VertexBuffer.UVKind:
  9162. this._strideSize = 2;
  9163. break;
  9164. case VertexBuffer.UV2Kind:
  9165. this._strideSize = 2;
  9166. break;
  9167. case VertexBuffer.ColorKind:
  9168. this._strideSize = 4;
  9169. break;
  9170. case VertexBuffer.MatricesIndicesKind:
  9171. this._strideSize = 4;
  9172. break;
  9173. case VertexBuffer.MatricesWeightsKind:
  9174. this._strideSize = 4;
  9175. break;
  9176. }
  9177. }
  9178. // Properties
  9179. VertexBuffer.prototype.isUpdatable = function () {
  9180. return this._updatable;
  9181. };
  9182. VertexBuffer.prototype.getData = function () {
  9183. return this._data;
  9184. };
  9185. VertexBuffer.prototype.getBuffer = function () {
  9186. return this._buffer;
  9187. };
  9188. VertexBuffer.prototype.getStrideSize = function () {
  9189. return this._strideSize;
  9190. };
  9191. // Methods
  9192. VertexBuffer.prototype.create = function (data) {
  9193. if (!data && this._buffer) {
  9194. return; // nothing to do
  9195. }
  9196. data = data || this._data;
  9197. if (!this._buffer) {
  9198. if (this._updatable) {
  9199. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  9200. }
  9201. else {
  9202. this._buffer = this._engine.createVertexBuffer(data);
  9203. }
  9204. }
  9205. if (this._updatable) {
  9206. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  9207. this._data = data;
  9208. }
  9209. };
  9210. VertexBuffer.prototype.update = function (data) {
  9211. this.create(data);
  9212. };
  9213. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  9214. if (!this._buffer) {
  9215. return;
  9216. }
  9217. if (this._updatable) {
  9218. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset);
  9219. this._data = null;
  9220. }
  9221. };
  9222. VertexBuffer.prototype.dispose = function () {
  9223. if (!this._buffer) {
  9224. return;
  9225. }
  9226. if (this._engine._releaseBuffer(this._buffer)) {
  9227. this._buffer = null;
  9228. }
  9229. };
  9230. Object.defineProperty(VertexBuffer, "PositionKind", {
  9231. get: function () {
  9232. return VertexBuffer._PositionKind;
  9233. },
  9234. enumerable: true,
  9235. configurable: true
  9236. });
  9237. Object.defineProperty(VertexBuffer, "NormalKind", {
  9238. get: function () {
  9239. return VertexBuffer._NormalKind;
  9240. },
  9241. enumerable: true,
  9242. configurable: true
  9243. });
  9244. Object.defineProperty(VertexBuffer, "UVKind", {
  9245. get: function () {
  9246. return VertexBuffer._UVKind;
  9247. },
  9248. enumerable: true,
  9249. configurable: true
  9250. });
  9251. Object.defineProperty(VertexBuffer, "UV2Kind", {
  9252. get: function () {
  9253. return VertexBuffer._UV2Kind;
  9254. },
  9255. enumerable: true,
  9256. configurable: true
  9257. });
  9258. Object.defineProperty(VertexBuffer, "ColorKind", {
  9259. get: function () {
  9260. return VertexBuffer._ColorKind;
  9261. },
  9262. enumerable: true,
  9263. configurable: true
  9264. });
  9265. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  9266. get: function () {
  9267. return VertexBuffer._MatricesIndicesKind;
  9268. },
  9269. enumerable: true,
  9270. configurable: true
  9271. });
  9272. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  9273. get: function () {
  9274. return VertexBuffer._MatricesWeightsKind;
  9275. },
  9276. enumerable: true,
  9277. configurable: true
  9278. });
  9279. // Enums
  9280. VertexBuffer._PositionKind = "position";
  9281. VertexBuffer._NormalKind = "normal";
  9282. VertexBuffer._UVKind = "uv";
  9283. VertexBuffer._UV2Kind = "uv2";
  9284. VertexBuffer._ColorKind = "color";
  9285. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  9286. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  9287. return VertexBuffer;
  9288. })();
  9289. BABYLON.VertexBuffer = VertexBuffer;
  9290. })(BABYLON || (BABYLON = {}));
  9291. //# sourceMappingURL=babylon.vertexBuffer.js.map
  9292. var BABYLON;
  9293. (function (BABYLON) {
  9294. var AbstractMesh = (function (_super) {
  9295. __extends(AbstractMesh, _super);
  9296. function AbstractMesh(name, scene) {
  9297. _super.call(this, name, scene);
  9298. // Properties
  9299. this.definedFacingForward = true; // orientation for POV movement & rotation
  9300. this.position = new BABYLON.Vector3(0, 0, 0);
  9301. this.rotation = new BABYLON.Vector3(0, 0, 0);
  9302. this.scaling = new BABYLON.Vector3(1, 1, 1);
  9303. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  9304. this.visibility = 1.0;
  9305. this.alphaIndex = Number.MAX_VALUE;
  9306. this.infiniteDistance = false;
  9307. this.isVisible = true;
  9308. this.isPickable = true;
  9309. this.showBoundingBox = false;
  9310. this.showSubMeshesBoundingBox = false;
  9311. this.onDispose = null;
  9312. this.checkCollisions = false;
  9313. this.isBlocker = false;
  9314. this.renderingGroupId = 0;
  9315. this.receiveShadows = false;
  9316. this.renderOutline = false;
  9317. this.outlineColor = BABYLON.Color3.Red();
  9318. this.outlineWidth = 0.02;
  9319. this.renderOverlay = false;
  9320. this.overlayColor = BABYLON.Color3.Red();
  9321. this.overlayAlpha = 0.5;
  9322. this.hasVertexAlpha = false;
  9323. this.useVertexColors = true;
  9324. this.applyFog = true;
  9325. this.useOctreeForRenderingSelection = true;
  9326. this.useOctreeForPicking = true;
  9327. this.useOctreeForCollisions = true;
  9328. this.layerMask = 0xFFFFFFFF;
  9329. // Physics
  9330. this._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  9331. // Collisions
  9332. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  9333. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  9334. this._collider = new BABYLON.Collider();
  9335. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  9336. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  9337. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  9338. // Cache
  9339. this._localScaling = BABYLON.Matrix.Zero();
  9340. this._localRotation = BABYLON.Matrix.Zero();
  9341. this._localTranslation = BABYLON.Matrix.Zero();
  9342. this._localBillboard = BABYLON.Matrix.Zero();
  9343. this._localPivotScaling = BABYLON.Matrix.Zero();
  9344. this._localPivotScalingRotation = BABYLON.Matrix.Zero();
  9345. this._localWorld = BABYLON.Matrix.Zero();
  9346. this._worldMatrix = BABYLON.Matrix.Zero();
  9347. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  9348. this._absolutePosition = BABYLON.Vector3.Zero();
  9349. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  9350. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  9351. this._isDirty = false;
  9352. this._pivotMatrix = BABYLON.Matrix.Identity();
  9353. this._isDisposed = false;
  9354. this._renderId = 0;
  9355. this._intersectionsInProgress = new Array();
  9356. this._onAfterWorldMatrixUpdate = new Array();
  9357. scene.meshes.push(this);
  9358. }
  9359. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  9360. get: function () {
  9361. return AbstractMesh._BILLBOARDMODE_NONE;
  9362. },
  9363. enumerable: true,
  9364. configurable: true
  9365. });
  9366. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  9367. get: function () {
  9368. return AbstractMesh._BILLBOARDMODE_X;
  9369. },
  9370. enumerable: true,
  9371. configurable: true
  9372. });
  9373. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  9374. get: function () {
  9375. return AbstractMesh._BILLBOARDMODE_Y;
  9376. },
  9377. enumerable: true,
  9378. configurable: true
  9379. });
  9380. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  9381. get: function () {
  9382. return AbstractMesh._BILLBOARDMODE_Z;
  9383. },
  9384. enumerable: true,
  9385. configurable: true
  9386. });
  9387. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  9388. get: function () {
  9389. return AbstractMesh._BILLBOARDMODE_ALL;
  9390. },
  9391. enumerable: true,
  9392. configurable: true
  9393. });
  9394. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  9395. // Methods
  9396. get: function () {
  9397. return false;
  9398. },
  9399. enumerable: true,
  9400. configurable: true
  9401. });
  9402. AbstractMesh.prototype.getLOD = function (camera) {
  9403. return this;
  9404. };
  9405. AbstractMesh.prototype.getTotalVertices = function () {
  9406. return 0;
  9407. };
  9408. AbstractMesh.prototype.getIndices = function () {
  9409. return null;
  9410. };
  9411. AbstractMesh.prototype.getVerticesData = function (kind) {
  9412. return null;
  9413. };
  9414. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  9415. return false;
  9416. };
  9417. AbstractMesh.prototype.getBoundingInfo = function () {
  9418. if (this._masterMesh) {
  9419. return this._masterMesh.getBoundingInfo();
  9420. }
  9421. if (!this._boundingInfo) {
  9422. this._updateBoundingInfo();
  9423. }
  9424. return this._boundingInfo;
  9425. };
  9426. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  9427. get: function () {
  9428. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  9429. },
  9430. enumerable: true,
  9431. configurable: true
  9432. });
  9433. AbstractMesh.prototype._preActivate = function () {
  9434. };
  9435. AbstractMesh.prototype._activate = function (renderId) {
  9436. this._renderId = renderId;
  9437. };
  9438. AbstractMesh.prototype.getWorldMatrix = function () {
  9439. if (this._masterMesh) {
  9440. return this._masterMesh.getWorldMatrix();
  9441. }
  9442. if (this._currentRenderId !== this.getScene().getRenderId()) {
  9443. this.computeWorldMatrix();
  9444. }
  9445. return this._worldMatrix;
  9446. };
  9447. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  9448. get: function () {
  9449. return this._worldMatrix;
  9450. },
  9451. enumerable: true,
  9452. configurable: true
  9453. });
  9454. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  9455. get: function () {
  9456. return this._absolutePosition;
  9457. },
  9458. enumerable: true,
  9459. configurable: true
  9460. });
  9461. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  9462. if (!this.rotationQuaternion) {
  9463. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  9464. this.rotation = BABYLON.Vector3.Zero();
  9465. }
  9466. if (!space || space == 0 /* LOCAL */) {
  9467. var rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  9468. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  9469. }
  9470. else {
  9471. if (this.parent) {
  9472. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  9473. invertParentWorldMatrix.invert();
  9474. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  9475. }
  9476. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  9477. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  9478. }
  9479. };
  9480. AbstractMesh.prototype.translate = function (axis, distance, space) {
  9481. var displacementVector = axis.scale(distance);
  9482. if (!space || space == 0 /* LOCAL */) {
  9483. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  9484. this.setPositionWithLocalVector(tempV3);
  9485. }
  9486. else {
  9487. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  9488. }
  9489. };
  9490. AbstractMesh.prototype.getAbsolutePosition = function () {
  9491. this.computeWorldMatrix();
  9492. return this._absolutePosition;
  9493. };
  9494. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  9495. if (!absolutePosition) {
  9496. return;
  9497. }
  9498. var absolutePositionX;
  9499. var absolutePositionY;
  9500. var absolutePositionZ;
  9501. if (absolutePosition.x === undefined) {
  9502. if (arguments.length < 3) {
  9503. return;
  9504. }
  9505. absolutePositionX = arguments[0];
  9506. absolutePositionY = arguments[1];
  9507. absolutePositionZ = arguments[2];
  9508. }
  9509. else {
  9510. absolutePositionX = absolutePosition.x;
  9511. absolutePositionY = absolutePosition.y;
  9512. absolutePositionZ = absolutePosition.z;
  9513. }
  9514. if (this.parent) {
  9515. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  9516. invertParentWorldMatrix.invert();
  9517. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  9518. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  9519. }
  9520. else {
  9521. this.position.x = absolutePositionX;
  9522. this.position.y = absolutePositionY;
  9523. this.position.z = absolutePositionZ;
  9524. }
  9525. };
  9526. // ================================== Point of View Movement =================================
  9527. /**
  9528. * Perform relative position change from the point of view of behind the front of the mesh.
  9529. * This is performed taking into account the meshes current rotation, so you do not have to care.
  9530. * Supports definition of mesh facing forward or backward.
  9531. * @param {number} amountRight
  9532. * @param {number} amountUp
  9533. * @param {number} amountForward
  9534. */
  9535. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  9536. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  9537. };
  9538. /**
  9539. * Calculate relative position change from the point of view of behind the front of the mesh.
  9540. * This is performed taking into account the meshes current rotation, so you do not have to care.
  9541. * Supports definition of mesh facing forward or backward.
  9542. * @param {number} amountRight
  9543. * @param {number} amountUp
  9544. * @param {number} amountForward
  9545. */
  9546. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  9547. var rotMatrix = new BABYLON.Matrix();
  9548. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  9549. rotQuaternion.toRotationMatrix(rotMatrix);
  9550. var translationDelta = BABYLON.Vector3.Zero();
  9551. var defForwardMult = this.definedFacingForward ? -1 : 1;
  9552. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  9553. return translationDelta;
  9554. };
  9555. // ================================== Point of View Rotation =================================
  9556. /**
  9557. * Perform relative rotation change from the point of view of behind the front of the mesh.
  9558. * Supports definition of mesh facing forward or backward.
  9559. * @param {number} flipBack
  9560. * @param {number} twirlClockwise
  9561. * @param {number} tiltRight
  9562. */
  9563. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  9564. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  9565. };
  9566. /**
  9567. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  9568. * Supports definition of mesh facing forward or backward.
  9569. * @param {number} flipBack
  9570. * @param {number} twirlClockwise
  9571. * @param {number} tiltRight
  9572. */
  9573. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  9574. var defForwardMult = this.definedFacingForward ? 1 : -1;
  9575. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  9576. };
  9577. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  9578. this._pivotMatrix = matrix;
  9579. this._cache.pivotMatrixUpdated = true;
  9580. };
  9581. AbstractMesh.prototype.getPivotMatrix = function () {
  9582. return this._pivotMatrix;
  9583. };
  9584. AbstractMesh.prototype._isSynchronized = function () {
  9585. if (this._isDirty) {
  9586. return false;
  9587. }
  9588. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  9589. return false;
  9590. if (this._cache.pivotMatrixUpdated) {
  9591. return false;
  9592. }
  9593. if (this.infiniteDistance) {
  9594. return false;
  9595. }
  9596. if (!this._cache.position.equals(this.position))
  9597. return false;
  9598. if (this.rotationQuaternion) {
  9599. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  9600. return false;
  9601. }
  9602. else {
  9603. if (!this._cache.rotation.equals(this.rotation))
  9604. return false;
  9605. }
  9606. if (!this._cache.scaling.equals(this.scaling))
  9607. return false;
  9608. return true;
  9609. };
  9610. AbstractMesh.prototype._initCache = function () {
  9611. _super.prototype._initCache.call(this);
  9612. this._cache.localMatrixUpdated = false;
  9613. this._cache.position = BABYLON.Vector3.Zero();
  9614. this._cache.scaling = BABYLON.Vector3.Zero();
  9615. this._cache.rotation = BABYLON.Vector3.Zero();
  9616. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  9617. };
  9618. AbstractMesh.prototype.markAsDirty = function (property) {
  9619. if (property === "rotation") {
  9620. this.rotationQuaternion = null;
  9621. }
  9622. this._currentRenderId = Number.MAX_VALUE;
  9623. this._isDirty = true;
  9624. };
  9625. AbstractMesh.prototype._updateBoundingInfo = function () {
  9626. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  9627. this._boundingInfo._update(this.worldMatrixFromCache);
  9628. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  9629. };
  9630. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  9631. if (!this.subMeshes) {
  9632. return;
  9633. }
  9634. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  9635. var subMesh = this.subMeshes[subIndex];
  9636. subMesh.updateBoundingInfo(matrix);
  9637. }
  9638. };
  9639. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  9640. if (!force && (this._currentRenderId == this.getScene().getRenderId() || this.isSynchronized(true))) {
  9641. return this._worldMatrix;
  9642. }
  9643. this._cache.position.copyFrom(this.position);
  9644. this._cache.scaling.copyFrom(this.scaling);
  9645. this._cache.pivotMatrixUpdated = false;
  9646. this._currentRenderId = this.getScene().getRenderId();
  9647. this._isDirty = false;
  9648. // Scaling
  9649. BABYLON.Matrix.ScalingToRef(this.scaling.x, this.scaling.y, this.scaling.z, this._localScaling);
  9650. // Rotation
  9651. if (this.rotationQuaternion) {
  9652. this.rotationQuaternion.toRotationMatrix(this._localRotation);
  9653. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  9654. }
  9655. else {
  9656. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._localRotation);
  9657. this._cache.rotation.copyFrom(this.rotation);
  9658. }
  9659. // Translation
  9660. if (this.infiniteDistance && !this.parent) {
  9661. var camera = this.getScene().activeCamera;
  9662. var cameraWorldMatrix = camera.getWorldMatrix();
  9663. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  9664. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, this._localTranslation);
  9665. }
  9666. else {
  9667. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._localTranslation);
  9668. }
  9669. // Composing transformations
  9670. this._pivotMatrix.multiplyToRef(this._localScaling, this._localPivotScaling);
  9671. this._localPivotScaling.multiplyToRef(this._localRotation, this._localPivotScalingRotation);
  9672. // Billboarding
  9673. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  9674. var localPosition = this.position.clone();
  9675. var zero = this.getScene().activeCamera.position.clone();
  9676. if (this.parent && this.parent.position) {
  9677. localPosition.addInPlace(this.parent.position);
  9678. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, this._localTranslation);
  9679. }
  9680. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) === AbstractMesh.BILLBOARDMODE_ALL) {
  9681. zero = this.getScene().activeCamera.position;
  9682. }
  9683. else {
  9684. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X)
  9685. zero.x = localPosition.x + BABYLON.Engine.Epsilon;
  9686. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y)
  9687. zero.y = localPosition.y + 0.001;
  9688. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z)
  9689. zero.z = localPosition.z + 0.001;
  9690. }
  9691. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), this._localBillboard);
  9692. this._localBillboard.m[12] = this._localBillboard.m[13] = this._localBillboard.m[14] = 0;
  9693. this._localBillboard.invert();
  9694. this._localPivotScalingRotation.multiplyToRef(this._localBillboard, this._localWorld);
  9695. this._rotateYByPI.multiplyToRef(this._localWorld, this._localPivotScalingRotation);
  9696. }
  9697. // Local world
  9698. this._localPivotScalingRotation.multiplyToRef(this._localTranslation, this._localWorld);
  9699. // Parent
  9700. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  9701. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  9702. }
  9703. else {
  9704. this._worldMatrix.copyFrom(this._localWorld);
  9705. }
  9706. // Bounding info
  9707. this._updateBoundingInfo();
  9708. // Absolute position
  9709. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  9710. for (var callbackIndex = 0; callbackIndex < this._onAfterWorldMatrixUpdate.length; callbackIndex++) {
  9711. this._onAfterWorldMatrixUpdate[callbackIndex](this);
  9712. }
  9713. return this._worldMatrix;
  9714. };
  9715. /**
  9716. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  9717. * @param func: callback function to add
  9718. */
  9719. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  9720. this._onAfterWorldMatrixUpdate.push(func);
  9721. };
  9722. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  9723. var index = this._onAfterWorldMatrixUpdate.indexOf(func);
  9724. if (index > -1) {
  9725. this._onAfterWorldMatrixUpdate.splice(index, 1);
  9726. }
  9727. };
  9728. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  9729. this.computeWorldMatrix();
  9730. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  9731. };
  9732. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  9733. this.computeWorldMatrix();
  9734. var invLocalWorldMatrix = this._localWorld.clone();
  9735. invLocalWorldMatrix.invert();
  9736. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  9737. };
  9738. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  9739. this.computeWorldMatrix();
  9740. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  9741. };
  9742. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  9743. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  9744. /// <param name="targetPoint" type="BABYLON.Vector3">The position (must be in same space as current mesh) to look at</param>
  9745. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  9746. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  9747. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  9748. /// <returns>Mesh oriented towards targetMesh</returns>
  9749. yawCor = yawCor || 0; // default to zero if undefined
  9750. pitchCor = pitchCor || 0;
  9751. rollCor = rollCor || 0;
  9752. var dv = targetPoint.subtract(this.position);
  9753. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  9754. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  9755. var pitch = Math.atan2(dv.y, len);
  9756. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  9757. };
  9758. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  9759. if (!this._boundingInfo.isInFrustum(frustumPlanes)) {
  9760. return false;
  9761. }
  9762. return true;
  9763. };
  9764. AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
  9765. if (!camera) {
  9766. camera = this.getScene().activeCamera;
  9767. }
  9768. var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
  9769. if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
  9770. return false;
  9771. }
  9772. return true;
  9773. };
  9774. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  9775. if (!this._boundingInfo || !mesh._boundingInfo) {
  9776. return false;
  9777. }
  9778. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  9779. };
  9780. AbstractMesh.prototype.intersectsPoint = function (point) {
  9781. if (!this._boundingInfo) {
  9782. return false;
  9783. }
  9784. return this._boundingInfo.intersectsPoint(point);
  9785. };
  9786. // Physics
  9787. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  9788. var physicsEngine = this.getScene().getPhysicsEngine();
  9789. if (!physicsEngine) {
  9790. return;
  9791. }
  9792. impostor = impostor || BABYLON.PhysicsEngine.NoImpostor;
  9793. if (impostor.impostor) {
  9794. // Old API
  9795. options = impostor;
  9796. impostor = impostor.impostor;
  9797. }
  9798. if (impostor === BABYLON.PhysicsEngine.NoImpostor) {
  9799. physicsEngine._unregisterMesh(this);
  9800. return;
  9801. }
  9802. if (!options) {
  9803. options = { mass: 0, friction: 0.2, restitution: 0.2 };
  9804. }
  9805. else {
  9806. if (!options.mass && options.mass !== 0)
  9807. options.mass = 0;
  9808. if (!options.friction && options.friction !== 0)
  9809. options.friction = 0.2;
  9810. if (!options.restitution && options.restitution !== 0)
  9811. options.restitution = 0.2;
  9812. }
  9813. this._physicImpostor = impostor;
  9814. this._physicsMass = options.mass;
  9815. this._physicsFriction = options.friction;
  9816. this._physicRestitution = options.restitution;
  9817. return physicsEngine._registerMesh(this, impostor, options);
  9818. };
  9819. AbstractMesh.prototype.getPhysicsImpostor = function () {
  9820. if (!this._physicImpostor) {
  9821. return BABYLON.PhysicsEngine.NoImpostor;
  9822. }
  9823. return this._physicImpostor;
  9824. };
  9825. AbstractMesh.prototype.getPhysicsMass = function () {
  9826. if (!this._physicsMass) {
  9827. return 0;
  9828. }
  9829. return this._physicsMass;
  9830. };
  9831. AbstractMesh.prototype.getPhysicsFriction = function () {
  9832. if (!this._physicsFriction) {
  9833. return 0;
  9834. }
  9835. return this._physicsFriction;
  9836. };
  9837. AbstractMesh.prototype.getPhysicsRestitution = function () {
  9838. if (!this._physicRestitution) {
  9839. return 0;
  9840. }
  9841. return this._physicRestitution;
  9842. };
  9843. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  9844. if (!camera) {
  9845. camera = this.getScene().activeCamera;
  9846. }
  9847. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  9848. };
  9849. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  9850. if (!camera) {
  9851. camera = this.getScene().activeCamera;
  9852. }
  9853. return this.absolutePosition.subtract(camera.position).length();
  9854. };
  9855. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  9856. if (!this._physicImpostor) {
  9857. return;
  9858. }
  9859. this.getScene().getPhysicsEngine()._applyImpulse(this, force, contactPoint);
  9860. };
  9861. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  9862. if (!this._physicImpostor) {
  9863. return;
  9864. }
  9865. this.getScene().getPhysicsEngine()._createLink(this, otherMesh, pivot1, pivot2, options);
  9866. };
  9867. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  9868. if (!this._physicImpostor) {
  9869. return;
  9870. }
  9871. this.getScene().getPhysicsEngine()._updateBodyPosition(this);
  9872. };
  9873. // Collisions
  9874. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  9875. var globalPosition = this.getAbsolutePosition();
  9876. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  9877. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  9878. this._collider.radius = this.ellipsoid;
  9879. this.getScene()._getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this._newPositionForCollisions, this);
  9880. this._newPositionForCollisions.subtractToRef(this._oldPositionForCollisions, this._diffPositionForCollisions);
  9881. if (this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  9882. this.position.addInPlace(this._diffPositionForCollisions);
  9883. }
  9884. };
  9885. // Submeshes octree
  9886. /**
  9887. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  9888. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  9889. */
  9890. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  9891. if (maxCapacity === void 0) { maxCapacity = 64; }
  9892. if (maxDepth === void 0) { maxDepth = 2; }
  9893. if (!this._submeshesOctree) {
  9894. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  9895. }
  9896. this.computeWorldMatrix(true);
  9897. // Update octree
  9898. var bbox = this.getBoundingInfo().boundingBox;
  9899. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  9900. return this._submeshesOctree;
  9901. };
  9902. // Collisions
  9903. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  9904. this._generatePointsArray();
  9905. // Transformation
  9906. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  9907. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  9908. subMesh._lastColliderWorldVertices = [];
  9909. subMesh._trianglePlanes = [];
  9910. var start = subMesh.verticesStart;
  9911. var end = (subMesh.verticesStart + subMesh.verticesCount);
  9912. for (var i = start; i < end; i++) {
  9913. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  9914. }
  9915. }
  9916. // Collide
  9917. collider._collide(subMesh, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart);
  9918. };
  9919. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  9920. var subMeshes;
  9921. var len;
  9922. // Octrees
  9923. if (this._submeshesOctree && this.useOctreeForCollisions) {
  9924. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  9925. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  9926. len = intersections.length;
  9927. subMeshes = intersections.data;
  9928. }
  9929. else {
  9930. subMeshes = this.subMeshes;
  9931. len = subMeshes.length;
  9932. }
  9933. for (var index = 0; index < len; index++) {
  9934. var subMesh = subMeshes[index];
  9935. // Bounding test
  9936. if (len > 1 && !subMesh._checkCollision(collider))
  9937. continue;
  9938. this._collideForSubMesh(subMesh, transformMatrix, collider);
  9939. }
  9940. };
  9941. AbstractMesh.prototype._checkCollision = function (collider) {
  9942. // Bounding box test
  9943. if (!this._boundingInfo._checkCollision(collider))
  9944. return;
  9945. // Transformation matrix
  9946. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  9947. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  9948. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  9949. };
  9950. // Picking
  9951. AbstractMesh.prototype._generatePointsArray = function () {
  9952. return false;
  9953. };
  9954. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  9955. var pickingInfo = new BABYLON.PickingInfo();
  9956. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  9957. return pickingInfo;
  9958. }
  9959. if (!this._generatePointsArray()) {
  9960. return pickingInfo;
  9961. }
  9962. var intersectInfo = null;
  9963. // Octrees
  9964. var subMeshes;
  9965. var len;
  9966. if (this._submeshesOctree && this.useOctreeForPicking) {
  9967. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  9968. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  9969. len = intersections.length;
  9970. subMeshes = intersections.data;
  9971. }
  9972. else {
  9973. subMeshes = this.subMeshes;
  9974. len = subMeshes.length;
  9975. }
  9976. for (var index = 0; index < len; index++) {
  9977. var subMesh = subMeshes[index];
  9978. // Bounding test
  9979. if (len > 1 && !subMesh.canIntersects(ray))
  9980. continue;
  9981. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  9982. if (currentIntersectInfo) {
  9983. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  9984. intersectInfo = currentIntersectInfo;
  9985. intersectInfo.subMeshId = index;
  9986. if (fastCheck) {
  9987. break;
  9988. }
  9989. }
  9990. }
  9991. }
  9992. if (intersectInfo) {
  9993. // Get picked point
  9994. var world = this.getWorldMatrix();
  9995. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  9996. var direction = ray.direction.clone();
  9997. direction = direction.scale(intersectInfo.distance);
  9998. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  9999. var pickedPoint = worldOrigin.add(worldDirection);
  10000. // Return result
  10001. pickingInfo.hit = true;
  10002. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  10003. pickingInfo.pickedPoint = pickedPoint;
  10004. pickingInfo.pickedMesh = this;
  10005. pickingInfo.bu = intersectInfo.bu;
  10006. pickingInfo.bv = intersectInfo.bv;
  10007. pickingInfo.faceId = intersectInfo.faceId;
  10008. pickingInfo.subMeshId = intersectInfo.subMeshId;
  10009. return pickingInfo;
  10010. }
  10011. return pickingInfo;
  10012. };
  10013. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  10014. return null;
  10015. };
  10016. AbstractMesh.prototype.releaseSubMeshes = function () {
  10017. if (this.subMeshes) {
  10018. while (this.subMeshes.length) {
  10019. this.subMeshes[0].dispose();
  10020. }
  10021. }
  10022. else {
  10023. this.subMeshes = new Array();
  10024. }
  10025. };
  10026. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  10027. // Physics
  10028. if (this.getPhysicsImpostor() != BABYLON.PhysicsEngine.NoImpostor) {
  10029. this.setPhysicsState(BABYLON.PhysicsEngine.NoImpostor);
  10030. }
  10031. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  10032. var other = this._intersectionsInProgress[index];
  10033. var pos = other._intersectionsInProgress.indexOf(this);
  10034. other._intersectionsInProgress.splice(pos, 1);
  10035. }
  10036. this._intersectionsInProgress = [];
  10037. // SubMeshes
  10038. this.releaseSubMeshes();
  10039. // Remove from scene
  10040. var index = this.getScene().meshes.indexOf(this);
  10041. if (index != -1) {
  10042. // Remove from the scene if mesh found
  10043. this.getScene().meshes.splice(index, 1);
  10044. }
  10045. if (!doNotRecurse) {
  10046. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  10047. if (this.getScene().particleSystems[index].emitter == this) {
  10048. this.getScene().particleSystems[index].dispose();
  10049. index--;
  10050. }
  10051. }
  10052. // Children
  10053. var objects = this.getScene().meshes.slice(0);
  10054. for (index = 0; index < objects.length; index++) {
  10055. if (objects[index].parent == this) {
  10056. objects[index].dispose();
  10057. }
  10058. }
  10059. }
  10060. else {
  10061. for (index = 0; index < this.getScene().meshes.length; index++) {
  10062. var obj = this.getScene().meshes[index];
  10063. if (obj.parent === this) {
  10064. obj.parent = null;
  10065. obj.computeWorldMatrix(true);
  10066. }
  10067. }
  10068. }
  10069. this._onAfterWorldMatrixUpdate = [];
  10070. this._isDisposed = true;
  10071. // Callback
  10072. if (this.onDispose) {
  10073. this.onDispose();
  10074. }
  10075. };
  10076. // Statics
  10077. AbstractMesh._BILLBOARDMODE_NONE = 0;
  10078. AbstractMesh._BILLBOARDMODE_X = 1;
  10079. AbstractMesh._BILLBOARDMODE_Y = 2;
  10080. AbstractMesh._BILLBOARDMODE_Z = 4;
  10081. AbstractMesh._BILLBOARDMODE_ALL = 7;
  10082. return AbstractMesh;
  10083. })(BABYLON.Node);
  10084. BABYLON.AbstractMesh = AbstractMesh;
  10085. })(BABYLON || (BABYLON = {}));
  10086. //# sourceMappingURL=babylon.abstractMesh.js.map
  10087. var BABYLON;
  10088. (function (BABYLON) {
  10089. var _InstancesBatch = (function () {
  10090. function _InstancesBatch() {
  10091. this.mustReturn = false;
  10092. this.visibleInstances = new Array();
  10093. this.renderSelf = new Array();
  10094. }
  10095. return _InstancesBatch;
  10096. })();
  10097. BABYLON._InstancesBatch = _InstancesBatch;
  10098. var Mesh = (function (_super) {
  10099. __extends(Mesh, _super);
  10100. /**
  10101. * @constructor
  10102. * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
  10103. * @param {Scene} scene - The scene to add this mesh to.
  10104. * @param {Node} parent - The parent of this mesh, if it has one
  10105. * @param {Mesh} source - An optional Mesh from which geometry is shared, cloned.
  10106. * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
  10107. * When false, achieved by calling a clone(), also passing False.
  10108. * This will make creation of children, recursive.
  10109. */
  10110. function Mesh(name, scene, parent, source, doNotCloneChildren) {
  10111. if (parent === void 0) { parent = null; }
  10112. _super.call(this, name, scene);
  10113. // Members
  10114. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  10115. this.instances = new Array();
  10116. this._LODLevels = new Array();
  10117. this._onBeforeRenderCallbacks = new Array();
  10118. this._onAfterRenderCallbacks = new Array();
  10119. this._visibleInstances = {};
  10120. this._renderIdForInstances = new Array();
  10121. this._batchCache = new _InstancesBatch();
  10122. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  10123. if (source) {
  10124. // Geometry
  10125. if (source._geometry) {
  10126. source._geometry.applyToMesh(this);
  10127. }
  10128. // Deep copy
  10129. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton"], []);
  10130. // Material
  10131. this.material = source.material;
  10132. if (!doNotCloneChildren) {
  10133. for (var index = 0; index < scene.meshes.length; index++) {
  10134. var mesh = scene.meshes[index];
  10135. if (mesh.parent === source) {
  10136. // doNotCloneChildren is always going to be False
  10137. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  10138. }
  10139. }
  10140. }
  10141. for (index = 0; index < scene.particleSystems.length; index++) {
  10142. var system = scene.particleSystems[index];
  10143. if (system.emitter === source) {
  10144. system.clone(system.name, this);
  10145. }
  10146. }
  10147. this.computeWorldMatrix(true);
  10148. }
  10149. // Parent
  10150. if (parent !== null) {
  10151. this.parent = parent;
  10152. }
  10153. }
  10154. Object.defineProperty(Mesh, "FRONTSIDE", {
  10155. get: function () {
  10156. return Mesh._FRONTSIDE;
  10157. },
  10158. enumerable: true,
  10159. configurable: true
  10160. });
  10161. Object.defineProperty(Mesh, "BACKSIDE", {
  10162. get: function () {
  10163. return Mesh._BACKSIDE;
  10164. },
  10165. enumerable: true,
  10166. configurable: true
  10167. });
  10168. Object.defineProperty(Mesh, "DOUBLESIDE", {
  10169. get: function () {
  10170. return Mesh._DOUBLESIDE;
  10171. },
  10172. enumerable: true,
  10173. configurable: true
  10174. });
  10175. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  10176. get: function () {
  10177. return Mesh._DEFAULTSIDE;
  10178. },
  10179. enumerable: true,
  10180. configurable: true
  10181. });
  10182. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  10183. // Methods
  10184. get: function () {
  10185. return this._LODLevels.length > 0;
  10186. },
  10187. enumerable: true,
  10188. configurable: true
  10189. });
  10190. Mesh.prototype._sortLODLevels = function () {
  10191. this._LODLevels.sort(function (a, b) {
  10192. if (a.distance < b.distance) {
  10193. return 1;
  10194. }
  10195. if (a.distance > b.distance) {
  10196. return -1;
  10197. }
  10198. return 0;
  10199. });
  10200. };
  10201. /**
  10202. * Add a mesh as LOD level triggered at the given distance.
  10203. * @param {number} distance - the distance from the center of the object to show this level
  10204. * @param {BABYLON.Mesh} mesh - the mesh to be added as LOD level
  10205. * @return {BABYLON.Mesh} this mesh (for chaining)
  10206. */
  10207. Mesh.prototype.addLODLevel = function (distance, mesh) {
  10208. if (mesh && mesh._masterMesh) {
  10209. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  10210. return this;
  10211. }
  10212. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  10213. this._LODLevels.push(level);
  10214. if (mesh) {
  10215. mesh._masterMesh = this;
  10216. }
  10217. this._sortLODLevels();
  10218. return this;
  10219. };
  10220. /**
  10221. * Remove a mesh from the LOD array
  10222. * @param {BABYLON.Mesh} mesh - the mesh to be removed.
  10223. * @return {BABYLON.Mesh} this mesh (for chaining)
  10224. */
  10225. Mesh.prototype.removeLODLevel = function (mesh) {
  10226. for (var index = 0; index < this._LODLevels.length; index++) {
  10227. if (this._LODLevels[index].mesh === mesh) {
  10228. this._LODLevels.splice(index, 1);
  10229. if (mesh) {
  10230. mesh._masterMesh = null;
  10231. }
  10232. }
  10233. }
  10234. this._sortLODLevels();
  10235. return this;
  10236. };
  10237. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  10238. if (!this._LODLevels || this._LODLevels.length === 0) {
  10239. return this;
  10240. }
  10241. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.position).length();
  10242. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  10243. return this;
  10244. }
  10245. for (var index = 0; index < this._LODLevels.length; index++) {
  10246. var level = this._LODLevels[index];
  10247. if (level.distance < distanceToCamera) {
  10248. if (level.mesh) {
  10249. level.mesh._preActivate();
  10250. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  10251. }
  10252. return level.mesh;
  10253. }
  10254. }
  10255. return this;
  10256. };
  10257. Object.defineProperty(Mesh.prototype, "geometry", {
  10258. get: function () {
  10259. return this._geometry;
  10260. },
  10261. enumerable: true,
  10262. configurable: true
  10263. });
  10264. Mesh.prototype.getTotalVertices = function () {
  10265. if (!this._geometry) {
  10266. return 0;
  10267. }
  10268. return this._geometry.getTotalVertices();
  10269. };
  10270. Mesh.prototype.getVerticesData = function (kind) {
  10271. if (!this._geometry) {
  10272. return null;
  10273. }
  10274. return this._geometry.getVerticesData(kind);
  10275. };
  10276. Mesh.prototype.getVertexBuffer = function (kind) {
  10277. if (!this._geometry) {
  10278. return undefined;
  10279. }
  10280. return this._geometry.getVertexBuffer(kind);
  10281. };
  10282. Mesh.prototype.isVerticesDataPresent = function (kind) {
  10283. if (!this._geometry) {
  10284. if (this._delayInfo) {
  10285. return this._delayInfo.indexOf(kind) !== -1;
  10286. }
  10287. return false;
  10288. }
  10289. return this._geometry.isVerticesDataPresent(kind);
  10290. };
  10291. Mesh.prototype.getVerticesDataKinds = function () {
  10292. if (!this._geometry) {
  10293. var result = [];
  10294. if (this._delayInfo) {
  10295. for (var kind in this._delayInfo) {
  10296. result.push(kind);
  10297. }
  10298. }
  10299. return result;
  10300. }
  10301. return this._geometry.getVerticesDataKinds();
  10302. };
  10303. Mesh.prototype.getTotalIndices = function () {
  10304. if (!this._geometry) {
  10305. return 0;
  10306. }
  10307. return this._geometry.getTotalIndices();
  10308. };
  10309. Mesh.prototype.getIndices = function () {
  10310. if (!this._geometry) {
  10311. return [];
  10312. }
  10313. return this._geometry.getIndices();
  10314. };
  10315. Object.defineProperty(Mesh.prototype, "isBlocked", {
  10316. get: function () {
  10317. return this._masterMesh !== null && this._masterMesh !== undefined;
  10318. },
  10319. enumerable: true,
  10320. configurable: true
  10321. });
  10322. Mesh.prototype.isReady = function () {
  10323. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  10324. return false;
  10325. }
  10326. return _super.prototype.isReady.call(this);
  10327. };
  10328. Mesh.prototype.isDisposed = function () {
  10329. return this._isDisposed;
  10330. };
  10331. // Methods
  10332. Mesh.prototype._preActivate = function () {
  10333. var sceneRenderId = this.getScene().getRenderId();
  10334. if (this._preActivateId === sceneRenderId) {
  10335. return;
  10336. }
  10337. this._preActivateId = sceneRenderId;
  10338. this._visibleInstances = null;
  10339. };
  10340. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  10341. if (!this._visibleInstances) {
  10342. this._visibleInstances = {};
  10343. this._visibleInstances.defaultRenderId = renderId;
  10344. this._visibleInstances.selfDefaultRenderId = this._renderId;
  10345. }
  10346. if (!this._visibleInstances[renderId]) {
  10347. this._visibleInstances[renderId] = new Array();
  10348. }
  10349. this._visibleInstances[renderId].push(instance);
  10350. };
  10351. Mesh.prototype.refreshBoundingInfo = function () {
  10352. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  10353. if (data) {
  10354. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  10355. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  10356. }
  10357. if (this.subMeshes) {
  10358. for (var index = 0; index < this.subMeshes.length; index++) {
  10359. this.subMeshes[index].refreshBoundingInfo();
  10360. }
  10361. }
  10362. this._updateBoundingInfo();
  10363. };
  10364. Mesh.prototype._createGlobalSubMesh = function () {
  10365. var totalVertices = this.getTotalVertices();
  10366. if (!totalVertices || !this.getIndices()) {
  10367. return null;
  10368. }
  10369. this.releaseSubMeshes();
  10370. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  10371. };
  10372. Mesh.prototype.subdivide = function (count) {
  10373. if (count < 1) {
  10374. return;
  10375. }
  10376. var totalIndices = this.getTotalIndices();
  10377. var subdivisionSize = (totalIndices / count) | 0;
  10378. var offset = 0;
  10379. while (subdivisionSize % 3 !== 0) {
  10380. subdivisionSize++;
  10381. }
  10382. this.releaseSubMeshes();
  10383. for (var index = 0; index < count; index++) {
  10384. if (offset >= totalIndices) {
  10385. break;
  10386. }
  10387. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  10388. offset += subdivisionSize;
  10389. }
  10390. this.synchronizeInstances();
  10391. };
  10392. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  10393. if (kind instanceof Array) {
  10394. var temp = data;
  10395. data = kind;
  10396. kind = temp;
  10397. BABYLON.Tools.Warn("Deprecated usage of setVerticesData detected (since v1.12). Current signature is setVerticesData(kind, data, updatable).");
  10398. }
  10399. if (!this._geometry) {
  10400. var vertexData = new BABYLON.VertexData();
  10401. vertexData.set(data, kind);
  10402. var scene = this.getScene();
  10403. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  10404. }
  10405. else {
  10406. this._geometry.setVerticesData(kind, data, updatable, stride);
  10407. }
  10408. };
  10409. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  10410. if (!this._geometry) {
  10411. return;
  10412. }
  10413. if (!makeItUnique) {
  10414. this._geometry.updateVerticesData(kind, data, updateExtends);
  10415. }
  10416. else {
  10417. this.makeGeometryUnique();
  10418. this.updateVerticesData(kind, data, updateExtends, false);
  10419. }
  10420. };
  10421. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  10422. if (!this._geometry) {
  10423. return;
  10424. }
  10425. if (!makeItUnique) {
  10426. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  10427. }
  10428. else {
  10429. this.makeGeometryUnique();
  10430. this.updateVerticesDataDirectly(kind, data, offset, false);
  10431. }
  10432. };
  10433. Mesh.prototype.makeGeometryUnique = function () {
  10434. if (!this._geometry) {
  10435. return;
  10436. }
  10437. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  10438. geometry.applyToMesh(this);
  10439. };
  10440. Mesh.prototype.setIndices = function (indices, totalVertices) {
  10441. if (!this._geometry) {
  10442. var vertexData = new BABYLON.VertexData();
  10443. vertexData.indices = indices;
  10444. var scene = this.getScene();
  10445. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  10446. }
  10447. else {
  10448. this._geometry.setIndices(indices, totalVertices);
  10449. }
  10450. };
  10451. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  10452. var engine = this.getScene().getEngine();
  10453. // Wireframe
  10454. var indexToBind;
  10455. switch (fillMode) {
  10456. case BABYLON.Material.PointFillMode:
  10457. indexToBind = null;
  10458. break;
  10459. case BABYLON.Material.WireFrameFillMode:
  10460. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  10461. break;
  10462. default:
  10463. case BABYLON.Material.TriangleFillMode:
  10464. indexToBind = this._geometry.getIndexBuffer();
  10465. break;
  10466. }
  10467. // VBOs
  10468. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  10469. };
  10470. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  10471. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  10472. return;
  10473. }
  10474. var engine = this.getScene().getEngine();
  10475. switch (fillMode) {
  10476. case BABYLON.Material.PointFillMode:
  10477. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  10478. break;
  10479. case BABYLON.Material.WireFrameFillMode:
  10480. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  10481. break;
  10482. default:
  10483. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  10484. }
  10485. };
  10486. Mesh.prototype.registerBeforeRender = function (func) {
  10487. this._onBeforeRenderCallbacks.push(func);
  10488. };
  10489. Mesh.prototype.unregisterBeforeRender = function (func) {
  10490. var index = this._onBeforeRenderCallbacks.indexOf(func);
  10491. if (index > -1) {
  10492. this._onBeforeRenderCallbacks.splice(index, 1);
  10493. }
  10494. };
  10495. Mesh.prototype.registerAfterRender = function (func) {
  10496. this._onAfterRenderCallbacks.push(func);
  10497. };
  10498. Mesh.prototype.unregisterAfterRender = function (func) {
  10499. var index = this._onAfterRenderCallbacks.indexOf(func);
  10500. if (index > -1) {
  10501. this._onAfterRenderCallbacks.splice(index, 1);
  10502. }
  10503. };
  10504. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  10505. var scene = this.getScene();
  10506. this._batchCache.mustReturn = false;
  10507. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  10508. this._batchCache.visibleInstances[subMeshId] = null;
  10509. if (this._visibleInstances) {
  10510. var currentRenderId = scene.getRenderId();
  10511. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  10512. var selfRenderId = this._renderId;
  10513. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  10514. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  10515. currentRenderId = Math.max(this._visibleInstances.defaultRenderId, currentRenderId);
  10516. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  10517. }
  10518. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  10519. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  10520. this._batchCache.mustReturn = true;
  10521. return this._batchCache;
  10522. }
  10523. if (currentRenderId !== selfRenderId) {
  10524. this._batchCache.renderSelf[subMeshId] = false;
  10525. }
  10526. }
  10527. this._renderIdForInstances[subMeshId] = currentRenderId;
  10528. }
  10529. return this._batchCache;
  10530. };
  10531. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  10532. var visibleInstances = batch.visibleInstances[subMesh._id];
  10533. var matricesCount = visibleInstances.length + 1;
  10534. var bufferSize = matricesCount * 16 * 4;
  10535. while (this._instancesBufferSize < bufferSize) {
  10536. this._instancesBufferSize *= 2;
  10537. }
  10538. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  10539. if (this._worldMatricesInstancesBuffer) {
  10540. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  10541. }
  10542. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  10543. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  10544. }
  10545. var offset = 0;
  10546. var instancesCount = 0;
  10547. var world = this.getWorldMatrix();
  10548. if (batch.renderSelf[subMesh._id]) {
  10549. world.copyToArray(this._worldMatricesInstancesArray, offset);
  10550. offset += 16;
  10551. instancesCount++;
  10552. }
  10553. if (visibleInstances) {
  10554. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  10555. var instance = visibleInstances[instanceIndex];
  10556. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  10557. offset += 16;
  10558. instancesCount++;
  10559. }
  10560. }
  10561. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  10562. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  10563. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  10564. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  10565. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  10566. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  10567. this._draw(subMesh, fillMode, instancesCount);
  10568. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  10569. };
  10570. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw) {
  10571. var scene = this.getScene();
  10572. var engine = scene.getEngine();
  10573. if (hardwareInstancedRendering) {
  10574. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  10575. }
  10576. else {
  10577. if (batch.renderSelf[subMesh._id]) {
  10578. // Draw
  10579. if (onBeforeDraw) {
  10580. onBeforeDraw(false, this.getWorldMatrix());
  10581. }
  10582. this._draw(subMesh, fillMode);
  10583. }
  10584. if (batch.visibleInstances[subMesh._id]) {
  10585. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  10586. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  10587. // World
  10588. var world = instance.getWorldMatrix();
  10589. if (onBeforeDraw) {
  10590. onBeforeDraw(true, world);
  10591. }
  10592. // Draw
  10593. this._draw(subMesh, fillMode);
  10594. }
  10595. }
  10596. }
  10597. };
  10598. Mesh.prototype.render = function (subMesh) {
  10599. var scene = this.getScene();
  10600. // Managing instances
  10601. var batch = this._getInstancesRenderList(subMesh._id);
  10602. if (batch.mustReturn) {
  10603. return;
  10604. }
  10605. // Checking geometry state
  10606. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  10607. return;
  10608. }
  10609. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  10610. this._onBeforeRenderCallbacks[callbackIndex](this);
  10611. }
  10612. var engine = scene.getEngine();
  10613. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  10614. // Material
  10615. var effectiveMaterial = subMesh.getMaterial();
  10616. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  10617. return;
  10618. }
  10619. // Outline - step 1
  10620. var savedDepthWrite = engine.getDepthWrite();
  10621. if (this.renderOutline) {
  10622. engine.setDepthWrite(false);
  10623. scene.getOutlineRenderer().render(subMesh, batch);
  10624. engine.setDepthWrite(savedDepthWrite);
  10625. }
  10626. effectiveMaterial._preBind();
  10627. var effect = effectiveMaterial.getEffect();
  10628. // Bind
  10629. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  10630. this._bind(subMesh, effect, fillMode);
  10631. var world = this.getWorldMatrix();
  10632. effectiveMaterial.bind(world, this);
  10633. // Draw
  10634. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  10635. if (isInstance) {
  10636. effectiveMaterial.bindOnlyWorldMatrix(world);
  10637. }
  10638. });
  10639. // Unbind
  10640. effectiveMaterial.unbind();
  10641. // Outline - step 2
  10642. if (this.renderOutline && savedDepthWrite) {
  10643. engine.setDepthWrite(true);
  10644. engine.setColorWrite(false);
  10645. scene.getOutlineRenderer().render(subMesh, batch);
  10646. engine.setColorWrite(true);
  10647. }
  10648. // Overlay
  10649. if (this.renderOverlay) {
  10650. var currentMode = engine.getAlphaMode();
  10651. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  10652. scene.getOutlineRenderer().render(subMesh, batch, true);
  10653. engine.setAlphaMode(currentMode);
  10654. }
  10655. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  10656. this._onAfterRenderCallbacks[callbackIndex](this);
  10657. }
  10658. };
  10659. Mesh.prototype.getEmittedParticleSystems = function () {
  10660. var results = new Array();
  10661. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  10662. var particleSystem = this.getScene().particleSystems[index];
  10663. if (particleSystem.emitter === this) {
  10664. results.push(particleSystem);
  10665. }
  10666. }
  10667. return results;
  10668. };
  10669. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  10670. var results = new Array();
  10671. var descendants = this.getDescendants();
  10672. descendants.push(this);
  10673. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  10674. var particleSystem = this.getScene().particleSystems[index];
  10675. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  10676. results.push(particleSystem);
  10677. }
  10678. }
  10679. return results;
  10680. };
  10681. Mesh.prototype.getChildren = function () {
  10682. var results = [];
  10683. for (var index = 0; index < this.getScene().meshes.length; index++) {
  10684. var mesh = this.getScene().meshes[index];
  10685. if (mesh.parent === this) {
  10686. results.push(mesh);
  10687. }
  10688. }
  10689. return results;
  10690. };
  10691. Mesh.prototype._checkDelayState = function () {
  10692. var _this = this;
  10693. var that = this;
  10694. var scene = this.getScene();
  10695. if (this._geometry) {
  10696. this._geometry.load(scene);
  10697. }
  10698. else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  10699. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  10700. scene._addPendingData(that);
  10701. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  10702. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  10703. if (data instanceof ArrayBuffer) {
  10704. _this._delayLoadingFunction(data, _this);
  10705. }
  10706. else {
  10707. _this._delayLoadingFunction(JSON.parse(data), _this);
  10708. }
  10709. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  10710. scene._removePendingData(_this);
  10711. }, function () {
  10712. }, scene.database, getBinaryData);
  10713. }
  10714. };
  10715. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  10716. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  10717. return false;
  10718. }
  10719. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  10720. return false;
  10721. }
  10722. this._checkDelayState();
  10723. return true;
  10724. };
  10725. Mesh.prototype.setMaterialByID = function (id) {
  10726. var materials = this.getScene().materials;
  10727. for (var index = 0; index < materials.length; index++) {
  10728. if (materials[index].id === id) {
  10729. this.material = materials[index];
  10730. return;
  10731. }
  10732. }
  10733. // Multi
  10734. var multiMaterials = this.getScene().multiMaterials;
  10735. for (index = 0; index < multiMaterials.length; index++) {
  10736. if (multiMaterials[index].id === id) {
  10737. this.material = multiMaterials[index];
  10738. return;
  10739. }
  10740. }
  10741. };
  10742. Mesh.prototype.getAnimatables = function () {
  10743. var results = [];
  10744. if (this.material) {
  10745. results.push(this.material);
  10746. }
  10747. if (this.skeleton) {
  10748. results.push(this.skeleton);
  10749. }
  10750. return results;
  10751. };
  10752. // Geometry
  10753. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  10754. // Position
  10755. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  10756. return;
  10757. }
  10758. this._resetPointsArrayCache();
  10759. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  10760. var temp = [];
  10761. for (var index = 0; index < data.length; index += 3) {
  10762. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  10763. }
  10764. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  10765. // Normals
  10766. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  10767. return;
  10768. }
  10769. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  10770. for (index = 0; index < data.length; index += 3) {
  10771. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  10772. }
  10773. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  10774. };
  10775. // Cache
  10776. Mesh.prototype._resetPointsArrayCache = function () {
  10777. this._positions = null;
  10778. };
  10779. Mesh.prototype._generatePointsArray = function () {
  10780. if (this._positions)
  10781. return true;
  10782. this._positions = [];
  10783. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  10784. if (!data) {
  10785. return false;
  10786. }
  10787. for (var index = 0; index < data.length; index += 3) {
  10788. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  10789. }
  10790. return true;
  10791. };
  10792. // Clone
  10793. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  10794. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  10795. };
  10796. // Dispose
  10797. Mesh.prototype.dispose = function (doNotRecurse) {
  10798. if (this._geometry) {
  10799. this._geometry.releaseForMesh(this, true);
  10800. }
  10801. // Instances
  10802. if (this._worldMatricesInstancesBuffer) {
  10803. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  10804. this._worldMatricesInstancesBuffer = null;
  10805. }
  10806. while (this.instances.length) {
  10807. this.instances[0].dispose();
  10808. }
  10809. _super.prototype.dispose.call(this, doNotRecurse);
  10810. };
  10811. // Geometric tools
  10812. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  10813. var _this = this;
  10814. var scene = this.getScene();
  10815. var onload = function (img) {
  10816. // Getting height map data
  10817. var canvas = document.createElement("canvas");
  10818. var context = canvas.getContext("2d");
  10819. var heightMapWidth = img.width;
  10820. var heightMapHeight = img.height;
  10821. canvas.width = heightMapWidth;
  10822. canvas.height = heightMapHeight;
  10823. context.drawImage(img, 0, 0);
  10824. // Create VertexData from map data
  10825. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  10826. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  10827. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  10828. //execute success callback, if set
  10829. if (onSuccess) {
  10830. onSuccess(_this);
  10831. }
  10832. };
  10833. BABYLON.Tools.LoadImage(url, onload, function () {
  10834. }, scene.database);
  10835. };
  10836. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  10837. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  10838. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  10839. return;
  10840. }
  10841. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  10842. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  10843. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  10844. var position = BABYLON.Vector3.Zero();
  10845. var normal = BABYLON.Vector3.Zero();
  10846. var uv = BABYLON.Vector2.Zero();
  10847. for (var index = 0; index < positions.length; index += 3) {
  10848. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  10849. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  10850. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  10851. // Compute height
  10852. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  10853. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  10854. var pos = (u + v * heightMapWidth) * 4;
  10855. var r = buffer[pos] / 255.0;
  10856. var g = buffer[pos + 1] / 255.0;
  10857. var b = buffer[pos + 2] / 255.0;
  10858. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  10859. normal.normalize();
  10860. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  10861. position = position.add(normal);
  10862. position.toArray(positions, index);
  10863. }
  10864. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  10865. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  10866. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  10867. };
  10868. Mesh.prototype.convertToFlatShadedMesh = function () {
  10869. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  10870. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  10871. var kinds = this.getVerticesDataKinds();
  10872. var vbs = [];
  10873. var data = [];
  10874. var newdata = [];
  10875. var updatableNormals = false;
  10876. for (var kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  10877. var kind = kinds[kindIndex];
  10878. var vertexBuffer = this.getVertexBuffer(kind);
  10879. if (kind === BABYLON.VertexBuffer.NormalKind) {
  10880. updatableNormals = vertexBuffer.isUpdatable();
  10881. kinds.splice(kindIndex, 1);
  10882. kindIndex--;
  10883. continue;
  10884. }
  10885. vbs[kind] = vertexBuffer;
  10886. data[kind] = vbs[kind].getData();
  10887. newdata[kind] = [];
  10888. }
  10889. // Save previous submeshes
  10890. var previousSubmeshes = this.subMeshes.slice(0);
  10891. var indices = this.getIndices();
  10892. var totalIndices = this.getTotalIndices();
  10893. for (var index = 0; index < totalIndices; index++) {
  10894. var vertexIndex = indices[index];
  10895. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  10896. kind = kinds[kindIndex];
  10897. var stride = vbs[kind].getStrideSize();
  10898. for (var offset = 0; offset < stride; offset++) {
  10899. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  10900. }
  10901. }
  10902. }
  10903. // Updating faces & normal
  10904. var normals = [];
  10905. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  10906. for (index = 0; index < totalIndices; index += 3) {
  10907. indices[index] = index;
  10908. indices[index + 1] = index + 1;
  10909. indices[index + 2] = index + 2;
  10910. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  10911. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  10912. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  10913. var p1p2 = p1.subtract(p2);
  10914. var p3p2 = p3.subtract(p2);
  10915. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  10916. for (var localIndex = 0; localIndex < 3; localIndex++) {
  10917. normals.push(normal.x);
  10918. normals.push(normal.y);
  10919. normals.push(normal.z);
  10920. }
  10921. }
  10922. this.setIndices(indices);
  10923. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  10924. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  10925. kind = kinds[kindIndex];
  10926. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  10927. }
  10928. // Updating submeshes
  10929. this.releaseSubMeshes();
  10930. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  10931. var previousOne = previousSubmeshes[submeshIndex];
  10932. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  10933. }
  10934. this.synchronizeInstances();
  10935. };
  10936. // Instances
  10937. Mesh.prototype.createInstance = function (name) {
  10938. return new BABYLON.InstancedMesh(name, this);
  10939. };
  10940. Mesh.prototype.synchronizeInstances = function () {
  10941. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  10942. var instance = this.instances[instanceIndex];
  10943. instance._syncSubMeshes();
  10944. }
  10945. };
  10946. /**
  10947. * Simplify the mesh according to the given array of settings.
  10948. * Function will return immediately and will simplify async.
  10949. * @param settings a collection of simplification settings.
  10950. * @param parallelProcessing should all levels calculate parallel or one after the other.
  10951. * @param type the type of simplification to run.
  10952. * successCallback optional success callback to be called after the simplification finished processing all settings.
  10953. */
  10954. Mesh.prototype.simplify = function (settings, parallelProcessing, type, successCallback) {
  10955. var _this = this;
  10956. if (parallelProcessing === void 0) { parallelProcessing = true; }
  10957. if (type === void 0) { type = 0 /* QUADRATIC */; }
  10958. var getSimplifier = function () {
  10959. switch (type) {
  10960. case 0 /* QUADRATIC */:
  10961. default:
  10962. return new BABYLON.QuadraticErrorSimplification(_this);
  10963. }
  10964. };
  10965. if (parallelProcessing) {
  10966. //parallel simplifier
  10967. settings.forEach(function (setting) {
  10968. var simplifier = getSimplifier();
  10969. simplifier.simplify(setting, function (newMesh) {
  10970. _this.addLODLevel(setting.distance, newMesh);
  10971. //check if it is the last
  10972. if (setting.quality === settings[settings.length - 1].quality && successCallback) {
  10973. //all done, run the success callback.
  10974. successCallback();
  10975. }
  10976. });
  10977. });
  10978. }
  10979. else {
  10980. //single simplifier.
  10981. var simplifier = getSimplifier();
  10982. var runDecimation = function (setting, callback) {
  10983. simplifier.simplify(setting, function (newMesh) {
  10984. _this.addLODLevel(setting.distance, newMesh);
  10985. //run the next quality level
  10986. callback();
  10987. });
  10988. };
  10989. BABYLON.AsyncLoop.Run(settings.length, function (loop) {
  10990. runDecimation(settings[loop.index], function () {
  10991. loop.executeNext();
  10992. });
  10993. }, function () {
  10994. //execution ended, run the success callback.
  10995. if (successCallback) {
  10996. successCallback();
  10997. }
  10998. });
  10999. }
  11000. };
  11001. // Statics
  11002. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation) {
  11003. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11004. var ribbon = new Mesh(name, scene);
  11005. var vertexData = BABYLON.VertexData.CreateRibbon(pathArray, closeArray, closePath, offset, sideOrientation);
  11006. vertexData.applyToMesh(ribbon, updatable);
  11007. return ribbon;
  11008. };
  11009. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  11010. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11011. var box = new Mesh(name, scene);
  11012. var vertexData = BABYLON.VertexData.CreateBox(size, sideOrientation);
  11013. vertexData.applyToMesh(box, updatable);
  11014. return box;
  11015. };
  11016. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  11017. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11018. var sphere = new Mesh(name, scene);
  11019. var vertexData = BABYLON.VertexData.CreateSphere(segments, diameter, sideOrientation);
  11020. vertexData.applyToMesh(sphere, updatable);
  11021. return sphere;
  11022. };
  11023. // Cylinder and cone (Code inspired by SharpDX.org)
  11024. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  11025. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11026. // subdivisions is a new parameter, we need to support old signature
  11027. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  11028. if (scene !== undefined) {
  11029. updatable = scene;
  11030. }
  11031. scene = subdivisions;
  11032. subdivisions = 1;
  11033. }
  11034. var cylinder = new Mesh(name, scene);
  11035. var vertexData = BABYLON.VertexData.CreateCylinder(height, diameterTop, diameterBottom, tessellation, subdivisions);
  11036. vertexData.applyToMesh(cylinder, updatable);
  11037. return cylinder;
  11038. };
  11039. // Torus (Code from SharpDX.org)
  11040. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  11041. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11042. var torus = new Mesh(name, scene);
  11043. var vertexData = BABYLON.VertexData.CreateTorus(diameter, thickness, tessellation, sideOrientation);
  11044. vertexData.applyToMesh(torus, updatable);
  11045. return torus;
  11046. };
  11047. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  11048. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11049. var torusKnot = new Mesh(name, scene);
  11050. var vertexData = BABYLON.VertexData.CreateTorusKnot(radius, tube, radialSegments, tubularSegments, p, q, sideOrientation);
  11051. vertexData.applyToMesh(torusKnot, updatable);
  11052. return torusKnot;
  11053. };
  11054. // Lines
  11055. Mesh.CreateLines = function (name, points, scene, updatable) {
  11056. var lines = new BABYLON.LinesMesh(name, scene, updatable);
  11057. var vertexData = BABYLON.VertexData.CreateLines(points);
  11058. vertexData.applyToMesh(lines, updatable);
  11059. return lines;
  11060. };
  11061. // Plane & ground
  11062. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  11063. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11064. var plane = new Mesh(name, scene);
  11065. var vertexData = BABYLON.VertexData.CreatePlane(size, sideOrientation);
  11066. vertexData.applyToMesh(plane, updatable);
  11067. return plane;
  11068. };
  11069. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  11070. var ground = new BABYLON.GroundMesh(name, scene);
  11071. ground._setReady(false);
  11072. ground._subdivisions = subdivisions;
  11073. var vertexData = BABYLON.VertexData.CreateGround(width, height, subdivisions);
  11074. vertexData.applyToMesh(ground, updatable);
  11075. ground._setReady(true);
  11076. return ground;
  11077. };
  11078. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  11079. var tiledGround = new Mesh(name, scene);
  11080. var vertexData = BABYLON.VertexData.CreateTiledGround(xmin, zmin, xmax, zmax, subdivisions, precision);
  11081. vertexData.applyToMesh(tiledGround, updatable);
  11082. return tiledGround;
  11083. };
  11084. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  11085. var ground = new BABYLON.GroundMesh(name, scene);
  11086. ground._subdivisions = subdivisions;
  11087. ground._setReady(false);
  11088. var onload = function (img) {
  11089. // Getting height map data
  11090. var canvas = document.createElement("canvas");
  11091. var context = canvas.getContext("2d");
  11092. var heightMapWidth = img.width;
  11093. var heightMapHeight = img.height;
  11094. canvas.width = heightMapWidth;
  11095. canvas.height = heightMapHeight;
  11096. context.drawImage(img, 0, 0);
  11097. // Create VertexData from map data
  11098. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  11099. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  11100. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap(width, height, subdivisions, minHeight, maxHeight, buffer, heightMapWidth, heightMapHeight);
  11101. vertexData.applyToMesh(ground, updatable);
  11102. ground._setReady(true);
  11103. //execute ready callback, if set
  11104. if (onReady) {
  11105. onReady(ground);
  11106. }
  11107. };
  11108. BABYLON.Tools.LoadImage(url, onload, function () {
  11109. }, scene.database);
  11110. return ground;
  11111. };
  11112. Mesh.CreateTube = function (name, path, radius, tesselation, radiusFunction, scene, updatable, sideOrientation) {
  11113. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11114. var path3D = new BABYLON.Path3D(path);
  11115. var tangents = path3D.getTangents();
  11116. var normals = path3D.getNormals();
  11117. var distances = path3D.getDistances();
  11118. var pi2 = Math.PI * 2;
  11119. var step = pi2 / tesselation;
  11120. var returnRadius = function (i, distance) { return radius; };
  11121. var radiusFunctionFinal = radiusFunction || returnRadius;
  11122. var circlePaths = [];
  11123. var circlePath;
  11124. var rad;
  11125. var normal;
  11126. var rotated;
  11127. var rotationMatrix;
  11128. for (var i = 0; i < path.length; i++) {
  11129. rad = radiusFunctionFinal(i, distances[i]); // current radius
  11130. circlePath = []; // current circle array
  11131. normal = normals[i]; // current normal
  11132. for (var ang = 0; ang < pi2; ang += step) {
  11133. rotationMatrix = BABYLON.Matrix.RotationAxis(tangents[i], ang);
  11134. rotated = BABYLON.Vector3.TransformCoordinates(normal, rotationMatrix).scaleInPlace(rad).add(path[i]);
  11135. circlePath.push(rotated);
  11136. }
  11137. circlePaths.push(circlePath);
  11138. }
  11139. var tube = Mesh.CreateRibbon(name, circlePaths, false, true, 0, scene, updatable, sideOrientation);
  11140. return tube;
  11141. };
  11142. // Tools
  11143. Mesh.MinMax = function (meshes) {
  11144. var minVector = null;
  11145. var maxVector = null;
  11146. for (var i in meshes) {
  11147. var mesh = meshes[i];
  11148. var boundingBox = mesh.getBoundingInfo().boundingBox;
  11149. if (!minVector) {
  11150. minVector = boundingBox.minimumWorld;
  11151. maxVector = boundingBox.maximumWorld;
  11152. continue;
  11153. }
  11154. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  11155. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  11156. }
  11157. return {
  11158. min: minVector,
  11159. max: maxVector
  11160. };
  11161. };
  11162. Mesh.Center = function (meshesOrMinMaxVector) {
  11163. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  11164. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  11165. };
  11166. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices) {
  11167. if (disposeSource === void 0) { disposeSource = true; }
  11168. var source = meshes[0];
  11169. var material = source.material;
  11170. var scene = source.getScene();
  11171. if (!allow32BitsIndices) {
  11172. var totalVertices = 0;
  11173. for (var index = 0; index < meshes.length; index++) {
  11174. totalVertices += meshes[index].getTotalVertices();
  11175. if (totalVertices > 65536) {
  11176. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  11177. return null;
  11178. }
  11179. }
  11180. }
  11181. // Merge
  11182. var vertexData = BABYLON.VertexData.ExtractFromMesh(source);
  11183. vertexData.transform(source.getWorldMatrix());
  11184. for (index = 1; index < meshes.length; index++) {
  11185. var otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index]);
  11186. otherVertexData.transform(meshes[index].getWorldMatrix());
  11187. vertexData.merge(otherVertexData);
  11188. }
  11189. var newMesh = new Mesh(source.name + "_merged", scene);
  11190. vertexData.applyToMesh(newMesh);
  11191. // Setting properties
  11192. newMesh.material = material;
  11193. newMesh.checkCollisions = source.checkCollisions;
  11194. // Cleaning
  11195. if (disposeSource) {
  11196. for (index = 0; index < meshes.length; index++) {
  11197. meshes[index].dispose();
  11198. }
  11199. }
  11200. return newMesh;
  11201. };
  11202. // Consts
  11203. Mesh._FRONTSIDE = 0;
  11204. Mesh._BACKSIDE = 1;
  11205. Mesh._DOUBLESIDE = 2;
  11206. Mesh._DEFAULTSIDE = 0;
  11207. return Mesh;
  11208. })(BABYLON.AbstractMesh);
  11209. BABYLON.Mesh = Mesh;
  11210. })(BABYLON || (BABYLON = {}));
  11211. //# sourceMappingURL=babylon.mesh.js.map
  11212. var BABYLON;
  11213. (function (BABYLON) {
  11214. var GroundMesh = (function (_super) {
  11215. __extends(GroundMesh, _super);
  11216. function GroundMesh(name, scene) {
  11217. _super.call(this, name, scene);
  11218. this.generateOctree = false;
  11219. this._worldInverse = new BABYLON.Matrix();
  11220. }
  11221. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  11222. get: function () {
  11223. return this._subdivisions;
  11224. },
  11225. enumerable: true,
  11226. configurable: true
  11227. });
  11228. GroundMesh.prototype.optimize = function (chunksCount) {
  11229. this.subdivide(this._subdivisions);
  11230. this.createOrUpdateSubmeshesOctree(32);
  11231. };
  11232. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  11233. var ray = new BABYLON.Ray(new BABYLON.Vector3(x, this.getBoundingInfo().boundingBox.maximumWorld.y + 1, z), new BABYLON.Vector3(0, -1, 0));
  11234. this.getWorldMatrix().invertToRef(this._worldInverse);
  11235. ray = BABYLON.Ray.Transform(ray, this._worldInverse);
  11236. var pickInfo = this.intersects(ray);
  11237. if (pickInfo.hit) {
  11238. return pickInfo.pickedPoint.y;
  11239. }
  11240. return 0;
  11241. };
  11242. return GroundMesh;
  11243. })(BABYLON.Mesh);
  11244. BABYLON.GroundMesh = GroundMesh;
  11245. })(BABYLON || (BABYLON = {}));
  11246. //# sourceMappingURL=babylon.groundMesh.js.map
  11247. var BABYLON;
  11248. (function (BABYLON) {
  11249. /**
  11250. * Creates an instance based on a source mesh.
  11251. */
  11252. var InstancedMesh = (function (_super) {
  11253. __extends(InstancedMesh, _super);
  11254. function InstancedMesh(name, source) {
  11255. _super.call(this, name, source.getScene());
  11256. source.instances.push(this);
  11257. this._sourceMesh = source;
  11258. this.position.copyFrom(source.position);
  11259. this.rotation.copyFrom(source.rotation);
  11260. this.scaling.copyFrom(source.scaling);
  11261. if (source.rotationQuaternion) {
  11262. this.rotationQuaternion = source.rotationQuaternion.clone();
  11263. }
  11264. this.infiniteDistance = source.infiniteDistance;
  11265. this.setPivotMatrix(source.getPivotMatrix());
  11266. this.refreshBoundingInfo();
  11267. this._syncSubMeshes();
  11268. }
  11269. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  11270. // Methods
  11271. get: function () {
  11272. return this._sourceMesh.receiveShadows;
  11273. },
  11274. enumerable: true,
  11275. configurable: true
  11276. });
  11277. Object.defineProperty(InstancedMesh.prototype, "material", {
  11278. get: function () {
  11279. return this._sourceMesh.material;
  11280. },
  11281. enumerable: true,
  11282. configurable: true
  11283. });
  11284. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  11285. get: function () {
  11286. return this._sourceMesh.visibility;
  11287. },
  11288. enumerable: true,
  11289. configurable: true
  11290. });
  11291. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  11292. get: function () {
  11293. return this._sourceMesh.skeleton;
  11294. },
  11295. enumerable: true,
  11296. configurable: true
  11297. });
  11298. InstancedMesh.prototype.getTotalVertices = function () {
  11299. return this._sourceMesh.getTotalVertices();
  11300. };
  11301. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  11302. get: function () {
  11303. return this._sourceMesh;
  11304. },
  11305. enumerable: true,
  11306. configurable: true
  11307. });
  11308. InstancedMesh.prototype.getVerticesData = function (kind) {
  11309. return this._sourceMesh.getVerticesData(kind);
  11310. };
  11311. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  11312. return this._sourceMesh.isVerticesDataPresent(kind);
  11313. };
  11314. InstancedMesh.prototype.getIndices = function () {
  11315. return this._sourceMesh.getIndices();
  11316. };
  11317. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  11318. get: function () {
  11319. return this._sourceMesh._positions;
  11320. },
  11321. enumerable: true,
  11322. configurable: true
  11323. });
  11324. InstancedMesh.prototype.refreshBoundingInfo = function () {
  11325. var data = this._sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11326. if (data) {
  11327. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._sourceMesh.getTotalVertices());
  11328. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  11329. }
  11330. this._updateBoundingInfo();
  11331. };
  11332. InstancedMesh.prototype._preActivate = function () {
  11333. if (this._currentLOD) {
  11334. this._currentLOD._preActivate();
  11335. }
  11336. };
  11337. InstancedMesh.prototype._activate = function (renderId) {
  11338. if (this._currentLOD) {
  11339. this._currentLOD._registerInstanceForRenderId(this, renderId);
  11340. }
  11341. };
  11342. InstancedMesh.prototype.getLOD = function (camera) {
  11343. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  11344. if (this._currentLOD === this.sourceMesh) {
  11345. return this;
  11346. }
  11347. return this._currentLOD;
  11348. };
  11349. InstancedMesh.prototype._syncSubMeshes = function () {
  11350. this.releaseSubMeshes();
  11351. if (this._sourceMesh.subMeshes) {
  11352. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  11353. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  11354. }
  11355. }
  11356. };
  11357. InstancedMesh.prototype._generatePointsArray = function () {
  11358. return this._sourceMesh._generatePointsArray();
  11359. };
  11360. // Clone
  11361. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  11362. var result = this._sourceMesh.createInstance(name);
  11363. // Deep copy
  11364. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  11365. // Bounding info
  11366. this.refreshBoundingInfo();
  11367. // Parent
  11368. if (newParent) {
  11369. result.parent = newParent;
  11370. }
  11371. if (!doNotCloneChildren) {
  11372. for (var index = 0; index < this.getScene().meshes.length; index++) {
  11373. var mesh = this.getScene().meshes[index];
  11374. if (mesh.parent === this) {
  11375. mesh.clone(mesh.name, result);
  11376. }
  11377. }
  11378. }
  11379. result.computeWorldMatrix(true);
  11380. return result;
  11381. };
  11382. // Dispoe
  11383. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  11384. // Remove from mesh
  11385. var index = this._sourceMesh.instances.indexOf(this);
  11386. this._sourceMesh.instances.splice(index, 1);
  11387. _super.prototype.dispose.call(this, doNotRecurse);
  11388. };
  11389. return InstancedMesh;
  11390. })(BABYLON.AbstractMesh);
  11391. BABYLON.InstancedMesh = InstancedMesh;
  11392. })(BABYLON || (BABYLON = {}));
  11393. //# sourceMappingURL=babylon.instancedMesh.js.mapvar BABYLON;
  11394. (function (BABYLON) {
  11395. var SubMesh = (function () {
  11396. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  11397. if (createBoundingBox === void 0) { createBoundingBox = true; }
  11398. this.materialIndex = materialIndex;
  11399. this.verticesStart = verticesStart;
  11400. this.verticesCount = verticesCount;
  11401. this.indexStart = indexStart;
  11402. this.indexCount = indexCount;
  11403. this._renderId = 0;
  11404. this._mesh = mesh;
  11405. this._renderingMesh = renderingMesh || mesh;
  11406. mesh.subMeshes.push(this);
  11407. this._id = mesh.subMeshes.length - 1;
  11408. if (createBoundingBox) {
  11409. this.refreshBoundingInfo();
  11410. }
  11411. }
  11412. SubMesh.prototype.getBoundingInfo = function () {
  11413. return this._boundingInfo;
  11414. };
  11415. SubMesh.prototype.getMesh = function () {
  11416. return this._mesh;
  11417. };
  11418. SubMesh.prototype.getRenderingMesh = function () {
  11419. return this._renderingMesh;
  11420. };
  11421. SubMesh.prototype.getMaterial = function () {
  11422. var rootMaterial = this._renderingMesh.material;
  11423. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  11424. var multiMaterial = rootMaterial;
  11425. return multiMaterial.getSubMaterial(this.materialIndex);
  11426. }
  11427. if (!rootMaterial) {
  11428. return this._mesh.getScene().defaultMaterial;
  11429. }
  11430. return rootMaterial;
  11431. };
  11432. // Methods
  11433. SubMesh.prototype.refreshBoundingInfo = function () {
  11434. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11435. if (!data) {
  11436. this._boundingInfo = this._mesh._boundingInfo;
  11437. return;
  11438. }
  11439. var indices = this._renderingMesh.getIndices();
  11440. var extend;
  11441. if (this.indexStart === 0 && this.indexCount === indices.length) {
  11442. extend = BABYLON.Tools.ExtractMinAndMax(data, this.verticesStart, this.verticesCount);
  11443. }
  11444. else {
  11445. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
  11446. }
  11447. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  11448. };
  11449. SubMesh.prototype._checkCollision = function (collider) {
  11450. return this._boundingInfo._checkCollision(collider);
  11451. };
  11452. SubMesh.prototype.updateBoundingInfo = function (world) {
  11453. if (!this._boundingInfo) {
  11454. this.refreshBoundingInfo();
  11455. }
  11456. this._boundingInfo._update(world);
  11457. };
  11458. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  11459. return this._boundingInfo.isInFrustum(frustumPlanes);
  11460. };
  11461. SubMesh.prototype.render = function () {
  11462. this._renderingMesh.render(this);
  11463. };
  11464. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  11465. if (!this._linesIndexBuffer) {
  11466. var linesIndices = [];
  11467. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  11468. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  11469. }
  11470. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  11471. this.linesIndexCount = linesIndices.length;
  11472. }
  11473. return this._linesIndexBuffer;
  11474. };
  11475. SubMesh.prototype.canIntersects = function (ray) {
  11476. return ray.intersectsBox(this._boundingInfo.boundingBox);
  11477. };
  11478. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  11479. var intersectInfo = null;
  11480. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  11481. var p0 = positions[indices[index]];
  11482. var p1 = positions[indices[index + 1]];
  11483. var p2 = positions[indices[index + 2]];
  11484. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  11485. if (currentIntersectInfo) {
  11486. if (currentIntersectInfo.distance < 0) {
  11487. continue;
  11488. }
  11489. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  11490. intersectInfo = currentIntersectInfo;
  11491. intersectInfo.faceId = index / 3;
  11492. if (fastCheck) {
  11493. break;
  11494. }
  11495. }
  11496. }
  11497. }
  11498. return intersectInfo;
  11499. };
  11500. // Clone
  11501. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  11502. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  11503. result._boundingInfo = new BABYLON.BoundingInfo(this._boundingInfo.minimum, this._boundingInfo.maximum);
  11504. return result;
  11505. };
  11506. // Dispose
  11507. SubMesh.prototype.dispose = function () {
  11508. if (this._linesIndexBuffer) {
  11509. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  11510. this._linesIndexBuffer = null;
  11511. }
  11512. // Remove from mesh
  11513. var index = this._mesh.subMeshes.indexOf(this);
  11514. this._mesh.subMeshes.splice(index, 1);
  11515. };
  11516. // Statics
  11517. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  11518. var minVertexIndex = Number.MAX_VALUE;
  11519. var maxVertexIndex = -Number.MAX_VALUE;
  11520. renderingMesh = renderingMesh || mesh;
  11521. var indices = renderingMesh.getIndices();
  11522. for (var index = startIndex; index < startIndex + indexCount; index++) {
  11523. var vertexIndex = indices[index];
  11524. if (vertexIndex < minVertexIndex)
  11525. minVertexIndex = vertexIndex;
  11526. if (vertexIndex > maxVertexIndex)
  11527. maxVertexIndex = vertexIndex;
  11528. }
  11529. return new BABYLON.SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  11530. };
  11531. return SubMesh;
  11532. })();
  11533. BABYLON.SubMesh = SubMesh;
  11534. })(BABYLON || (BABYLON = {}));
  11535. //# sourceMappingURL=babylon.subMesh.js.mapvar BABYLON;
  11536. (function (BABYLON) {
  11537. var BaseTexture = (function () {
  11538. function BaseTexture(scene) {
  11539. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  11540. this.hasAlpha = false;
  11541. this.getAlphaFromRGB = false;
  11542. this.level = 1;
  11543. this.isCube = false;
  11544. this.isRenderTarget = false;
  11545. this.animations = new Array();
  11546. this.coordinatesIndex = 0;
  11547. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  11548. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  11549. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  11550. this.anisotropicFilteringLevel = 4;
  11551. this._scene = scene;
  11552. this._scene.textures.push(this);
  11553. }
  11554. BaseTexture.prototype.getScene = function () {
  11555. return this._scene;
  11556. };
  11557. BaseTexture.prototype.getTextureMatrix = function () {
  11558. return null;
  11559. };
  11560. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  11561. return null;
  11562. };
  11563. BaseTexture.prototype.getInternalTexture = function () {
  11564. return this._texture;
  11565. };
  11566. BaseTexture.prototype.isReady = function () {
  11567. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  11568. return true;
  11569. }
  11570. if (this._texture) {
  11571. return this._texture.isReady;
  11572. }
  11573. return false;
  11574. };
  11575. BaseTexture.prototype.getSize = function () {
  11576. if (this._texture._width) {
  11577. return { width: this._texture._width, height: this._texture._height };
  11578. }
  11579. if (this._texture._size) {
  11580. return { width: this._texture._size, height: this._texture._size };
  11581. }
  11582. return { width: 0, height: 0 };
  11583. };
  11584. BaseTexture.prototype.getBaseSize = function () {
  11585. if (!this.isReady())
  11586. return { width: 0, height: 0 };
  11587. if (this._texture._size) {
  11588. return { width: this._texture._size, height: this._texture._size };
  11589. }
  11590. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  11591. };
  11592. BaseTexture.prototype.scale = function (ratio) {
  11593. };
  11594. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  11595. get: function () {
  11596. return false;
  11597. },
  11598. enumerable: true,
  11599. configurable: true
  11600. });
  11601. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  11602. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  11603. for (var index = 0; index < texturesCache.length; index++) {
  11604. var texturesCacheEntry = texturesCache[index];
  11605. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  11606. texturesCache.splice(index, 1);
  11607. return;
  11608. }
  11609. }
  11610. };
  11611. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  11612. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  11613. for (var index = 0; index < texturesCache.length; index++) {
  11614. var texturesCacheEntry = texturesCache[index];
  11615. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  11616. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  11617. texturesCacheEntry.references++;
  11618. return texturesCacheEntry;
  11619. }
  11620. }
  11621. }
  11622. return null;
  11623. };
  11624. BaseTexture.prototype.delayLoad = function () {
  11625. };
  11626. BaseTexture.prototype.releaseInternalTexture = function () {
  11627. if (!this._texture) {
  11628. return;
  11629. }
  11630. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  11631. this._texture.references--;
  11632. // Final reference ?
  11633. if (this._texture.references === 0) {
  11634. var index = texturesCache.indexOf(this._texture);
  11635. texturesCache.splice(index, 1);
  11636. this._scene.getEngine()._releaseTexture(this._texture);
  11637. delete this._texture;
  11638. }
  11639. };
  11640. BaseTexture.prototype.clone = function () {
  11641. return null;
  11642. };
  11643. BaseTexture.prototype.dispose = function () {
  11644. // Remove from scene
  11645. var index = this._scene.textures.indexOf(this);
  11646. if (index >= 0) {
  11647. this._scene.textures.splice(index, 1);
  11648. }
  11649. if (this._texture === undefined) {
  11650. return;
  11651. }
  11652. this.releaseInternalTexture();
  11653. // Callback
  11654. if (this.onDispose) {
  11655. this.onDispose();
  11656. }
  11657. };
  11658. return BaseTexture;
  11659. })();
  11660. BABYLON.BaseTexture = BaseTexture;
  11661. })(BABYLON || (BABYLON = {}));
  11662. //# sourceMappingURL=babylon.baseTexture.js.mapvar BABYLON;
  11663. (function (BABYLON) {
  11664. var RenderingGroup = (function () {
  11665. function RenderingGroup(index, scene) {
  11666. this.index = index;
  11667. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  11668. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  11669. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  11670. this._scene = scene;
  11671. }
  11672. RenderingGroup.prototype.render = function (customRenderFunction) {
  11673. if (customRenderFunction) {
  11674. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  11675. return true;
  11676. }
  11677. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  11678. return false;
  11679. }
  11680. var engine = this._scene.getEngine();
  11681. // Opaque
  11682. var subIndex;
  11683. var submesh;
  11684. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  11685. submesh = this._opaqueSubMeshes.data[subIndex];
  11686. submesh.render();
  11687. }
  11688. // Alpha test
  11689. engine.setAlphaTesting(true);
  11690. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  11691. submesh = this._alphaTestSubMeshes.data[subIndex];
  11692. submesh.render();
  11693. }
  11694. engine.setAlphaTesting(false);
  11695. // Transparent
  11696. if (this._transparentSubMeshes.length) {
  11697. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  11698. submesh = this._transparentSubMeshes.data[subIndex];
  11699. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  11700. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.position).length();
  11701. }
  11702. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  11703. sortedArray.sort(function (a, b) {
  11704. // Alpha index first
  11705. if (a._alphaIndex > b._alphaIndex) {
  11706. return 1;
  11707. }
  11708. if (a._alphaIndex < b._alphaIndex) {
  11709. return -1;
  11710. }
  11711. // Then distance to camera
  11712. if (a._distanceToCamera < b._distanceToCamera) {
  11713. return 1;
  11714. }
  11715. if (a._distanceToCamera > b._distanceToCamera) {
  11716. return -1;
  11717. }
  11718. return 0;
  11719. });
  11720. // Rendering
  11721. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  11722. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  11723. submesh = sortedArray[subIndex];
  11724. submesh.render();
  11725. }
  11726. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  11727. }
  11728. return true;
  11729. };
  11730. RenderingGroup.prototype.prepare = function () {
  11731. this._opaqueSubMeshes.reset();
  11732. this._transparentSubMeshes.reset();
  11733. this._alphaTestSubMeshes.reset();
  11734. };
  11735. RenderingGroup.prototype.dispatch = function (subMesh) {
  11736. var material = subMesh.getMaterial();
  11737. var mesh = subMesh.getMesh();
  11738. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  11739. this._transparentSubMeshes.push(subMesh);
  11740. }
  11741. else if (material.needAlphaTesting()) {
  11742. this._alphaTestSubMeshes.push(subMesh);
  11743. }
  11744. else {
  11745. this._opaqueSubMeshes.push(subMesh); // Opaque
  11746. }
  11747. };
  11748. return RenderingGroup;
  11749. })();
  11750. BABYLON.RenderingGroup = RenderingGroup;
  11751. })(BABYLON || (BABYLON = {}));
  11752. //# sourceMappingURL=babylon.renderingGroup.js.mapvar BABYLON;
  11753. (function (BABYLON) {
  11754. var RenderingManager = (function () {
  11755. function RenderingManager(scene) {
  11756. this._renderingGroups = new Array();
  11757. this._scene = scene;
  11758. }
  11759. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  11760. if (this._scene._activeParticleSystems.length === 0) {
  11761. return;
  11762. }
  11763. // Particles
  11764. var beforeParticlesDate = BABYLON.Tools.Now;
  11765. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  11766. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  11767. if (particleSystem.renderingGroupId !== index) {
  11768. continue;
  11769. }
  11770. this._clearDepthBuffer();
  11771. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  11772. this._scene._activeParticles += particleSystem.render();
  11773. }
  11774. }
  11775. this._scene._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  11776. };
  11777. RenderingManager.prototype._renderSprites = function (index) {
  11778. if (!this._scene.spritesEnabled || this._scene.spriteManagers.length === 0) {
  11779. return;
  11780. }
  11781. // Sprites
  11782. var beforeSpritessDate = BABYLON.Tools.Now;
  11783. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  11784. var spriteManager = this._scene.spriteManagers[id];
  11785. if (spriteManager.renderingGroupId === index) {
  11786. this._clearDepthBuffer();
  11787. spriteManager.render();
  11788. }
  11789. }
  11790. this._scene._spritesDuration += BABYLON.Tools.Now - beforeSpritessDate;
  11791. };
  11792. RenderingManager.prototype._clearDepthBuffer = function () {
  11793. if (this._depthBufferAlreadyCleaned) {
  11794. return;
  11795. }
  11796. this._scene.getEngine().clear(0, false, true);
  11797. this._depthBufferAlreadyCleaned = true;
  11798. };
  11799. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  11800. for (var index = 0; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  11801. this._depthBufferAlreadyCleaned = false;
  11802. var renderingGroup = this._renderingGroups[index];
  11803. var needToStepBack = false;
  11804. if (renderingGroup) {
  11805. this._clearDepthBuffer();
  11806. if (!renderingGroup.render(customRenderFunction)) {
  11807. this._renderingGroups.splice(index, 1);
  11808. needToStepBack = true;
  11809. }
  11810. }
  11811. if (renderSprites) {
  11812. this._renderSprites(index);
  11813. }
  11814. if (renderParticles) {
  11815. this._renderParticles(index, activeMeshes);
  11816. }
  11817. if (needToStepBack) {
  11818. index--;
  11819. }
  11820. }
  11821. };
  11822. RenderingManager.prototype.reset = function () {
  11823. for (var index in this._renderingGroups) {
  11824. var renderingGroup = this._renderingGroups[index];
  11825. renderingGroup.prepare();
  11826. }
  11827. };
  11828. RenderingManager.prototype.dispatch = function (subMesh) {
  11829. var mesh = subMesh.getMesh();
  11830. var renderingGroupId = mesh.renderingGroupId || 0;
  11831. if (!this._renderingGroups[renderingGroupId]) {
  11832. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  11833. }
  11834. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  11835. };
  11836. RenderingManager.MAX_RENDERINGGROUPS = 4;
  11837. return RenderingManager;
  11838. })();
  11839. BABYLON.RenderingManager = RenderingManager;
  11840. })(BABYLON || (BABYLON = {}));
  11841. //# sourceMappingURL=babylon.renderingManager.js.map
  11842. var BABYLON;
  11843. (function (BABYLON) {
  11844. var Texture = (function (_super) {
  11845. __extends(Texture, _super);
  11846. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  11847. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  11848. if (onLoad === void 0) { onLoad = null; }
  11849. if (onError === void 0) { onError = null; }
  11850. if (buffer === void 0) { buffer = null; }
  11851. if (deleteBuffer === void 0) { deleteBuffer = false; }
  11852. _super.call(this, scene);
  11853. this.uOffset = 0;
  11854. this.vOffset = 0;
  11855. this.uScale = 1.0;
  11856. this.vScale = 1.0;
  11857. this.uAng = 0;
  11858. this.vAng = 0;
  11859. this.wAng = 0;
  11860. this.name = url;
  11861. this.url = url;
  11862. this._noMipmap = noMipmap;
  11863. this._invertY = invertY;
  11864. this._samplingMode = samplingMode;
  11865. this._buffer = buffer;
  11866. this._deleteBuffer = deleteBuffer;
  11867. if (!url) {
  11868. return;
  11869. }
  11870. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  11871. if (!this._texture) {
  11872. if (!scene.useDelayedTextureLoading) {
  11873. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  11874. if (deleteBuffer) {
  11875. delete this._buffer;
  11876. }
  11877. }
  11878. else {
  11879. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  11880. }
  11881. }
  11882. }
  11883. Texture.prototype.delayLoad = function () {
  11884. if (this.delayLoadState != BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  11885. return;
  11886. }
  11887. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  11888. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  11889. if (!this._texture) {
  11890. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, null, null, this._buffer);
  11891. if (this._deleteBuffer) {
  11892. delete this._buffer;
  11893. }
  11894. }
  11895. };
  11896. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  11897. x -= this.uOffset + 0.5;
  11898. y -= this.vOffset + 0.5;
  11899. z -= 0.5;
  11900. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  11901. t.x *= this.uScale;
  11902. t.y *= this.vScale;
  11903. t.x += 0.5;
  11904. t.y += 0.5;
  11905. t.z += 0.5;
  11906. };
  11907. Texture.prototype.getTextureMatrix = function () {
  11908. 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) {
  11909. return this._cachedTextureMatrix;
  11910. }
  11911. this._cachedUOffset = this.uOffset;
  11912. this._cachedVOffset = this.vOffset;
  11913. this._cachedUScale = this.uScale;
  11914. this._cachedVScale = this.vScale;
  11915. this._cachedUAng = this.uAng;
  11916. this._cachedVAng = this.vAng;
  11917. this._cachedWAng = this.wAng;
  11918. if (!this._cachedTextureMatrix) {
  11919. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  11920. this._rowGenerationMatrix = new BABYLON.Matrix();
  11921. this._t0 = BABYLON.Vector3.Zero();
  11922. this._t1 = BABYLON.Vector3.Zero();
  11923. this._t2 = BABYLON.Vector3.Zero();
  11924. }
  11925. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  11926. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  11927. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  11928. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  11929. this._t1.subtractInPlace(this._t0);
  11930. this._t2.subtractInPlace(this._t0);
  11931. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  11932. this._cachedTextureMatrix.m[0] = this._t1.x;
  11933. this._cachedTextureMatrix.m[1] = this._t1.y;
  11934. this._cachedTextureMatrix.m[2] = this._t1.z;
  11935. this._cachedTextureMatrix.m[4] = this._t2.x;
  11936. this._cachedTextureMatrix.m[5] = this._t2.y;
  11937. this._cachedTextureMatrix.m[6] = this._t2.z;
  11938. this._cachedTextureMatrix.m[8] = this._t0.x;
  11939. this._cachedTextureMatrix.m[9] = this._t0.y;
  11940. this._cachedTextureMatrix.m[10] = this._t0.z;
  11941. return this._cachedTextureMatrix;
  11942. };
  11943. Texture.prototype.getReflectionTextureMatrix = function () {
  11944. if (this.uOffset === this._cachedUOffset && this.vOffset === this._cachedVOffset && this.uScale === this._cachedUScale && this.vScale === this._cachedVScale && this.coordinatesMode === this._cachedCoordinatesMode) {
  11945. return this._cachedTextureMatrix;
  11946. }
  11947. if (!this._cachedTextureMatrix) {
  11948. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  11949. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  11950. }
  11951. this._cachedCoordinatesMode = this.coordinatesMode;
  11952. switch (this.coordinatesMode) {
  11953. case BABYLON.Texture.SPHERICAL_MODE:
  11954. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  11955. this._cachedTextureMatrix[0] = -0.5 * this.uScale;
  11956. this._cachedTextureMatrix[5] = -0.5 * this.vScale;
  11957. this._cachedTextureMatrix[12] = 0.5 + this.uOffset;
  11958. this._cachedTextureMatrix[13] = 0.5 + this.vOffset;
  11959. break;
  11960. case BABYLON.Texture.PLANAR_MODE:
  11961. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  11962. this._cachedTextureMatrix[0] = this.uScale;
  11963. this._cachedTextureMatrix[5] = this.vScale;
  11964. this._cachedTextureMatrix[12] = this.uOffset;
  11965. this._cachedTextureMatrix[13] = this.vOffset;
  11966. break;
  11967. case BABYLON.Texture.PROJECTION_MODE:
  11968. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  11969. this._projectionModeMatrix.m[0] = 0.5;
  11970. this._projectionModeMatrix.m[5] = -0.5;
  11971. this._projectionModeMatrix.m[10] = 0.0;
  11972. this._projectionModeMatrix.m[12] = 0.5;
  11973. this._projectionModeMatrix.m[13] = 0.5;
  11974. this._projectionModeMatrix.m[14] = 1.0;
  11975. this._projectionModeMatrix.m[15] = 1.0;
  11976. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  11977. break;
  11978. default:
  11979. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  11980. break;
  11981. }
  11982. return this._cachedTextureMatrix;
  11983. };
  11984. Texture.prototype.clone = function () {
  11985. var newTexture = new BABYLON.Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY, this._samplingMode);
  11986. // Base texture
  11987. newTexture.hasAlpha = this.hasAlpha;
  11988. newTexture.level = this.level;
  11989. newTexture.wrapU = this.wrapU;
  11990. newTexture.wrapV = this.wrapV;
  11991. newTexture.coordinatesIndex = this.coordinatesIndex;
  11992. newTexture.coordinatesMode = this.coordinatesMode;
  11993. // Texture
  11994. newTexture.uOffset = this.uOffset;
  11995. newTexture.vOffset = this.vOffset;
  11996. newTexture.uScale = this.uScale;
  11997. newTexture.vScale = this.vScale;
  11998. newTexture.uAng = this.uAng;
  11999. newTexture.vAng = this.vAng;
  12000. newTexture.wAng = this.wAng;
  12001. return newTexture;
  12002. };
  12003. // Statics
  12004. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  12005. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  12006. if (onLoad === void 0) { onLoad = null; }
  12007. if (onError === void 0) { onError = null; }
  12008. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  12009. };
  12010. // Constants
  12011. Texture.NEAREST_SAMPLINGMODE = 1;
  12012. Texture.BILINEAR_SAMPLINGMODE = 2;
  12013. Texture.TRILINEAR_SAMPLINGMODE = 3;
  12014. Texture.EXPLICIT_MODE = 0;
  12015. Texture.SPHERICAL_MODE = 1;
  12016. Texture.PLANAR_MODE = 2;
  12017. Texture.CUBIC_MODE = 3;
  12018. Texture.PROJECTION_MODE = 4;
  12019. Texture.SKYBOX_MODE = 5;
  12020. Texture.CLAMP_ADDRESSMODE = 0;
  12021. Texture.WRAP_ADDRESSMODE = 1;
  12022. Texture.MIRROR_ADDRESSMODE = 2;
  12023. return Texture;
  12024. })(BABYLON.BaseTexture);
  12025. BABYLON.Texture = Texture;
  12026. })(BABYLON || (BABYLON = {}));
  12027. //# sourceMappingURL=babylon.texture.js.map
  12028. var BABYLON;
  12029. (function (BABYLON) {
  12030. var CubeTexture = (function (_super) {
  12031. __extends(CubeTexture, _super);
  12032. function CubeTexture(rootUrl, scene, extensions, noMipmap) {
  12033. _super.call(this, scene);
  12034. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  12035. this.name = rootUrl;
  12036. this.url = rootUrl;
  12037. this._noMipmap = noMipmap;
  12038. this.hasAlpha = false;
  12039. this._texture = this._getFromCache(rootUrl, noMipmap);
  12040. if (!extensions) {
  12041. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  12042. }
  12043. this._extensions = extensions;
  12044. if (!this._texture) {
  12045. if (!scene.useDelayedTextureLoading) {
  12046. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, extensions, noMipmap);
  12047. }
  12048. else {
  12049. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  12050. }
  12051. }
  12052. this.isCube = true;
  12053. this._textureMatrix = BABYLON.Matrix.Identity();
  12054. }
  12055. CubeTexture.prototype.clone = function () {
  12056. var newTexture = new CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap);
  12057. // Base texture
  12058. newTexture.level = this.level;
  12059. newTexture.wrapU = this.wrapU;
  12060. newTexture.wrapV = this.wrapV;
  12061. newTexture.coordinatesIndex = this.coordinatesIndex;
  12062. newTexture.coordinatesMode = this.coordinatesMode;
  12063. return newTexture;
  12064. };
  12065. // Methods
  12066. CubeTexture.prototype.delayLoad = function () {
  12067. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  12068. return;
  12069. }
  12070. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  12071. this._texture = this._getFromCache(this.url, this._noMipmap);
  12072. if (!this._texture) {
  12073. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  12074. }
  12075. };
  12076. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  12077. return this._textureMatrix;
  12078. };
  12079. return CubeTexture;
  12080. })(BABYLON.BaseTexture);
  12081. BABYLON.CubeTexture = CubeTexture;
  12082. })(BABYLON || (BABYLON = {}));
  12083. //# sourceMappingURL=babylon.cubeTexture.js.map
  12084. var BABYLON;
  12085. (function (BABYLON) {
  12086. var RenderTargetTexture = (function (_super) {
  12087. __extends(RenderTargetTexture, _super);
  12088. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type) {
  12089. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  12090. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  12091. _super.call(this, null, scene, !generateMipMaps);
  12092. this.renderList = new Array();
  12093. this.renderParticles = true;
  12094. this.renderSprites = false;
  12095. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  12096. this._currentRefreshId = -1;
  12097. this._refreshRate = 1;
  12098. this.name = name;
  12099. this.isRenderTarget = true;
  12100. this._size = size;
  12101. this._generateMipMaps = generateMipMaps;
  12102. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  12103. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, type: type });
  12104. // Rendering groups
  12105. this._renderingManager = new BABYLON.RenderingManager(scene);
  12106. }
  12107. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  12108. this._currentRefreshId = -1;
  12109. };
  12110. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  12111. get: function () {
  12112. return this._refreshRate;
  12113. },
  12114. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  12115. set: function (value) {
  12116. this._refreshRate = value;
  12117. this.resetRefreshCounter();
  12118. },
  12119. enumerable: true,
  12120. configurable: true
  12121. });
  12122. RenderTargetTexture.prototype._shouldRender = function () {
  12123. if (this._currentRefreshId === -1) {
  12124. this._currentRefreshId = 1;
  12125. return true;
  12126. }
  12127. if (this.refreshRate === this._currentRefreshId) {
  12128. this._currentRefreshId = 1;
  12129. return true;
  12130. }
  12131. this._currentRefreshId++;
  12132. return false;
  12133. };
  12134. RenderTargetTexture.prototype.isReady = function () {
  12135. if (!this.getScene().renderTargetsEnabled) {
  12136. return false;
  12137. }
  12138. return _super.prototype.isReady.call(this);
  12139. };
  12140. RenderTargetTexture.prototype.getRenderSize = function () {
  12141. return this._size;
  12142. };
  12143. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  12144. get: function () {
  12145. return true;
  12146. },
  12147. enumerable: true,
  12148. configurable: true
  12149. });
  12150. RenderTargetTexture.prototype.scale = function (ratio) {
  12151. var newSize = this._size * ratio;
  12152. this.resize(newSize, this._generateMipMaps);
  12153. };
  12154. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  12155. this.releaseInternalTexture();
  12156. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  12157. };
  12158. RenderTargetTexture.prototype.render = function (useCameraPostProcess) {
  12159. var scene = this.getScene();
  12160. var engine = scene.getEngine();
  12161. if (this._waitingRenderList) {
  12162. this.renderList = [];
  12163. for (var index = 0; index < this._waitingRenderList.length; index++) {
  12164. var id = this._waitingRenderList[index];
  12165. this.renderList.push(scene.getMeshByID(id));
  12166. }
  12167. delete this._waitingRenderList;
  12168. }
  12169. if (this.renderList && this.renderList.length === 0) {
  12170. return;
  12171. }
  12172. // Bind
  12173. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  12174. engine.bindFramebuffer(this._texture);
  12175. }
  12176. this._renderingManager.reset();
  12177. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  12178. for (var meshIndex = 0; meshIndex < currentRenderList.length; meshIndex++) {
  12179. var mesh = currentRenderList[meshIndex];
  12180. if (mesh) {
  12181. if (!mesh.isReady()) {
  12182. // Reset _currentRefreshId
  12183. this.resetRefreshCounter();
  12184. continue;
  12185. }
  12186. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  12187. mesh._activate(scene.getRenderId());
  12188. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  12189. var subMesh = mesh.subMeshes[subIndex];
  12190. scene._activeVertices += subMesh.indexCount;
  12191. this._renderingManager.dispatch(subMesh);
  12192. }
  12193. }
  12194. }
  12195. }
  12196. if (this.onBeforeRender) {
  12197. this.onBeforeRender();
  12198. }
  12199. // Clear
  12200. engine.clear(scene.clearColor, true, true);
  12201. if (!this._doNotChangeAspectRatio) {
  12202. scene.updateTransformMatrix(true);
  12203. }
  12204. // Render
  12205. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  12206. if (useCameraPostProcess) {
  12207. scene.postProcessManager._finalizeFrame(false, this._texture);
  12208. }
  12209. if (!this._doNotChangeAspectRatio) {
  12210. scene.updateTransformMatrix(true);
  12211. }
  12212. if (this.onAfterRender) {
  12213. this.onAfterRender();
  12214. }
  12215. // Unbind
  12216. engine.unBindFramebuffer(this._texture);
  12217. };
  12218. RenderTargetTexture.prototype.clone = function () {
  12219. var textureSize = this.getSize();
  12220. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  12221. // Base texture
  12222. newTexture.hasAlpha = this.hasAlpha;
  12223. newTexture.level = this.level;
  12224. // RenderTarget Texture
  12225. newTexture.coordinatesMode = this.coordinatesMode;
  12226. newTexture.renderList = this.renderList.slice(0);
  12227. return newTexture;
  12228. };
  12229. return RenderTargetTexture;
  12230. })(BABYLON.Texture);
  12231. BABYLON.RenderTargetTexture = RenderTargetTexture;
  12232. })(BABYLON || (BABYLON = {}));
  12233. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  12234. var BABYLON;
  12235. (function (BABYLON) {
  12236. var ProceduralTexture = (function (_super) {
  12237. __extends(ProceduralTexture, _super);
  12238. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps) {
  12239. if (generateMipMaps === void 0) { generateMipMaps = true; }
  12240. _super.call(this, null, scene, !generateMipMaps);
  12241. this._currentRefreshId = -1;
  12242. this._refreshRate = 1;
  12243. this._vertexDeclaration = [2];
  12244. this._vertexStrideSize = 2 * 4;
  12245. this._uniforms = new Array();
  12246. this._samplers = new Array();
  12247. this._textures = new Array();
  12248. this._floats = new Array();
  12249. this._floatsArrays = {};
  12250. this._colors3 = new Array();
  12251. this._colors4 = new Array();
  12252. this._vectors2 = new Array();
  12253. this._vectors3 = new Array();
  12254. this._matrices = new Array();
  12255. this._fallbackTextureUsed = false;
  12256. scene._proceduralTextures.push(this);
  12257. this.name = name;
  12258. this.isRenderTarget = true;
  12259. this._size = size;
  12260. this._generateMipMaps = generateMipMaps;
  12261. this.setFragment(fragment);
  12262. this._fallbackTexture = fallbackTexture;
  12263. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  12264. // VBO
  12265. var vertices = [];
  12266. vertices.push(1, 1);
  12267. vertices.push(-1, 1);
  12268. vertices.push(-1, -1);
  12269. vertices.push(1, -1);
  12270. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  12271. // Indices
  12272. var indices = [];
  12273. indices.push(0);
  12274. indices.push(1);
  12275. indices.push(2);
  12276. indices.push(0);
  12277. indices.push(2);
  12278. indices.push(3);
  12279. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  12280. }
  12281. ProceduralTexture.prototype.reset = function () {
  12282. if (this._effect === undefined) {
  12283. return;
  12284. }
  12285. var engine = this.getScene().getEngine();
  12286. engine._releaseEffect(this._effect);
  12287. };
  12288. ProceduralTexture.prototype.isReady = function () {
  12289. var _this = this;
  12290. var engine = this.getScene().getEngine();
  12291. var shaders;
  12292. if (!this._fragment) {
  12293. return false;
  12294. }
  12295. if (this._fallbackTextureUsed) {
  12296. return true;
  12297. }
  12298. if (this._fragment.fragmentElement !== undefined) {
  12299. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  12300. }
  12301. else {
  12302. shaders = { vertex: "procedural", fragment: this._fragment };
  12303. }
  12304. this._effect = engine.createEffect(shaders, ["position"], this._uniforms, this._samplers, "", null, null, function () {
  12305. _this.releaseInternalTexture();
  12306. if (_this._fallbackTexture) {
  12307. _this._texture = _this._fallbackTexture._texture;
  12308. _this._texture.references++;
  12309. }
  12310. _this._fallbackTextureUsed = true;
  12311. });
  12312. return this._effect.isReady();
  12313. };
  12314. ProceduralTexture.prototype.resetRefreshCounter = function () {
  12315. this._currentRefreshId = -1;
  12316. };
  12317. ProceduralTexture.prototype.setFragment = function (fragment) {
  12318. this._fragment = fragment;
  12319. };
  12320. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  12321. get: function () {
  12322. return this._refreshRate;
  12323. },
  12324. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  12325. set: function (value) {
  12326. this._refreshRate = value;
  12327. this.resetRefreshCounter();
  12328. },
  12329. enumerable: true,
  12330. configurable: true
  12331. });
  12332. ProceduralTexture.prototype._shouldRender = function () {
  12333. if (!this.isReady() || !this._texture) {
  12334. return false;
  12335. }
  12336. if (this._fallbackTextureUsed) {
  12337. return false;
  12338. }
  12339. if (this._currentRefreshId === -1) {
  12340. this._currentRefreshId = 1;
  12341. return true;
  12342. }
  12343. if (this.refreshRate === this._currentRefreshId) {
  12344. this._currentRefreshId = 1;
  12345. return true;
  12346. }
  12347. this._currentRefreshId++;
  12348. return false;
  12349. };
  12350. ProceduralTexture.prototype.getRenderSize = function () {
  12351. return this._size;
  12352. };
  12353. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  12354. if (this._fallbackTextureUsed) {
  12355. return;
  12356. }
  12357. this.releaseInternalTexture();
  12358. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  12359. };
  12360. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  12361. if (this._uniforms.indexOf(uniformName) === -1) {
  12362. this._uniforms.push(uniformName);
  12363. }
  12364. };
  12365. ProceduralTexture.prototype.setTexture = function (name, texture) {
  12366. if (this._samplers.indexOf(name) === -1) {
  12367. this._samplers.push(name);
  12368. }
  12369. this._textures[name] = texture;
  12370. return this;
  12371. };
  12372. ProceduralTexture.prototype.setFloat = function (name, value) {
  12373. this._checkUniform(name);
  12374. this._floats[name] = value;
  12375. return this;
  12376. };
  12377. ProceduralTexture.prototype.setFloats = function (name, value) {
  12378. this._checkUniform(name);
  12379. this._floatsArrays[name] = value;
  12380. return this;
  12381. };
  12382. ProceduralTexture.prototype.setColor3 = function (name, value) {
  12383. this._checkUniform(name);
  12384. this._colors3[name] = value;
  12385. return this;
  12386. };
  12387. ProceduralTexture.prototype.setColor4 = function (name, value) {
  12388. this._checkUniform(name);
  12389. this._colors4[name] = value;
  12390. return this;
  12391. };
  12392. ProceduralTexture.prototype.setVector2 = function (name, value) {
  12393. this._checkUniform(name);
  12394. this._vectors2[name] = value;
  12395. return this;
  12396. };
  12397. ProceduralTexture.prototype.setVector3 = function (name, value) {
  12398. this._checkUniform(name);
  12399. this._vectors3[name] = value;
  12400. return this;
  12401. };
  12402. ProceduralTexture.prototype.setMatrix = function (name, value) {
  12403. this._checkUniform(name);
  12404. this._matrices[name] = value;
  12405. return this;
  12406. };
  12407. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  12408. var scene = this.getScene();
  12409. var engine = scene.getEngine();
  12410. engine.bindFramebuffer(this._texture);
  12411. // Clear
  12412. engine.clear(scene.clearColor, true, true);
  12413. // Render
  12414. engine.enableEffect(this._effect);
  12415. engine.setState(false);
  12416. for (var name in this._textures) {
  12417. this._effect.setTexture(name, this._textures[name]);
  12418. }
  12419. for (name in this._floats) {
  12420. this._effect.setFloat(name, this._floats[name]);
  12421. }
  12422. for (name in this._floatsArrays) {
  12423. this._effect.setArray(name, this._floatsArrays[name]);
  12424. }
  12425. for (name in this._colors3) {
  12426. this._effect.setColor3(name, this._colors3[name]);
  12427. }
  12428. for (name in this._colors4) {
  12429. var color = this._colors4[name];
  12430. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  12431. }
  12432. for (name in this._vectors2) {
  12433. this._effect.setVector2(name, this._vectors2[name]);
  12434. }
  12435. for (name in this._vectors3) {
  12436. this._effect.setVector3(name, this._vectors3[name]);
  12437. }
  12438. for (name in this._matrices) {
  12439. this._effect.setMatrix(name, this._matrices[name]);
  12440. }
  12441. // VBOs
  12442. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  12443. // Draw order
  12444. engine.draw(true, 0, 6);
  12445. // Unbind
  12446. engine.unBindFramebuffer(this._texture);
  12447. };
  12448. ProceduralTexture.prototype.clone = function () {
  12449. var textureSize = this.getSize();
  12450. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  12451. // Base texture
  12452. newTexture.hasAlpha = this.hasAlpha;
  12453. newTexture.level = this.level;
  12454. // RenderTarget Texture
  12455. newTexture.coordinatesMode = this.coordinatesMode;
  12456. return newTexture;
  12457. };
  12458. ProceduralTexture.prototype.dispose = function () {
  12459. var index = this.getScene()._proceduralTextures.indexOf(this);
  12460. if (index >= 0) {
  12461. this.getScene()._proceduralTextures.splice(index, 1);
  12462. }
  12463. _super.prototype.dispose.call(this);
  12464. };
  12465. return ProceduralTexture;
  12466. })(BABYLON.Texture);
  12467. BABYLON.ProceduralTexture = ProceduralTexture;
  12468. })(BABYLON || (BABYLON = {}));
  12469. //# sourceMappingURL=babylon.proceduralTexture.js.map
  12470. var BABYLON;
  12471. (function (BABYLON) {
  12472. var WoodProceduralTexture = (function (_super) {
  12473. __extends(WoodProceduralTexture, _super);
  12474. function WoodProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  12475. _super.call(this, name, size, "wood", scene, fallbackTexture, generateMipMaps);
  12476. this._ampScale = 100.0;
  12477. this._woodColor = new BABYLON.Color3(0.32, 0.17, 0.09);
  12478. this.updateShaderUniforms();
  12479. this.refreshRate = 0;
  12480. }
  12481. WoodProceduralTexture.prototype.updateShaderUniforms = function () {
  12482. this.setFloat("ampScale", this._ampScale);
  12483. this.setColor3("woodColor", this._woodColor);
  12484. };
  12485. Object.defineProperty(WoodProceduralTexture.prototype, "ampScale", {
  12486. get: function () {
  12487. return this._ampScale;
  12488. },
  12489. set: function (value) {
  12490. this._ampScale = value;
  12491. this.updateShaderUniforms();
  12492. },
  12493. enumerable: true,
  12494. configurable: true
  12495. });
  12496. Object.defineProperty(WoodProceduralTexture.prototype, "woodColor", {
  12497. get: function () {
  12498. return this._woodColor;
  12499. },
  12500. set: function (value) {
  12501. this._woodColor = value;
  12502. this.updateShaderUniforms();
  12503. },
  12504. enumerable: true,
  12505. configurable: true
  12506. });
  12507. return WoodProceduralTexture;
  12508. })(BABYLON.ProceduralTexture);
  12509. BABYLON.WoodProceduralTexture = WoodProceduralTexture;
  12510. var FireProceduralTexture = (function (_super) {
  12511. __extends(FireProceduralTexture, _super);
  12512. function FireProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  12513. _super.call(this, name, size, "fire", scene, fallbackTexture, generateMipMaps);
  12514. this._time = 0.0;
  12515. this._speed = new BABYLON.Vector2(0.5, 0.3);
  12516. this._shift = 1.6;
  12517. this._autoGenerateTime = true;
  12518. this._alphaThreshold = 0.5;
  12519. this._fireColors = FireProceduralTexture.RedFireColors;
  12520. this.updateShaderUniforms();
  12521. this.refreshRate = 1;
  12522. }
  12523. FireProceduralTexture.prototype.updateShaderUniforms = function () {
  12524. this.setFloat("time", this._time);
  12525. this.setVector2("speed", this._speed);
  12526. this.setFloat("shift", this._shift);
  12527. this.setColor3("c1", this._fireColors[0]);
  12528. this.setColor3("c2", this._fireColors[1]);
  12529. this.setColor3("c3", this._fireColors[2]);
  12530. this.setColor3("c4", this._fireColors[3]);
  12531. this.setColor3("c5", this._fireColors[4]);
  12532. this.setColor3("c6", this._fireColors[5]);
  12533. this.setFloat("alphaThreshold", this._alphaThreshold);
  12534. };
  12535. FireProceduralTexture.prototype.render = function (useCameraPostProcess) {
  12536. if (this._autoGenerateTime) {
  12537. this._time += this.getScene().getAnimationRatio() * 0.03;
  12538. this.updateShaderUniforms();
  12539. }
  12540. _super.prototype.render.call(this, useCameraPostProcess);
  12541. };
  12542. Object.defineProperty(FireProceduralTexture, "PurpleFireColors", {
  12543. get: function () {
  12544. return [
  12545. new BABYLON.Color3(0.5, 0.0, 1.0),
  12546. new BABYLON.Color3(0.9, 0.0, 1.0),
  12547. new BABYLON.Color3(0.2, 0.0, 1.0),
  12548. new BABYLON.Color3(1.0, 0.9, 1.0),
  12549. new BABYLON.Color3(0.1, 0.1, 1.0),
  12550. new BABYLON.Color3(0.9, 0.9, 1.0)
  12551. ];
  12552. },
  12553. enumerable: true,
  12554. configurable: true
  12555. });
  12556. Object.defineProperty(FireProceduralTexture, "GreenFireColors", {
  12557. get: function () {
  12558. return [
  12559. new BABYLON.Color3(0.5, 1.0, 0.0),
  12560. new BABYLON.Color3(0.5, 1.0, 0.0),
  12561. new BABYLON.Color3(0.3, 0.4, 0.0),
  12562. new BABYLON.Color3(0.5, 1.0, 0.0),
  12563. new BABYLON.Color3(0.2, 0.0, 0.0),
  12564. new BABYLON.Color3(0.5, 1.0, 0.0)
  12565. ];
  12566. },
  12567. enumerable: true,
  12568. configurable: true
  12569. });
  12570. Object.defineProperty(FireProceduralTexture, "RedFireColors", {
  12571. get: function () {
  12572. return [
  12573. new BABYLON.Color3(0.5, 0.0, 0.1),
  12574. new BABYLON.Color3(0.9, 0.0, 0.0),
  12575. new BABYLON.Color3(0.2, 0.0, 0.0),
  12576. new BABYLON.Color3(1.0, 0.9, 0.0),
  12577. new BABYLON.Color3(0.1, 0.1, 0.1),
  12578. new BABYLON.Color3(0.9, 0.9, 0.9)
  12579. ];
  12580. },
  12581. enumerable: true,
  12582. configurable: true
  12583. });
  12584. Object.defineProperty(FireProceduralTexture, "BlueFireColors", {
  12585. get: function () {
  12586. return [
  12587. new BABYLON.Color3(0.1, 0.0, 0.5),
  12588. new BABYLON.Color3(0.0, 0.0, 0.5),
  12589. new BABYLON.Color3(0.1, 0.0, 0.2),
  12590. new BABYLON.Color3(0.0, 0.0, 1.0),
  12591. new BABYLON.Color3(0.1, 0.2, 0.3),
  12592. new BABYLON.Color3(0.0, 0.2, 0.9)
  12593. ];
  12594. },
  12595. enumerable: true,
  12596. configurable: true
  12597. });
  12598. Object.defineProperty(FireProceduralTexture.prototype, "fireColors", {
  12599. get: function () {
  12600. return this._fireColors;
  12601. },
  12602. set: function (value) {
  12603. this._fireColors = value;
  12604. this.updateShaderUniforms();
  12605. },
  12606. enumerable: true,
  12607. configurable: true
  12608. });
  12609. Object.defineProperty(FireProceduralTexture.prototype, "time", {
  12610. get: function () {
  12611. return this._time;
  12612. },
  12613. set: function (value) {
  12614. this._time = value;
  12615. this.updateShaderUniforms();
  12616. },
  12617. enumerable: true,
  12618. configurable: true
  12619. });
  12620. Object.defineProperty(FireProceduralTexture.prototype, "speed", {
  12621. get: function () {
  12622. return this._speed;
  12623. },
  12624. set: function (value) {
  12625. this._speed = value;
  12626. this.updateShaderUniforms();
  12627. },
  12628. enumerable: true,
  12629. configurable: true
  12630. });
  12631. Object.defineProperty(FireProceduralTexture.prototype, "shift", {
  12632. get: function () {
  12633. return this._shift;
  12634. },
  12635. set: function (value) {
  12636. this._shift = value;
  12637. this.updateShaderUniforms();
  12638. },
  12639. enumerable: true,
  12640. configurable: true
  12641. });
  12642. Object.defineProperty(FireProceduralTexture.prototype, "alphaThreshold", {
  12643. get: function () {
  12644. return this._alphaThreshold;
  12645. },
  12646. set: function (value) {
  12647. this._alphaThreshold = value;
  12648. this.updateShaderUniforms();
  12649. },
  12650. enumerable: true,
  12651. configurable: true
  12652. });
  12653. return FireProceduralTexture;
  12654. })(BABYLON.ProceduralTexture);
  12655. BABYLON.FireProceduralTexture = FireProceduralTexture;
  12656. var CloudProceduralTexture = (function (_super) {
  12657. __extends(CloudProceduralTexture, _super);
  12658. function CloudProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  12659. _super.call(this, name, size, "cloud", scene, fallbackTexture, generateMipMaps);
  12660. this._skyColor = new BABYLON.Color3(0.15, 0.68, 1.0);
  12661. this._cloudColor = new BABYLON.Color3(1, 1, 1);
  12662. this.updateShaderUniforms();
  12663. this.refreshRate = 0;
  12664. }
  12665. CloudProceduralTexture.prototype.updateShaderUniforms = function () {
  12666. this.setColor3("skyColor", this._skyColor);
  12667. this.setColor3("cloudColor", this._cloudColor);
  12668. };
  12669. Object.defineProperty(CloudProceduralTexture.prototype, "skyColor", {
  12670. get: function () {
  12671. return this._skyColor;
  12672. },
  12673. set: function (value) {
  12674. this._skyColor = value;
  12675. this.updateShaderUniforms();
  12676. },
  12677. enumerable: true,
  12678. configurable: true
  12679. });
  12680. Object.defineProperty(CloudProceduralTexture.prototype, "cloudColor", {
  12681. get: function () {
  12682. return this._cloudColor;
  12683. },
  12684. set: function (value) {
  12685. this._cloudColor = value;
  12686. this.updateShaderUniforms();
  12687. },
  12688. enumerable: true,
  12689. configurable: true
  12690. });
  12691. return CloudProceduralTexture;
  12692. })(BABYLON.ProceduralTexture);
  12693. BABYLON.CloudProceduralTexture = CloudProceduralTexture;
  12694. var GrassProceduralTexture = (function (_super) {
  12695. __extends(GrassProceduralTexture, _super);
  12696. function GrassProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  12697. _super.call(this, name, size, "grass", scene, fallbackTexture, generateMipMaps);
  12698. this._herb1 = new BABYLON.Color3(0.29, 0.38, 0.02);
  12699. this._herb2 = new BABYLON.Color3(0.36, 0.49, 0.09);
  12700. this._herb3 = new BABYLON.Color3(0.51, 0.6, 0.28);
  12701. this._groundColor = new BABYLON.Color3(1, 1, 1);
  12702. this._grassColors = [
  12703. new BABYLON.Color3(0.29, 0.38, 0.02),
  12704. new BABYLON.Color3(0.36, 0.49, 0.09),
  12705. new BABYLON.Color3(0.51, 0.6, 0.28)
  12706. ];
  12707. this.updateShaderUniforms();
  12708. this.refreshRate = 0;
  12709. }
  12710. GrassProceduralTexture.prototype.updateShaderUniforms = function () {
  12711. this.setColor3("herb1Color", this._grassColors[0]);
  12712. this.setColor3("herb2Color", this._grassColors[1]);
  12713. this.setColor3("herb3Color", this._grassColors[2]);
  12714. this.setColor3("groundColor", this._groundColor);
  12715. };
  12716. Object.defineProperty(GrassProceduralTexture.prototype, "grassColors", {
  12717. get: function () {
  12718. return this._grassColors;
  12719. },
  12720. set: function (value) {
  12721. this._grassColors = value;
  12722. this.updateShaderUniforms();
  12723. },
  12724. enumerable: true,
  12725. configurable: true
  12726. });
  12727. Object.defineProperty(GrassProceduralTexture.prototype, "groundColor", {
  12728. get: function () {
  12729. return this._groundColor;
  12730. },
  12731. set: function (value) {
  12732. this.groundColor = value;
  12733. this.updateShaderUniforms();
  12734. },
  12735. enumerable: true,
  12736. configurable: true
  12737. });
  12738. return GrassProceduralTexture;
  12739. })(BABYLON.ProceduralTexture);
  12740. BABYLON.GrassProceduralTexture = GrassProceduralTexture;
  12741. var RoadProceduralTexture = (function (_super) {
  12742. __extends(RoadProceduralTexture, _super);
  12743. function RoadProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  12744. _super.call(this, name, size, "road", scene, fallbackTexture, generateMipMaps);
  12745. this._roadColor = new BABYLON.Color3(0.53, 0.53, 0.53);
  12746. this.updateShaderUniforms();
  12747. this.refreshRate = 0;
  12748. }
  12749. RoadProceduralTexture.prototype.updateShaderUniforms = function () {
  12750. this.setColor3("roadColor", this._roadColor);
  12751. };
  12752. Object.defineProperty(RoadProceduralTexture.prototype, "roadColor", {
  12753. get: function () {
  12754. return this._roadColor;
  12755. },
  12756. set: function (value) {
  12757. this._roadColor = value;
  12758. this.updateShaderUniforms();
  12759. },
  12760. enumerable: true,
  12761. configurable: true
  12762. });
  12763. return RoadProceduralTexture;
  12764. })(BABYLON.ProceduralTexture);
  12765. BABYLON.RoadProceduralTexture = RoadProceduralTexture;
  12766. var BrickProceduralTexture = (function (_super) {
  12767. __extends(BrickProceduralTexture, _super);
  12768. function BrickProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  12769. _super.call(this, name, size, "brick", scene, fallbackTexture, generateMipMaps);
  12770. this._numberOfBricksHeight = 15;
  12771. this._numberOfBricksWidth = 5;
  12772. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  12773. this._brickColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  12774. this.updateShaderUniforms();
  12775. this.refreshRate = 0;
  12776. }
  12777. BrickProceduralTexture.prototype.updateShaderUniforms = function () {
  12778. this.setFloat("numberOfBricksHeight", this._numberOfBricksHeight);
  12779. this.setFloat("numberOfBricksWidth", this._numberOfBricksWidth);
  12780. this.setColor3("brickColor", this._brickColor);
  12781. this.setColor3("jointColor", this._jointColor);
  12782. };
  12783. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksHeight", {
  12784. get: function () {
  12785. return this._numberOfBricksHeight;
  12786. },
  12787. enumerable: true,
  12788. configurable: true
  12789. });
  12790. Object.defineProperty(BrickProceduralTexture.prototype, "cloudColor", {
  12791. set: function (value) {
  12792. this._numberOfBricksHeight = value;
  12793. this.updateShaderUniforms();
  12794. },
  12795. enumerable: true,
  12796. configurable: true
  12797. });
  12798. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksWidth", {
  12799. get: function () {
  12800. return this._numberOfBricksWidth;
  12801. },
  12802. set: function (value) {
  12803. this._numberOfBricksHeight = value;
  12804. this.updateShaderUniforms();
  12805. },
  12806. enumerable: true,
  12807. configurable: true
  12808. });
  12809. Object.defineProperty(BrickProceduralTexture.prototype, "jointColor", {
  12810. get: function () {
  12811. return this._jointColor;
  12812. },
  12813. set: function (value) {
  12814. this._jointColor = value;
  12815. this.updateShaderUniforms();
  12816. },
  12817. enumerable: true,
  12818. configurable: true
  12819. });
  12820. Object.defineProperty(BrickProceduralTexture.prototype, "brickColor", {
  12821. get: function () {
  12822. return this._brickColor;
  12823. },
  12824. set: function (value) {
  12825. this._brickColor = value;
  12826. this.updateShaderUniforms();
  12827. },
  12828. enumerable: true,
  12829. configurable: true
  12830. });
  12831. return BrickProceduralTexture;
  12832. })(BABYLON.ProceduralTexture);
  12833. BABYLON.BrickProceduralTexture = BrickProceduralTexture;
  12834. var MarbleProceduralTexture = (function (_super) {
  12835. __extends(MarbleProceduralTexture, _super);
  12836. function MarbleProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  12837. _super.call(this, name, size, "marble", scene, fallbackTexture, generateMipMaps);
  12838. this._numberOfTilesHeight = 3;
  12839. this._numberOfTilesWidth = 3;
  12840. this._amplitude = 9.0;
  12841. this._marbleColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  12842. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  12843. this.updateShaderUniforms();
  12844. this.refreshRate = 0;
  12845. }
  12846. MarbleProceduralTexture.prototype.updateShaderUniforms = function () {
  12847. this.setFloat("numberOfTilesHeight", this._numberOfTilesHeight);
  12848. this.setFloat("numberOfTilesWidth", this._numberOfTilesWidth);
  12849. this.setFloat("amplitude", this._amplitude);
  12850. this.setColor3("marbleColor", this._marbleColor);
  12851. this.setColor3("jointColor", this._jointColor);
  12852. };
  12853. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesHeight", {
  12854. get: function () {
  12855. return this._numberOfTilesHeight;
  12856. },
  12857. set: function (value) {
  12858. this._numberOfTilesHeight = value;
  12859. this.updateShaderUniforms();
  12860. },
  12861. enumerable: true,
  12862. configurable: true
  12863. });
  12864. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesWidth", {
  12865. get: function () {
  12866. return this._numberOfTilesWidth;
  12867. },
  12868. set: function (value) {
  12869. this._numberOfTilesWidth = value;
  12870. this.updateShaderUniforms();
  12871. },
  12872. enumerable: true,
  12873. configurable: true
  12874. });
  12875. Object.defineProperty(MarbleProceduralTexture.prototype, "jointColor", {
  12876. get: function () {
  12877. return this._jointColor;
  12878. },
  12879. set: function (value) {
  12880. this._jointColor = value;
  12881. this.updateShaderUniforms();
  12882. },
  12883. enumerable: true,
  12884. configurable: true
  12885. });
  12886. Object.defineProperty(MarbleProceduralTexture.prototype, "marbleColor", {
  12887. get: function () {
  12888. return this._marbleColor;
  12889. },
  12890. set: function (value) {
  12891. this._marbleColor = value;
  12892. this.updateShaderUniforms();
  12893. },
  12894. enumerable: true,
  12895. configurable: true
  12896. });
  12897. return MarbleProceduralTexture;
  12898. })(BABYLON.ProceduralTexture);
  12899. BABYLON.MarbleProceduralTexture = MarbleProceduralTexture;
  12900. })(BABYLON || (BABYLON = {}));
  12901. //# sourceMappingURL=babylon.standardProceduralTexture.js.map
  12902. var BABYLON;
  12903. (function (BABYLON) {
  12904. var CustomProceduralTexture = (function (_super) {
  12905. __extends(CustomProceduralTexture, _super);
  12906. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  12907. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  12908. this._animate = true;
  12909. this._time = 0;
  12910. this._texturePath = texturePath;
  12911. //Try to load json
  12912. this.loadJson(texturePath);
  12913. this.refreshRate = 1;
  12914. }
  12915. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  12916. var _this = this;
  12917. var that = this;
  12918. function noConfigFile() {
  12919. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  12920. try {
  12921. that.setFragment(that._texturePath);
  12922. }
  12923. catch (ex) {
  12924. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  12925. }
  12926. }
  12927. var configFileUrl = jsonUrl + "/config.json";
  12928. var xhr = new XMLHttpRequest();
  12929. xhr.open("GET", configFileUrl, true);
  12930. xhr.addEventListener("load", function () {
  12931. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  12932. try {
  12933. _this._config = JSON.parse(xhr.response);
  12934. _this.updateShaderUniforms();
  12935. _this.updateTextures();
  12936. _this.setFragment(_this._texturePath + "/custom");
  12937. _this._animate = _this._config.animate;
  12938. _this.refreshRate = _this._config.refreshrate;
  12939. }
  12940. catch (ex) {
  12941. noConfigFile();
  12942. }
  12943. }
  12944. else {
  12945. noConfigFile();
  12946. }
  12947. }, false);
  12948. xhr.addEventListener("error", function () {
  12949. noConfigFile();
  12950. }, false);
  12951. try {
  12952. xhr.send();
  12953. }
  12954. catch (ex) {
  12955. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  12956. }
  12957. };
  12958. CustomProceduralTexture.prototype.isReady = function () {
  12959. if (!_super.prototype.isReady.call(this)) {
  12960. return false;
  12961. }
  12962. for (var name in this._textures) {
  12963. var texture = this._textures[name];
  12964. if (!texture.isReady()) {
  12965. return false;
  12966. }
  12967. }
  12968. return true;
  12969. };
  12970. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  12971. if (this._animate) {
  12972. this._time += this.getScene().getAnimationRatio() * 0.03;
  12973. this.updateShaderUniforms();
  12974. }
  12975. _super.prototype.render.call(this, useCameraPostProcess);
  12976. };
  12977. CustomProceduralTexture.prototype.updateTextures = function () {
  12978. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  12979. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  12980. }
  12981. };
  12982. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  12983. if (this._config) {
  12984. for (var j = 0; j < this._config.uniforms.length; j++) {
  12985. var uniform = this._config.uniforms[j];
  12986. switch (uniform.type) {
  12987. case "float":
  12988. this.setFloat(uniform.name, uniform.value);
  12989. break;
  12990. case "color3":
  12991. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  12992. break;
  12993. case "color4":
  12994. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  12995. break;
  12996. case "vector2":
  12997. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  12998. break;
  12999. case "vector3":
  13000. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  13001. break;
  13002. }
  13003. }
  13004. }
  13005. this.setFloat("time", this._time);
  13006. };
  13007. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  13008. get: function () {
  13009. return this._animate;
  13010. },
  13011. set: function (value) {
  13012. this._animate = value;
  13013. },
  13014. enumerable: true,
  13015. configurable: true
  13016. });
  13017. return CustomProceduralTexture;
  13018. })(BABYLON.ProceduralTexture);
  13019. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  13020. })(BABYLON || (BABYLON = {}));
  13021. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  13022. var BABYLON;
  13023. (function (BABYLON) {
  13024. var MirrorTexture = (function (_super) {
  13025. __extends(MirrorTexture, _super);
  13026. function MirrorTexture(name, size, scene, generateMipMaps) {
  13027. var _this = this;
  13028. _super.call(this, name, size, scene, generateMipMaps, true);
  13029. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  13030. this._transformMatrix = BABYLON.Matrix.Zero();
  13031. this._mirrorMatrix = BABYLON.Matrix.Zero();
  13032. this.onBeforeRender = function () {
  13033. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  13034. _this._savedViewMatrix = scene.getViewMatrix();
  13035. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  13036. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  13037. scene.clipPlane = _this.mirrorPlane;
  13038. scene.getEngine().cullBackFaces = false;
  13039. };
  13040. this.onAfterRender = function () {
  13041. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  13042. scene.getEngine().cullBackFaces = true;
  13043. delete scene.clipPlane;
  13044. };
  13045. }
  13046. MirrorTexture.prototype.clone = function () {
  13047. var textureSize = this.getSize();
  13048. var newTexture = new BABYLON.MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  13049. // Base texture
  13050. newTexture.hasAlpha = this.hasAlpha;
  13051. newTexture.level = this.level;
  13052. // Mirror Texture
  13053. newTexture.mirrorPlane = this.mirrorPlane.clone();
  13054. newTexture.renderList = this.renderList.slice(0);
  13055. return newTexture;
  13056. };
  13057. return MirrorTexture;
  13058. })(BABYLON.RenderTargetTexture);
  13059. BABYLON.MirrorTexture = MirrorTexture;
  13060. })(BABYLON || (BABYLON = {}));
  13061. //# sourceMappingURL=babylon.mirrorTexture.js.map
  13062. var BABYLON;
  13063. (function (BABYLON) {
  13064. var DynamicTexture = (function (_super) {
  13065. __extends(DynamicTexture, _super);
  13066. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  13067. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  13068. _super.call(this, null, scene, !generateMipMaps);
  13069. this.name = name;
  13070. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  13071. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  13072. this._generateMipMaps = generateMipMaps;
  13073. if (options.getContext) {
  13074. this._canvas = options;
  13075. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  13076. }
  13077. else {
  13078. this._canvas = document.createElement("canvas");
  13079. if (options.width) {
  13080. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  13081. }
  13082. else {
  13083. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  13084. }
  13085. }
  13086. var textureSize = this.getSize();
  13087. this._canvas.width = textureSize.width;
  13088. this._canvas.height = textureSize.height;
  13089. this._context = this._canvas.getContext("2d");
  13090. }
  13091. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  13092. get: function () {
  13093. return true;
  13094. },
  13095. enumerable: true,
  13096. configurable: true
  13097. });
  13098. DynamicTexture.prototype.scale = function (ratio) {
  13099. var textureSize = this.getSize();
  13100. textureSize.width *= ratio;
  13101. textureSize.height *= ratio;
  13102. this._canvas.width = textureSize.width;
  13103. this._canvas.height = textureSize.height;
  13104. this.releaseInternalTexture();
  13105. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  13106. };
  13107. DynamicTexture.prototype.getContext = function () {
  13108. return this._context;
  13109. };
  13110. DynamicTexture.prototype.clear = function () {
  13111. var size = this.getSize();
  13112. this._context.fillRect(0, 0, size.width, size.height);
  13113. };
  13114. DynamicTexture.prototype.update = function (invertY) {
  13115. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  13116. };
  13117. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  13118. if (update === void 0) { update = true; }
  13119. var size = this.getSize();
  13120. if (clearColor) {
  13121. this._context.fillStyle = clearColor;
  13122. this._context.fillRect(0, 0, size.width, size.height);
  13123. }
  13124. this._context.font = font;
  13125. if (x === null) {
  13126. var textSize = this._context.measureText(text);
  13127. x = (size.width - textSize.width) / 2;
  13128. }
  13129. this._context.fillStyle = color;
  13130. this._context.fillText(text, x, y);
  13131. if (update) {
  13132. this.update(invertY);
  13133. }
  13134. };
  13135. DynamicTexture.prototype.clone = function () {
  13136. var textureSize = this.getSize();
  13137. var newTexture = new DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  13138. // Base texture
  13139. newTexture.hasAlpha = this.hasAlpha;
  13140. newTexture.level = this.level;
  13141. // Dynamic Texture
  13142. newTexture.wrapU = this.wrapU;
  13143. newTexture.wrapV = this.wrapV;
  13144. return newTexture;
  13145. };
  13146. return DynamicTexture;
  13147. })(BABYLON.Texture);
  13148. BABYLON.DynamicTexture = DynamicTexture;
  13149. })(BABYLON || (BABYLON = {}));
  13150. //# sourceMappingURL=babylon.dynamicTexture.js.map
  13151. var BABYLON;
  13152. (function (BABYLON) {
  13153. var VideoTexture = (function (_super) {
  13154. __extends(VideoTexture, _super);
  13155. function VideoTexture(name, urls, size, scene, generateMipMaps, invertY, samplingMode) {
  13156. var _this = this;
  13157. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  13158. _super.call(this, null, scene, !generateMipMaps, invertY);
  13159. this._autoLaunch = true;
  13160. this.name = name;
  13161. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  13162. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  13163. var requiredWidth = size.width || size;
  13164. var requiredHeight = size.height || size;
  13165. this._texture = scene.getEngine().createDynamicTexture(requiredWidth, requiredHeight, generateMipMaps, samplingMode);
  13166. var textureSize = this.getSize();
  13167. this.video = document.createElement("video");
  13168. this.video.width = textureSize.width;
  13169. this.video.height = textureSize.height;
  13170. this.video.autoplay = false;
  13171. this.video.loop = true;
  13172. this.video.addEventListener("canplaythrough", function () {
  13173. if (_this._texture) {
  13174. _this._texture.isReady = true;
  13175. }
  13176. });
  13177. urls.forEach(function (url) {
  13178. //Backwards-compatibility for typescript 1. from 1.3 it should say "SOURCE". see here - https://github.com/Microsoft/TypeScript/issues/1850
  13179. var source = document.createElement("source");
  13180. source.src = url;
  13181. _this.video.appendChild(source);
  13182. });
  13183. this._lastUpdate = BABYLON.Tools.Now;
  13184. }
  13185. VideoTexture.prototype.update = function () {
  13186. if (this._autoLaunch) {
  13187. this._autoLaunch = false;
  13188. this.video.play();
  13189. }
  13190. var now = BABYLON.Tools.Now;
  13191. if (now - this._lastUpdate < 15) {
  13192. return false;
  13193. }
  13194. this._lastUpdate = now;
  13195. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  13196. return true;
  13197. };
  13198. return VideoTexture;
  13199. })(BABYLON.Texture);
  13200. BABYLON.VideoTexture = VideoTexture;
  13201. })(BABYLON || (BABYLON = {}));
  13202. //# sourceMappingURL=babylon.videoTexture.js.mapvar BABYLON;
  13203. (function (BABYLON) {
  13204. var EffectFallbacks = (function () {
  13205. function EffectFallbacks() {
  13206. this._defines = {};
  13207. this._currentRank = 32;
  13208. this._maxRank = -1;
  13209. }
  13210. EffectFallbacks.prototype.addFallback = function (rank, define) {
  13211. if (!this._defines[rank]) {
  13212. if (rank < this._currentRank) {
  13213. this._currentRank = rank;
  13214. }
  13215. if (rank > this._maxRank) {
  13216. this._maxRank = rank;
  13217. }
  13218. this._defines[rank] = new Array();
  13219. }
  13220. this._defines[rank].push(define);
  13221. };
  13222. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  13223. get: function () {
  13224. return this._currentRank <= this._maxRank;
  13225. },
  13226. enumerable: true,
  13227. configurable: true
  13228. });
  13229. EffectFallbacks.prototype.reduce = function (currentDefines) {
  13230. var currentFallbacks = this._defines[this._currentRank];
  13231. for (var index = 0; index < currentFallbacks.length; index++) {
  13232. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  13233. }
  13234. this._currentRank++;
  13235. return currentDefines;
  13236. };
  13237. return EffectFallbacks;
  13238. })();
  13239. BABYLON.EffectFallbacks = EffectFallbacks;
  13240. var Effect = (function () {
  13241. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  13242. var _this = this;
  13243. this._isReady = false;
  13244. this._compilationError = "";
  13245. this._valueCache = [];
  13246. this._engine = engine;
  13247. this.name = baseName;
  13248. this.defines = defines;
  13249. this._uniformsNames = uniformsNames.concat(samplers);
  13250. this._samplers = samplers;
  13251. this._attributesNames = attributesNames;
  13252. this.onError = onError;
  13253. this.onCompiled = onCompiled;
  13254. var vertexSource;
  13255. var fragmentSource;
  13256. if (baseName.vertexElement) {
  13257. vertexSource = document.getElementById(baseName.vertexElement);
  13258. if (!vertexSource) {
  13259. vertexSource = baseName.vertexElement;
  13260. }
  13261. }
  13262. else {
  13263. vertexSource = baseName.vertex || baseName;
  13264. }
  13265. if (baseName.fragmentElement) {
  13266. fragmentSource = document.getElementById(baseName.fragmentElement);
  13267. if (!fragmentSource) {
  13268. fragmentSource = baseName.fragmentElement;
  13269. }
  13270. }
  13271. else {
  13272. fragmentSource = baseName.fragment || baseName;
  13273. }
  13274. this._loadVertexShader(vertexSource, function (vertexCode) {
  13275. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  13276. _this._prepareEffect(vertexCode, fragmentCode, attributesNames, defines, fallbacks);
  13277. });
  13278. });
  13279. }
  13280. // Properties
  13281. Effect.prototype.isReady = function () {
  13282. return this._isReady;
  13283. };
  13284. Effect.prototype.getProgram = function () {
  13285. return this._program;
  13286. };
  13287. Effect.prototype.getAttributesNames = function () {
  13288. return this._attributesNames;
  13289. };
  13290. Effect.prototype.getAttributeLocation = function (index) {
  13291. return this._attributes[index];
  13292. };
  13293. Effect.prototype.getAttributeLocationByName = function (name) {
  13294. var index = this._attributesNames.indexOf(name);
  13295. return this._attributes[index];
  13296. };
  13297. Effect.prototype.getAttributesCount = function () {
  13298. return this._attributes.length;
  13299. };
  13300. Effect.prototype.getUniformIndex = function (uniformName) {
  13301. return this._uniformsNames.indexOf(uniformName);
  13302. };
  13303. Effect.prototype.getUniform = function (uniformName) {
  13304. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  13305. };
  13306. Effect.prototype.getSamplers = function () {
  13307. return this._samplers;
  13308. };
  13309. Effect.prototype.getCompilationError = function () {
  13310. return this._compilationError;
  13311. };
  13312. // Methods
  13313. Effect.prototype._loadVertexShader = function (vertex, callback) {
  13314. // DOM element ?
  13315. if (vertex instanceof HTMLElement) {
  13316. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  13317. callback(vertexCode);
  13318. return;
  13319. }
  13320. // Is in local store ?
  13321. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  13322. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  13323. return;
  13324. }
  13325. var vertexShaderUrl;
  13326. if (vertex[0] === ".") {
  13327. vertexShaderUrl = vertex;
  13328. }
  13329. else {
  13330. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  13331. }
  13332. // Vertex shader
  13333. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  13334. };
  13335. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  13336. // DOM element ?
  13337. if (fragment instanceof HTMLElement) {
  13338. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  13339. callback(fragmentCode);
  13340. return;
  13341. }
  13342. // Is in local store ?
  13343. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  13344. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  13345. return;
  13346. }
  13347. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  13348. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  13349. return;
  13350. }
  13351. var fragmentShaderUrl;
  13352. if (fragment[0] === ".") {
  13353. fragmentShaderUrl = fragment;
  13354. }
  13355. else {
  13356. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  13357. }
  13358. // Fragment shader
  13359. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  13360. };
  13361. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  13362. try {
  13363. var engine = this._engine;
  13364. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  13365. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  13366. this._attributes = engine.getAttributes(this._program, attributesNames);
  13367. for (var index = 0; index < this._samplers.length; index++) {
  13368. var sampler = this.getUniform(this._samplers[index]);
  13369. if (sampler == null) {
  13370. this._samplers.splice(index, 1);
  13371. index--;
  13372. }
  13373. }
  13374. engine.bindSamplers(this);
  13375. this._isReady = true;
  13376. if (this.onCompiled) {
  13377. this.onCompiled(this);
  13378. }
  13379. }
  13380. catch (e) {
  13381. // Is it a problem with precision?
  13382. if (e.message.indexOf("highp") !== -1) {
  13383. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  13384. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  13385. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  13386. return;
  13387. }
  13388. // Let's go through fallbacks then
  13389. if (fallbacks && fallbacks.isMoreFallbacks) {
  13390. defines = fallbacks.reduce(defines);
  13391. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  13392. }
  13393. else {
  13394. BABYLON.Tools.Error("Unable to compile effect: " + this.name);
  13395. BABYLON.Tools.Error("Defines: " + defines);
  13396. BABYLON.Tools.Error("Error: " + e.message);
  13397. this._compilationError = e.message;
  13398. if (this.onError) {
  13399. this.onError(this, this._compilationError);
  13400. }
  13401. }
  13402. }
  13403. };
  13404. Effect.prototype._bindTexture = function (channel, texture) {
  13405. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  13406. };
  13407. Effect.prototype.setTexture = function (channel, texture) {
  13408. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  13409. };
  13410. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  13411. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  13412. };
  13413. //public _cacheMatrix(uniformName, matrix) {
  13414. // if (!this._valueCache[uniformName]) {
  13415. // this._valueCache[uniformName] = new BABYLON.Matrix();
  13416. // }
  13417. // for (var index = 0; index < 16; index++) {
  13418. // this._valueCache[uniformName].m[index] = matrix.m[index];
  13419. // }
  13420. //};
  13421. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  13422. if (!this._valueCache[uniformName]) {
  13423. this._valueCache[uniformName] = [x, y];
  13424. return;
  13425. }
  13426. this._valueCache[uniformName][0] = x;
  13427. this._valueCache[uniformName][1] = y;
  13428. };
  13429. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  13430. if (!this._valueCache[uniformName]) {
  13431. this._valueCache[uniformName] = [x, y, z];
  13432. return;
  13433. }
  13434. this._valueCache[uniformName][0] = x;
  13435. this._valueCache[uniformName][1] = y;
  13436. this._valueCache[uniformName][2] = z;
  13437. };
  13438. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  13439. if (!this._valueCache[uniformName]) {
  13440. this._valueCache[uniformName] = [x, y, z, w];
  13441. return;
  13442. }
  13443. this._valueCache[uniformName][0] = x;
  13444. this._valueCache[uniformName][1] = y;
  13445. this._valueCache[uniformName][2] = z;
  13446. this._valueCache[uniformName][3] = w;
  13447. };
  13448. Effect.prototype.setArray = function (uniformName, array) {
  13449. this._engine.setArray(this.getUniform(uniformName), array);
  13450. return this;
  13451. };
  13452. Effect.prototype.setArray2 = function (uniformName, array) {
  13453. this._engine.setArray2(this.getUniform(uniformName), array);
  13454. return this;
  13455. };
  13456. Effect.prototype.setArray3 = function (uniformName, array) {
  13457. this._engine.setArray3(this.getUniform(uniformName), array);
  13458. return this;
  13459. };
  13460. Effect.prototype.setArray4 = function (uniformName, array) {
  13461. this._engine.setArray4(this.getUniform(uniformName), array);
  13462. return this;
  13463. };
  13464. Effect.prototype.setMatrices = function (uniformName, matrices) {
  13465. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  13466. return this;
  13467. };
  13468. Effect.prototype.setMatrix = function (uniformName, matrix) {
  13469. //if (this._valueCache[uniformName] && this._valueCache[uniformName].equals(matrix))
  13470. // return;
  13471. //this._cacheMatrix(uniformName, matrix);
  13472. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  13473. return this;
  13474. };
  13475. Effect.prototype.setFloat = function (uniformName, value) {
  13476. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  13477. return this;
  13478. this._valueCache[uniformName] = value;
  13479. this._engine.setFloat(this.getUniform(uniformName), value);
  13480. return this;
  13481. };
  13482. Effect.prototype.setBool = function (uniformName, bool) {
  13483. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  13484. return this;
  13485. this._valueCache[uniformName] = bool;
  13486. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  13487. return this;
  13488. };
  13489. Effect.prototype.setVector2 = function (uniformName, vector2) {
  13490. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector2.x && this._valueCache[uniformName][1] === vector2.y)
  13491. return this;
  13492. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  13493. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  13494. return this;
  13495. };
  13496. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  13497. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y)
  13498. return this;
  13499. this._cacheFloat2(uniformName, x, y);
  13500. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  13501. return this;
  13502. };
  13503. Effect.prototype.setVector3 = function (uniformName, vector3) {
  13504. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector3.x && this._valueCache[uniformName][1] === vector3.y && this._valueCache[uniformName][2] === vector3.z)
  13505. return this;
  13506. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  13507. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  13508. return this;
  13509. };
  13510. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  13511. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z)
  13512. return this;
  13513. this._cacheFloat3(uniformName, x, y, z);
  13514. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  13515. return this;
  13516. };
  13517. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  13518. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z && this._valueCache[uniformName][3] === w)
  13519. return this;
  13520. this._cacheFloat4(uniformName, x, y, z, w);
  13521. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  13522. return this;
  13523. };
  13524. Effect.prototype.setColor3 = function (uniformName, color3) {
  13525. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b)
  13526. return this;
  13527. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  13528. this._engine.setColor3(this.getUniform(uniformName), color3);
  13529. return this;
  13530. };
  13531. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  13532. 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)
  13533. return this;
  13534. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  13535. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  13536. return this;
  13537. };
  13538. // Statics
  13539. 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}",
  13540. 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}",
  13541. 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}",
  13542. 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}",
  13543. 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}",
  13544. 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}",
  13545. colorPixelShader:"precision highp float;\n\nuniform vec4 color;\n\nvoid main(void) {\n gl_FragColor = color;\n}",
  13546. 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}",
  13547. 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}",
  13548. 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 float darkness0;\n#endif\n#ifdef SPOTLIGHT0\nuniform vec4 vLightDirection0;\n#endif\n#ifdef HEMILIGHT0\nuniform vec3 vLightGround0;\n#endif\n#endif\n\n#ifdef LIGHT1\nuniform vec4 vLightData1;\nuniform vec4 vLightDiffuse1;\nuniform vec3 vLightSpecular1;\n#ifdef SHADOW1\nvarying vec4 vPositionFromLight1;\nuniform sampler2D shadowSampler1;\nuniform float darkness1;\n#endif\n#ifdef SPOTLIGHT1\nuniform vec4 vLightDirection1;\n#endif\n#ifdef HEMILIGHT1\nuniform vec3 vLightGround1;\n#endif\n#endif\n\n#ifdef LIGHT2\nuniform vec4 vLightData2;\nuniform vec4 vLightDiffuse2;\nuniform vec3 vLightSpecular2;\n#ifdef SHADOW2\nvarying vec4 vPositionFromLight2;\nuniform sampler2D shadowSampler2;\nuniform float darkness2;\n#endif\n#ifdef SPOTLIGHT2\nuniform vec4 vLightDirection2;\n#endif\n#ifdef HEMILIGHT2\nuniform vec3 vLightGround2;\n#endif\n#endif\n\n#ifdef LIGHT3\nuniform vec4 vLightData3;\nuniform vec4 vLightDiffuse3;\nuniform vec3 vLightSpecular3;\n#ifdef SHADOW3\nvarying vec4 vPositionFromLight3;\nuniform sampler2D shadowSampler3;\nuniform float darkness3;\n#endif\n#ifdef SPOTLIGHT3\nuniform vec4 vLightDirection3;\n#endif\n#ifdef HEMILIGHT3\nuniform vec3 vLightGround3;\n#endif\n#endif\n\n// Samplers\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\nuniform vec2 vDiffuseInfos;\n#endif\n\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec2 vAmbientInfos;\n#endif\n\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n\n#ifdef SPECULAR\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform sampler2D specularSampler;\n#endif\n\n// Fresnel\n#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection, vec3 worldNormal, float bias, float power)\n{\n float fresnelTerm = pow(bias + abs(dot(viewDirection, worldNormal)), power);\n return clamp(fresnelTerm, 0., 1.);\n}\n#endif\n\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n// Reflection\n#ifdef REFLECTION\nvarying vec3 vPositionUVW;\nuniform samplerCube reflectionCubeSampler;\nuniform sampler2D reflection2DSampler;\nuniform vec3 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform mat4 view;\n\nvec3 computeReflectionCoords(float mode, vec4 worldPos, vec3 worldNormal)\n{\n if (mode == MAP_SPHERICAL)\n {\n vec3 coords = vec3(view * vec4(worldNormal, 0.0));\n\n return vec3(reflectionMatrix * vec4(coords, 1.0));\n }\n else if (mode == MAP_PLANAR)\n {\n vec3 viewDir = worldPos.xyz - vEyePosition;\n vec3 coords = normalize(reflect(viewDir, worldNormal));\n\n return vec3(reflectionMatrix * vec4(coords, 1));\n }\n else if (mode == MAP_CUBIC)\n {\n vec3 viewDir = worldPos.xyz - vEyePosition;\n vec3 coords = reflect(viewDir, worldNormal);\n\n return vec3(reflectionMatrix * vec4(coords, 0));\n }\n else if (mode == MAP_PROJECTION)\n {\n return vec3(reflectionMatrix * (view * worldPos));\n }\n else if (mode == MAP_SKYBOX)\n {\n return vPositionUVW;\n }\n\n return vec3(0, 0, 0);\n}\n#endif\n\n// Shadows\n#ifdef SHADOWS\n\nfloat unpack(vec4 color)\n{\n const vec4 bitShift = vec4(1. / (255. * 255. * 255.), 1. / (255. * 255.), 1. / 255., 1.);\n return dot(color, bitShift);\n}\n\nfloat unpackHalf(vec2 color)\n{\n return color.x + (color.y / 255.0);\n}\n\nfloat computeShadow(vec4 vPositionFromLight, sampler2D shadowSampler, float darkness)\n{\n vec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\n vec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\n\n if (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n {\n return 1.0;\n }\n\n float shadow = unpack(texture2D(shadowSampler, uv));\n\n if (depth.z > shadow)\n {\n return darkness;\n }\n return 1.;\n}\n\nfloat computeShadowWithPCF(vec4 vPositionFromLight, sampler2D shadowSampler)\n{\n vec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\n vec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\n\n if (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n {\n return 1.0;\n }\n\n float visibility = 1.;\n\n vec2 poissonDisk[4];\n poissonDisk[0] = vec2(-0.94201624, -0.39906216);\n poissonDisk[1] = vec2(0.94558609, -0.76890725);\n poissonDisk[2] = vec2(-0.094184101, -0.92938870);\n poissonDisk[3] = vec2(0.34495938, 0.29387760);\n\n // Poisson Sampling\n if (unpack(texture2D(shadowSampler, uv + poissonDisk[0] / 1500.0)) < depth.z) visibility -= 0.2;\n if (unpack(texture2D(shadowSampler, uv + poissonDisk[1] / 1500.0)) < depth.z) visibility -= 0.2;\n if (unpack(texture2D(shadowSampler, uv + poissonDisk[2] / 1500.0)) < depth.z) visibility -= 0.2;\n if (unpack(texture2D(shadowSampler, uv + poissonDisk[3] / 1500.0)) < depth.z) visibility -= 0.2;\n\n return visibility;\n}\n\n// Thanks to http://devmaster.net/\nfloat ChebychevInequality(vec2 moments, float t)\n{\n if (t <= moments.x)\n {\n return 1.0;\n }\n\n float variance = moments.y - (moments.x * moments.x);\n variance = max(variance, 0.);\n\n float d = t - moments.x;\n return variance / (variance + d * d);\n}\n\nfloat computeShadowWithVSM(vec4 vPositionFromLight, sampler2D shadowSampler)\n{\n vec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\n vec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\n\n if (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n {\n return 1.0;\n }\n\n vec4 texel = texture2D(shadowSampler, uv);\n\n vec2 moments = vec2(unpackHalf(texel.xy), unpackHalf(texel.zw));\n return clamp(1.3 - ChebychevInequality(moments, depth.z), 0., 1.0);\n}\n#endif\n\n// Bump\n#ifdef BUMP\n#extension GL_OES_standard_derivatives : enable\nvarying vec2 vBumpUV;\nuniform vec2 vBumpInfos;\nuniform sampler2D bumpSampler;\n\n// Thanks to http://www.thetenthplanet.de/archives/1180\nmat3 cotangent_frame(vec3 normal, vec3 p, vec2 uv)\n{\n // get edge vectors of the pixel triangle\n vec3 dp1 = dFdx(p);\n vec3 dp2 = dFdy(p);\n vec2 duv1 = dFdx(uv);\n vec2 duv2 = dFdy(uv);\n\n // solve the linear system\n vec3 dp2perp = cross(dp2, normal);\n vec3 dp1perp = cross(normal, dp1);\n vec3 tangent = dp2perp * duv1.x + dp1perp * duv2.x;\n vec3 binormal = dp2perp * duv1.y + dp1perp * duv2.y;\n\n // construct a scale-invariant frame \n float invmax = inversesqrt(max(dot(tangent, tangent), dot(binormal, binormal)));\n return mat3(tangent * invmax, binormal * invmax, normal);\n}\n\nvec3 perturbNormal(vec3 viewDir)\n{\n vec3 map = texture2D(bumpSampler, vBumpUV).xyz;\n map = map * 255. / 127. - 128. / 127.;\n mat3 TBN = cotangent_frame(vNormalW * vBumpInfos.y, -viewDir, vBumpUV);\n return normalize(TBN * map);\n}\n#endif\n\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\n\n// Fog\n#ifdef FOG\n\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\n\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying float fFogDistance;\n\nfloat CalcFogFactor()\n{\n float fogCoeff = 1.0;\n float fogStart = vFogInfos.y;\n float fogEnd = vFogInfos.z;\n float fogDensity = vFogInfos.w;\n\n if (FOGMODE_LINEAR == vFogInfos.x)\n {\n fogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\n }\n else if (FOGMODE_EXP == vFogInfos.x)\n {\n fogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\n }\n else if (FOGMODE_EXP2 == vFogInfos.x)\n {\n fogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\n }\n\n return clamp(fogCoeff, 0.0, 1.0);\n}\n#endif\n\n// Light Computing\nstruct lightingInfo\n{\n vec3 diffuse;\n vec3 specular;\n};\n\nlightingInfo computeLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec3 diffuseColor, vec3 specularColor, float range) {\n lightingInfo result;\n\n vec3 lightVectorW;\n float attenuation = 1.0;\n if (lightData.w == 0.)\n {\n vec3 direction = lightData.xyz - vPositionW;\n\n attenuation = max(0., 1.0 - length(direction) / range);\n lightVectorW = normalize(direction);\n }\n else\n {\n lightVectorW = normalize(-lightData.xyz);\n }\n\n // diffuse\n float ndl = max(0., dot(vNormal, lightVectorW));\n\n // Specular\n vec3 angleW = normalize(viewDirectionW + lightVectorW);\n float specComp = max(0., dot(vNormal, angleW));\n specComp = pow(specComp, max(1., vSpecularColor.a));\n\n result.diffuse = ndl * diffuseColor * attenuation;\n result.specular = specComp * specularColor * attenuation;\n\n return result;\n}\n\nlightingInfo computeSpotLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 lightDirection, vec3 diffuseColor, vec3 specularColor, float range) {\n lightingInfo result;\n\n vec3 direction = lightData.xyz - vPositionW;\n vec3 lightVectorW = normalize(direction);\n float attenuation = max(0., 1.0 - length(direction) / range);\n\n // diffuse\n float cosAngle = max(0., dot(-lightDirection.xyz, lightVectorW));\n float spotAtten = 0.0;\n\n if (cosAngle >= lightDirection.w)\n {\n cosAngle = max(0., pow(cosAngle, lightData.w));\n spotAtten = max(0., (cosAngle - lightDirection.w) / (1. - cosAngle));\n\n // Diffuse\n float ndl = max(0., dot(vNormal, -lightDirection.xyz));\n\n // Specular\n vec3 angleW = normalize(viewDirectionW - lightDirection.xyz);\n float specComp = max(0., dot(vNormal, angleW));\n specComp = pow(specComp, vSpecularColor.a);\n\n result.diffuse = ndl * spotAtten * diffuseColor * attenuation;\n result.specular = specComp * specularColor * spotAtten * attenuation;\n\n return result;\n }\n\n result.diffuse = vec3(0.);\n result.specular = vec3(0.);\n\n return result;\n}\n\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec3 diffuseColor, vec3 specularColor, vec3 groundColor) {\n lightingInfo result;\n\n // Diffuse\n float ndl = dot(vNormal, lightData.xyz) * 0.5 + 0.5;\n\n // Specular\n vec3 angleW = normalize(viewDirectionW + lightData.xyz);\n float specComp = max(0., dot(vNormal, angleW));\n specComp = pow(specComp, vSpecularColor.a);\n\n result.diffuse = mix(groundColor, diffuseColor, ndl);\n result.specular = specComp * specularColor;\n\n return result;\n}\n\nvoid main(void) {\n // Clip plane\n#ifdef CLIPPLANE\n if (fClipDistance > 0.0)\n discard;\n#endif\n\n vec3 viewDirectionW = normalize(vEyePosition - vPositionW);\n\n // Base color\n vec4 baseColor = vec4(1., 1., 1., 1.);\n vec3 diffuseColor = vDiffuseColor.rgb;\n\n // Alpha\n float alpha = vDiffuseColor.a;\n\n#ifdef VERTEXCOLOR\n baseColor.rgb *= vColor.rgb;\n#endif\n\n#ifdef DIFFUSE\n baseColor = texture2D(diffuseSampler, vDiffuseUV);\n\n#ifdef ALPHATEST\n if (baseColor.a < 0.4)\n discard;\n#endif\n\n#ifdef ALPHAFROMDIFFUSE\n alpha *= baseColor.a;\n#endif\n\n baseColor.rgb *= vDiffuseInfos.y;\n#endif\n\n // Bump\n#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);\n#else\n #ifdef SHADOWPCF0\n shadow = computeShadowWithPCF(vPositionFromLight0, shadowSampler0);\n #else\n shadow = computeShadow(vPositionFromLight0, shadowSampler0, darkness0);\n #endif\n#endif\n#else\n shadow = 1.;\n#endif\n diffuseBase += info.diffuse * shadow;\n specularBase += info.specular * shadow;\n#endif\n\n#ifdef LIGHT1\n#ifdef SPOTLIGHT1\n info = computeSpotLighting(viewDirectionW, normalW, vLightData1, vLightDirection1, vLightDiffuse1.rgb, vLightSpecular1, vLightDiffuse1.a);\n#endif\n#ifdef HEMILIGHT1\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightSpecular1, vLightGround1);\n#endif\n#ifdef POINTDIRLIGHT1\n info = computeLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightSpecular1, vLightDiffuse1.a);\n#endif\n#ifdef SHADOW1\n#ifdef SHADOWVSM1\n shadow = computeShadowWithVSM(vPositionFromLight1, shadowSampler1);\n#else\n #ifdef SHADOWPCF1\n shadow = computeShadowWithPCF(vPositionFromLight1, shadowSampler1);\n #else\n shadow = computeShadow(vPositionFromLight1, shadowSampler1, darkness1);\n #endif\n#endif\n#else\n shadow = 1.;\n#endif\n diffuseBase += info.diffuse * shadow;\n specularBase += info.specular * shadow;\n#endif\n\n#ifdef LIGHT2\n#ifdef SPOTLIGHT2\n info = computeSpotLighting(viewDirectionW, normalW, vLightData2, vLightDirection2, vLightDiffuse2.rgb, vLightSpecular2, vLightDiffuse2.a);\n#endif\n#ifdef HEMILIGHT2\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightSpecular2, vLightGround2);\n#endif\n#ifdef POINTDIRLIGHT2\n info = computeLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightSpecular2, vLightDiffuse2.a);\n#endif\n#ifdef SHADOW2\n#ifdef SHADOWVSM2\n shadow = computeShadowWithVSM(vPositionFromLight2, shadowSampler2);\n#else\n #ifdef SHADOWPCF2\n shadow = computeShadowWithPCF(vPositionFromLight2, shadowSampler2);\n #else\n shadow = computeShadow(vPositionFromLight2, shadowSampler2, darkness2);\n #endif \n#endif \n#else\n shadow = 1.;\n#endif\n diffuseBase += info.diffuse * shadow;\n specularBase += info.specular * shadow;\n#endif\n\n#ifdef LIGHT3\n#ifdef SPOTLIGHT3\n info = computeSpotLighting(viewDirectionW, normalW, vLightData3, vLightDirection3, vLightDiffuse3.rgb, vLightSpecular3, vLightDiffuse3.a);\n#endif\n#ifdef HEMILIGHT3\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightSpecular3, vLightGround3);\n#endif\n#ifdef POINTDIRLIGHT3\n info = computeLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightSpecular3, vLightDiffuse3.a);\n#endif\n#ifdef SHADOW3\n#ifdef SHADOWVSM3\n shadow = computeShadowWithVSM(vPositionFromLight3, shadowSampler3);\n#else\n #ifdef SHADOWPCF3\n shadow = computeShadowWithPCF(vPositionFromLight3, shadowSampler3);\n #else\n shadow = computeShadow(vPositionFromLight3, shadowSampler3, darkness3);\n #endif \n#endif \n#else\n shadow = 1.;\n#endif\n diffuseBase += info.diffuse * shadow;\n specularBase += info.specular * shadow;\n#endif\n\n // Reflection\n vec3 reflectionColor = vec3(0., 0., 0.);\n\n#ifdef REFLECTION\n vec3 vReflectionUVW = computeReflectionCoords(vReflectionInfos.x, vec4(vPositionW, 1.0), normalW);\n\n if (vReflectionInfos.z != 0.0)\n {\n reflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW).rgb * vReflectionInfos.y * shadow;\n }\n else\n {\n vec2 coords = vReflectionUVW.xy;\n\n if (vReflectionInfos.x == MAP_PROJECTION)\n {\n coords /= vReflectionUVW.z;\n }\n\n coords.y = 1.0 - coords.y;\n\n reflectionColor = texture2D(reflection2DSampler, coords).rgb * vReflectionInfos.y * shadow;\n }\n\n#ifdef REFLECTIONFRESNEL\n float reflectionFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, reflectionRightColor.a, reflectionLeftColor.a);\n\n reflectionColor *= reflectionLeftColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\n#endif\n#endif\n\n#ifdef OPACITY\n vec4 opacityMap = texture2D(opacitySampler, vOpacityUV);\n\n#ifdef OPACITYRGB\n opacityMap.rgb = opacityMap.rgb * vec3(0.3, 0.59, 0.11);\n alpha *= (opacityMap.x + opacityMap.y + opacityMap.z)* vOpacityInfos.y;\n#else\n alpha *= opacityMap.a * vOpacityInfos.y;\n#endif\n\n#endif\n\n#ifdef VERTEXALPHA\n alpha *= vColor.a;\n#endif\n\n#ifdef OPACITYFRESNEL\n float opacityFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, opacityParts.z, opacityParts.w);\n\n alpha += opacityParts.x * (1.0 - opacityFresnelTerm) + opacityFresnelTerm * opacityParts.y;\n#endif\n\n // Emissive\n vec3 emissiveColor = vEmissiveColor;\n#ifdef EMISSIVE\n emissiveColor += texture2D(emissiveSampler, vEmissiveUV).rgb * vEmissiveInfos.y;\n#endif\n\n#ifdef EMISSIVEFRESNEL\n float emissiveFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, emissiveRightColor.a, emissiveLeftColor.a);\n\n emissiveColor *= emissiveLeftColor.rgb * (1.0 - emissiveFresnelTerm) + emissiveFresnelTerm * emissiveRightColor.rgb;\n#endif\n\n // Specular map\n vec3 specularColor = vSpecularColor.rgb;\n#ifdef SPECULAR\n specularColor = texture2D(specularSampler, vSpecularUV).rgb * vSpecularInfos.y;\n#endif\n\n // Fresnel\n#ifdef DIFFUSEFRESNEL\n float diffuseFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, diffuseRightColor.a, diffuseLeftColor.a);\n\n diffuseBase *= diffuseLeftColor.rgb * (1.0 - diffuseFresnelTerm) + diffuseFresnelTerm * diffuseRightColor.rgb;\n#endif\n\n // Composition\n vec3 finalDiffuse = clamp(diffuseBase * diffuseColor + emissiveColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\n vec3 finalSpecular = specularBase * specularColor;\n\n#ifdef SPECULAROVERALPHA\n alpha = clamp(alpha + dot(finalSpecular, vec3(0.3, 0.59, 0.11)), 0., 1.);\n#endif\n\n vec4 color = vec4(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor, alpha);\n\n#ifdef FOG\n float fog = CalcFogFactor();\n color.rgb = fog * color.rgb + (1.0 - fog) * vFogColor;\n#endif\n\n gl_FragColor = color;\n}",
  13549. 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}",
  13550. 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}",
  13551. depthVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Attribute\nattribute vec3 position;\n#ifdef BONES\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#endif\n\n// Uniform\n#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif\n\nuniform mat4 viewProjection;\n#ifdef BONES\nuniform mat4 mBones[BonesPerMesh];\n#endif\n\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n\nvoid main(void)\n{\n#ifdef INSTANCES\n mat4 finalWorld = mat4(world0, world1, world2, world3);\n#else\n mat4 finalWorld = world;\n#endif\n\n#ifdef BONES\n mat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\n mat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\n mat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\n mat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\n finalWorld = finalWorld * (m0 + m1 + m2 + m3);\n gl_Position = viewProjection * finalWorld * vec4(position, 1.0);\n#else\n gl_Position = viewProjection * finalWorld * vec4(position, 1.0);\n#endif\n\n#ifdef ALPHATEST\n#ifdef UV1\n vUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\n#endif\n#ifdef UV2\n vUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\n#endif\n#endif\n}",
  13552. 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}",
  13553. 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}",
  13554. 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}",
  13555. 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}",
  13556. 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}",
  13557. 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}",
  13558. 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}",
  13559. 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}",
  13560. 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}",
  13561. 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}",
  13562. 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}",
  13563. 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}",
  13564. 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}",
  13565. 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}",
  13566. 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}",
  13567. 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}",
  13568. 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}",
  13569. 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}",
  13570. 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}",
  13571. 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}",
  13572. 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}",
  13573. 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}",
  13574. 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}",
  13575. shadowMapPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvec4 pack(float depth)\n{\n const vec4 bitOffset = vec4(255. * 255. * 255., 255. * 255., 255., 1.);\n const vec4 bitMask = vec4(0., 1. / 255., 1. / 255., 1. / 255.);\n \n vec4 comp = mod(depth * bitOffset * vec4(254.), vec4(255.)) / vec4(254.);\n comp -= comp.xxyz * bitMask;\n \n return comp;\n}\n\n// Thanks to http://devmaster.net/\nvec2 packHalf(float depth) \n{ \n const vec2 bitOffset = vec2(1.0 / 255., 0.);\n vec2 color = vec2(depth, fract(depth * 255.));\n\n return color - (color.yy * bitOffset);\n}\n\n#ifndef VSM\nvarying vec4 vPosition;\n#endif\n\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n\nvoid main(void)\n{\n#ifdef ALPHATEST\n if (texture2D(diffuseSampler, vUV).a < 0.4)\n discard;\n#endif\n\n#ifdef VSM\n float moment1 = gl_FragCoord.z / gl_FragCoord.w;\n float moment2 = moment1 * moment1;\n gl_FragColor = vec4(packHalf(moment1), packHalf(moment2));\n#else\n gl_FragColor = pack(vPosition.z / vPosition.w);\n#endif\n}",
  13576. shadowMapVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Attribute\nattribute vec3 position;\n#ifdef BONES\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#endif\n\n// Uniform\n#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif\n\nuniform mat4 viewProjection;\n#ifdef BONES\nuniform mat4 mBones[BonesPerMesh];\n#endif\n\n#ifndef VSM\nvarying vec4 vPosition;\n#endif\n\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n\nvoid main(void)\n{\n#ifdef INSTANCES\n mat4 finalWorld = mat4(world0, world1, world2, world3);\n#else\n mat4 finalWorld = world;\n#endif\n\n#ifdef BONES\n mat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\n mat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\n mat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\n mat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\n finalWorld = finalWorld * (m0 + m1 + m2 + m3);\n gl_Position = viewProjection * finalWorld * vec4(position, 1.0);\n#else\n#ifndef VSM\n vPosition = viewProjection * finalWorld * vec4(position, 1.0);\n#endif\n gl_Position = viewProjection * finalWorld * vec4(position, 1.0);\n#endif\n\n#ifdef ALPHATEST\n#ifdef UV1\n vUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\n#endif\n#ifdef UV2\n vUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\n#endif\n#endif\n}",
  13577. 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}",
  13578. 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}",
  13579. 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}",
  13580. 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}",
  13581. 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}",
  13582. volumetricLightScatteringPassPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n#if defined(ALPHATEST) || defined(BASIC_RENDER) || defined(OPACITY)\nvarying vec2 vUV;\n#endif\n\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\nuniform sampler2D diffuseSampler;\n#endif\n\n#if defined(OPACITY)\nuniform sampler2D opacitySampler;\n#endif\n\nvoid main(void)\n{\n#if defined(ALPHATEST) || defined(OPACITY) || defined(BASIC_RENDER)\n vec4 diffuseColor = texture2D(diffuseSampler, vUV);\n#endif\n\n#ifdef ALPHATEST\n if (diffuseColor.a < 0.4)\n discard;\n#endif\n\n#ifdef BASIC_RENDER\n#ifdef OPACITY\n gl_FragColor = diffuseColor * texture2D(opacitySampler, vUV);\n#else\n gl_FragColor = diffuseColor;\n#endif\n#else\n gl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\n#endif\n\n}",
  13583. 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}",
  13584. };
  13585. return Effect;
  13586. })();
  13587. BABYLON.Effect = Effect;
  13588. })(BABYLON || (BABYLON = {}));
  13589. //# sourceMappingURL=babylon.effect.js.mapvar BABYLON;
  13590. (function (BABYLON) {
  13591. var Material = (function () {
  13592. function Material(name, scene, doNotAdd) {
  13593. this.name = name;
  13594. this.checkReadyOnEveryCall = true;
  13595. this.checkReadyOnlyOnce = false;
  13596. this.state = "";
  13597. this.alpha = 1.0;
  13598. this.backFaceCulling = true;
  13599. this._wasPreviouslyReady = false;
  13600. this._fillMode = Material.TriangleFillMode;
  13601. this.pointSize = 1.0;
  13602. this.id = name;
  13603. this._scene = scene;
  13604. if (!doNotAdd) {
  13605. scene.materials.push(this);
  13606. }
  13607. }
  13608. Object.defineProperty(Material, "TriangleFillMode", {
  13609. get: function () {
  13610. return Material._TriangleFillMode;
  13611. },
  13612. enumerable: true,
  13613. configurable: true
  13614. });
  13615. Object.defineProperty(Material, "WireFrameFillMode", {
  13616. get: function () {
  13617. return Material._WireFrameFillMode;
  13618. },
  13619. enumerable: true,
  13620. configurable: true
  13621. });
  13622. Object.defineProperty(Material, "PointFillMode", {
  13623. get: function () {
  13624. return Material._PointFillMode;
  13625. },
  13626. enumerable: true,
  13627. configurable: true
  13628. });
  13629. Object.defineProperty(Material.prototype, "wireframe", {
  13630. get: function () {
  13631. return this._fillMode === Material.WireFrameFillMode;
  13632. },
  13633. set: function (value) {
  13634. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  13635. },
  13636. enumerable: true,
  13637. configurable: true
  13638. });
  13639. Object.defineProperty(Material.prototype, "pointsCloud", {
  13640. get: function () {
  13641. return this._fillMode === Material.PointFillMode;
  13642. },
  13643. set: function (value) {
  13644. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  13645. },
  13646. enumerable: true,
  13647. configurable: true
  13648. });
  13649. Object.defineProperty(Material.prototype, "fillMode", {
  13650. get: function () {
  13651. return this._fillMode;
  13652. },
  13653. set: function (value) {
  13654. this._fillMode = value;
  13655. },
  13656. enumerable: true,
  13657. configurable: true
  13658. });
  13659. Material.prototype.isReady = function (mesh, useInstances) {
  13660. return true;
  13661. };
  13662. Material.prototype.getEffect = function () {
  13663. return this._effect;
  13664. };
  13665. Material.prototype.getScene = function () {
  13666. return this._scene;
  13667. };
  13668. Material.prototype.needAlphaBlending = function () {
  13669. return (this.alpha < 1.0);
  13670. };
  13671. Material.prototype.needAlphaTesting = function () {
  13672. return false;
  13673. };
  13674. Material.prototype.getAlphaTestTexture = function () {
  13675. return null;
  13676. };
  13677. Material.prototype.trackCreation = function (onCompiled, onError) {
  13678. };
  13679. Material.prototype._preBind = function () {
  13680. var engine = this._scene.getEngine();
  13681. engine.enableEffect(this._effect);
  13682. engine.setState(this.backFaceCulling);
  13683. };
  13684. Material.prototype.bind = function (world, mesh) {
  13685. this._scene._cachedMaterial = this;
  13686. if (this.onBind) {
  13687. this.onBind(this);
  13688. }
  13689. };
  13690. Material.prototype.bindOnlyWorldMatrix = function (world) {
  13691. };
  13692. Material.prototype.unbind = function () {
  13693. };
  13694. Material.prototype.dispose = function (forceDisposeEffect) {
  13695. // Remove from scene
  13696. var index = this._scene.materials.indexOf(this);
  13697. this._scene.materials.splice(index, 1);
  13698. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  13699. if (forceDisposeEffect && this._effect) {
  13700. this._scene.getEngine()._releaseEffect(this._effect);
  13701. this._effect = null;
  13702. }
  13703. // Callback
  13704. if (this.onDispose) {
  13705. this.onDispose();
  13706. }
  13707. };
  13708. Material._TriangleFillMode = 0;
  13709. Material._WireFrameFillMode = 1;
  13710. Material._PointFillMode = 2;
  13711. return Material;
  13712. })();
  13713. BABYLON.Material = Material;
  13714. })(BABYLON || (BABYLON = {}));
  13715. //# sourceMappingURL=babylon.material.js.map
  13716. var BABYLON;
  13717. (function (BABYLON) {
  13718. var maxSimultaneousLights = 4;
  13719. var FresnelParameters = (function () {
  13720. function FresnelParameters() {
  13721. this.isEnabled = true;
  13722. this.leftColor = BABYLON.Color3.White();
  13723. this.rightColor = BABYLON.Color3.Black();
  13724. this.bias = 0;
  13725. this.power = 1;
  13726. }
  13727. return FresnelParameters;
  13728. })();
  13729. BABYLON.FresnelParameters = FresnelParameters;
  13730. var StandardMaterial = (function (_super) {
  13731. __extends(StandardMaterial, _super);
  13732. function StandardMaterial(name, scene) {
  13733. var _this = this;
  13734. _super.call(this, name, scene);
  13735. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  13736. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  13737. this.specularColor = new BABYLON.Color3(1, 1, 1);
  13738. this.specularPower = 64;
  13739. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  13740. this.useAlphaFromDiffuseTexture = false;
  13741. this.useSpecularOverAlpha = true;
  13742. this.fogEnabled = true;
  13743. this._cachedDefines = null;
  13744. this._renderTargets = new BABYLON.SmartArray(16);
  13745. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  13746. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  13747. this._scaledDiffuse = new BABYLON.Color3();
  13748. this._scaledSpecular = new BABYLON.Color3();
  13749. this.getRenderTargetTextures = function () {
  13750. _this._renderTargets.reset();
  13751. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  13752. _this._renderTargets.push(_this.reflectionTexture);
  13753. }
  13754. return _this._renderTargets;
  13755. };
  13756. }
  13757. StandardMaterial.prototype.needAlphaBlending = function () {
  13758. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  13759. };
  13760. StandardMaterial.prototype.needAlphaTesting = function () {
  13761. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && !this.diffuseTexture.getAlphaFromRGB;
  13762. };
  13763. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  13764. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  13765. };
  13766. StandardMaterial.prototype.getAlphaTestTexture = function () {
  13767. return this.diffuseTexture;
  13768. };
  13769. // Methods
  13770. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  13771. if (this.checkReadyOnlyOnce) {
  13772. if (this._wasPreviouslyReady) {
  13773. return true;
  13774. }
  13775. }
  13776. var scene = this.getScene();
  13777. if (!this.checkReadyOnEveryCall) {
  13778. if (this._renderId === scene.getRenderId()) {
  13779. return true;
  13780. }
  13781. }
  13782. var engine = scene.getEngine();
  13783. var defines = [];
  13784. var fallbacks = new BABYLON.EffectFallbacks();
  13785. var needNormals = false;
  13786. var needUVs = false;
  13787. // Textures
  13788. if (scene.texturesEnabled) {
  13789. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  13790. if (!this.diffuseTexture.isReady()) {
  13791. return false;
  13792. }
  13793. else {
  13794. needUVs = true;
  13795. defines.push("#define DIFFUSE");
  13796. }
  13797. }
  13798. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  13799. if (!this.ambientTexture.isReady()) {
  13800. return false;
  13801. }
  13802. else {
  13803. needUVs = true;
  13804. defines.push("#define AMBIENT");
  13805. }
  13806. }
  13807. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  13808. if (!this.opacityTexture.isReady()) {
  13809. return false;
  13810. }
  13811. else {
  13812. needUVs = true;
  13813. defines.push("#define OPACITY");
  13814. if (this.opacityTexture.getAlphaFromRGB) {
  13815. defines.push("#define OPACITYRGB");
  13816. }
  13817. }
  13818. }
  13819. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  13820. if (!this.reflectionTexture.isReady()) {
  13821. return false;
  13822. }
  13823. else {
  13824. needNormals = true;
  13825. needUVs = true;
  13826. defines.push("#define REFLECTION");
  13827. fallbacks.addFallback(0, "REFLECTION");
  13828. }
  13829. }
  13830. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  13831. if (!this.emissiveTexture.isReady()) {
  13832. return false;
  13833. }
  13834. else {
  13835. needUVs = true;
  13836. defines.push("#define EMISSIVE");
  13837. }
  13838. }
  13839. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  13840. if (!this.specularTexture.isReady()) {
  13841. return false;
  13842. }
  13843. else {
  13844. needUVs = true;
  13845. defines.push("#define SPECULAR");
  13846. fallbacks.addFallback(0, "SPECULAR");
  13847. }
  13848. }
  13849. }
  13850. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  13851. if (!this.bumpTexture.isReady()) {
  13852. return false;
  13853. }
  13854. else {
  13855. needUVs = true;
  13856. defines.push("#define BUMP");
  13857. fallbacks.addFallback(0, "BUMP");
  13858. }
  13859. }
  13860. // Effect
  13861. if (this.useSpecularOverAlpha) {
  13862. defines.push("#define SPECULAROVERALPHA");
  13863. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  13864. }
  13865. if (scene.clipPlane) {
  13866. defines.push("#define CLIPPLANE");
  13867. }
  13868. if (engine.getAlphaTesting()) {
  13869. defines.push("#define ALPHATEST");
  13870. }
  13871. if (this._shouldUseAlphaFromDiffuseTexture()) {
  13872. defines.push("#define ALPHAFROMDIFFUSE");
  13873. }
  13874. // Point size
  13875. if (this.pointsCloud || scene.forcePointsCloud) {
  13876. defines.push("#define POINTSIZE");
  13877. }
  13878. // Fog
  13879. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  13880. defines.push("#define FOG");
  13881. fallbacks.addFallback(1, "FOG");
  13882. }
  13883. var shadowsActivated = false;
  13884. var lightIndex = 0;
  13885. if (scene.lightsEnabled) {
  13886. for (var index = 0; index < scene.lights.length; index++) {
  13887. var light = scene.lights[index];
  13888. if (!light.isEnabled()) {
  13889. continue;
  13890. }
  13891. // Excluded check
  13892. if (light._excludedMeshesIds.length > 0) {
  13893. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  13894. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  13895. if (excludedMesh) {
  13896. light.excludedMeshes.push(excludedMesh);
  13897. }
  13898. }
  13899. light._excludedMeshesIds = [];
  13900. }
  13901. // Included check
  13902. if (light._includedOnlyMeshesIds.length > 0) {
  13903. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  13904. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  13905. if (includedOnlyMesh) {
  13906. light.includedOnlyMeshes.push(includedOnlyMesh);
  13907. }
  13908. }
  13909. light._includedOnlyMeshesIds = [];
  13910. }
  13911. if (!light.canAffectMesh(mesh)) {
  13912. continue;
  13913. }
  13914. needNormals = true;
  13915. defines.push("#define LIGHT" + lightIndex);
  13916. if (lightIndex > 0) {
  13917. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  13918. }
  13919. var type;
  13920. if (light instanceof BABYLON.SpotLight) {
  13921. type = "#define SPOTLIGHT" + lightIndex;
  13922. }
  13923. else if (light instanceof BABYLON.HemisphericLight) {
  13924. type = "#define HEMILIGHT" + lightIndex;
  13925. }
  13926. else {
  13927. type = "#define POINTDIRLIGHT" + lightIndex;
  13928. }
  13929. defines.push(type);
  13930. if (lightIndex > 0) {
  13931. fallbacks.addFallback(lightIndex, type.replace("#define ", ""));
  13932. }
  13933. // Shadows
  13934. if (scene.shadowsEnabled) {
  13935. var shadowGenerator = light.getShadowGenerator();
  13936. if (mesh && mesh.receiveShadows && shadowGenerator) {
  13937. defines.push("#define SHADOW" + lightIndex);
  13938. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  13939. if (!shadowsActivated) {
  13940. defines.push("#define SHADOWS");
  13941. shadowsActivated = true;
  13942. }
  13943. if (shadowGenerator.useVarianceShadowMap) {
  13944. defines.push("#define SHADOWVSM" + lightIndex);
  13945. if (lightIndex > 0) {
  13946. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  13947. }
  13948. }
  13949. if (shadowGenerator.usePoissonSampling) {
  13950. defines.push("#define SHADOWPCF" + lightIndex);
  13951. if (lightIndex > 0) {
  13952. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  13953. }
  13954. }
  13955. }
  13956. }
  13957. lightIndex++;
  13958. if (lightIndex === maxSimultaneousLights)
  13959. break;
  13960. }
  13961. }
  13962. if (StandardMaterial.FresnelEnabled) {
  13963. // Fresnel
  13964. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled || this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled || this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  13965. var fresnelRank = 1;
  13966. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  13967. defines.push("#define DIFFUSEFRESNEL");
  13968. fallbacks.addFallback(fresnelRank, "DIFFUSEFRESNEL");
  13969. fresnelRank++;
  13970. }
  13971. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  13972. defines.push("#define OPACITYFRESNEL");
  13973. fallbacks.addFallback(fresnelRank, "OPACITYFRESNEL");
  13974. fresnelRank++;
  13975. }
  13976. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  13977. defines.push("#define REFLECTIONFRESNEL");
  13978. fallbacks.addFallback(fresnelRank, "REFLECTIONFRESNEL");
  13979. fresnelRank++;
  13980. }
  13981. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  13982. defines.push("#define EMISSIVEFRESNEL");
  13983. fallbacks.addFallback(fresnelRank, "EMISSIVEFRESNEL");
  13984. fresnelRank++;
  13985. }
  13986. needNormals = true;
  13987. defines.push("#define FRESNEL");
  13988. fallbacks.addFallback(fresnelRank - 1, "FRESNEL");
  13989. }
  13990. }
  13991. // Attribs
  13992. var attribs = [BABYLON.VertexBuffer.PositionKind];
  13993. if (mesh) {
  13994. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  13995. attribs.push(BABYLON.VertexBuffer.NormalKind);
  13996. defines.push("#define NORMAL");
  13997. }
  13998. if (needUVs) {
  13999. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  14000. attribs.push(BABYLON.VertexBuffer.UVKind);
  14001. defines.push("#define UV1");
  14002. }
  14003. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  14004. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  14005. defines.push("#define UV2");
  14006. }
  14007. }
  14008. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  14009. attribs.push(BABYLON.VertexBuffer.ColorKind);
  14010. defines.push("#define VERTEXCOLOR");
  14011. if (mesh.hasVertexAlpha) {
  14012. defines.push("#define VERTEXALPHA");
  14013. }
  14014. }
  14015. if (mesh.useBones) {
  14016. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  14017. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  14018. defines.push("#define BONES");
  14019. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  14020. defines.push("#define BONES4");
  14021. fallbacks.addFallback(0, "BONES4");
  14022. }
  14023. // Instances
  14024. if (useInstances) {
  14025. defines.push("#define INSTANCES");
  14026. attribs.push("world0");
  14027. attribs.push("world1");
  14028. attribs.push("world2");
  14029. attribs.push("world3");
  14030. }
  14031. }
  14032. // Get correct effect
  14033. var join = defines.join("\n");
  14034. if (this._cachedDefines !== join) {
  14035. this._cachedDefines = join;
  14036. scene.resetCachedMaterial();
  14037. // Legacy browser patch
  14038. var shaderName = "default";
  14039. if (!scene.getEngine().getCaps().standardDerivatives) {
  14040. shaderName = "legacydefault";
  14041. }
  14042. 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", "darkness0", "darkness1", "darkness2", "darkness3", "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);
  14043. }
  14044. if (!this._effect.isReady()) {
  14045. return false;
  14046. }
  14047. this._renderId = scene.getRenderId();
  14048. this._wasPreviouslyReady = true;
  14049. return true;
  14050. };
  14051. StandardMaterial.prototype.unbind = function () {
  14052. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  14053. this._effect.setTexture("reflection2DSampler", null);
  14054. }
  14055. };
  14056. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  14057. this._effect.setMatrix("world", world);
  14058. };
  14059. StandardMaterial.prototype.bind = function (world, mesh) {
  14060. var scene = this.getScene();
  14061. // Matrices
  14062. this.bindOnlyWorldMatrix(world);
  14063. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  14064. // Bones
  14065. if (mesh.useBones) {
  14066. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  14067. }
  14068. if (scene.getCachedMaterial() !== this) {
  14069. if (StandardMaterial.FresnelEnabled) {
  14070. // Fresnel
  14071. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  14072. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  14073. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  14074. }
  14075. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  14076. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  14077. }
  14078. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  14079. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  14080. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  14081. }
  14082. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  14083. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  14084. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  14085. }
  14086. }
  14087. // Textures
  14088. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  14089. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  14090. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  14091. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  14092. }
  14093. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  14094. this._effect.setTexture("ambientSampler", this.ambientTexture);
  14095. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  14096. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  14097. }
  14098. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  14099. this._effect.setTexture("opacitySampler", this.opacityTexture);
  14100. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  14101. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  14102. }
  14103. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  14104. if (this.reflectionTexture.isCube) {
  14105. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  14106. }
  14107. else {
  14108. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  14109. }
  14110. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  14111. this._effect.setFloat3("vReflectionInfos", this.reflectionTexture.coordinatesMode, this.reflectionTexture.level, this.reflectionTexture.isCube ? 1 : 0);
  14112. }
  14113. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  14114. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  14115. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  14116. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  14117. }
  14118. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  14119. this._effect.setTexture("specularSampler", this.specularTexture);
  14120. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  14121. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  14122. }
  14123. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  14124. this._effect.setTexture("bumpSampler", this.bumpTexture);
  14125. this._effect.setFloat2("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level);
  14126. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  14127. }
  14128. // Clip plane
  14129. if (scene.clipPlane) {
  14130. var clipPlane = scene.clipPlane;
  14131. this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  14132. }
  14133. // Point size
  14134. if (this.pointsCloud) {
  14135. this._effect.setFloat("pointSize", this.pointSize);
  14136. }
  14137. // Colors
  14138. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  14139. // Scaling down color according to emissive
  14140. this._scaledSpecular.r = this.specularColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  14141. this._scaledSpecular.g = this.specularColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  14142. this._scaledSpecular.b = this.specularColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  14143. this._effect.setVector3("vEyePosition", scene.activeCamera.position);
  14144. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  14145. this._effect.setColor4("vSpecularColor", this._scaledSpecular, this.specularPower);
  14146. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  14147. }
  14148. // Scaling down color according to emissive
  14149. this._scaledDiffuse.r = this.diffuseColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  14150. this._scaledDiffuse.g = this.diffuseColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  14151. this._scaledDiffuse.b = this.diffuseColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  14152. this._effect.setColor4("vDiffuseColor", this._scaledDiffuse, this.alpha * mesh.visibility);
  14153. if (scene.lightsEnabled) {
  14154. var lightIndex = 0;
  14155. for (var index = 0; index < scene.lights.length; index++) {
  14156. var light = scene.lights[index];
  14157. if (!light.isEnabled()) {
  14158. continue;
  14159. }
  14160. if (!light.canAffectMesh(mesh)) {
  14161. continue;
  14162. }
  14163. if (light instanceof BABYLON.PointLight) {
  14164. // Point Light
  14165. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  14166. }
  14167. else if (light instanceof BABYLON.DirectionalLight) {
  14168. // Directional Light
  14169. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  14170. }
  14171. else if (light instanceof BABYLON.SpotLight) {
  14172. // Spot Light
  14173. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  14174. }
  14175. else if (light instanceof BABYLON.HemisphericLight) {
  14176. // Hemispheric Light
  14177. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  14178. }
  14179. light.diffuse.scaleToRef(light.intensity, this._scaledDiffuse);
  14180. light.specular.scaleToRef(light.intensity, this._scaledSpecular);
  14181. this._effect.setColor4("vLightDiffuse" + lightIndex, this._scaledDiffuse, light.range);
  14182. this._effect.setColor3("vLightSpecular" + lightIndex, this._scaledSpecular);
  14183. // Shadows
  14184. if (scene.shadowsEnabled) {
  14185. var shadowGenerator = light.getShadowGenerator();
  14186. if (mesh.receiveShadows && shadowGenerator) {
  14187. this._effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  14188. this._effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMap());
  14189. this._effect.setFloat("darkness" + lightIndex, shadowGenerator.getDarkness());
  14190. }
  14191. }
  14192. lightIndex++;
  14193. if (lightIndex === maxSimultaneousLights)
  14194. break;
  14195. }
  14196. }
  14197. // View
  14198. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  14199. this._effect.setMatrix("view", scene.getViewMatrix());
  14200. }
  14201. // Fog
  14202. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  14203. this._effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  14204. this._effect.setColor3("vFogColor", scene.fogColor);
  14205. }
  14206. _super.prototype.bind.call(this, world, mesh);
  14207. };
  14208. StandardMaterial.prototype.getAnimatables = function () {
  14209. var results = [];
  14210. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  14211. results.push(this.diffuseTexture);
  14212. }
  14213. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  14214. results.push(this.ambientTexture);
  14215. }
  14216. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  14217. results.push(this.opacityTexture);
  14218. }
  14219. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  14220. results.push(this.reflectionTexture);
  14221. }
  14222. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  14223. results.push(this.emissiveTexture);
  14224. }
  14225. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  14226. results.push(this.specularTexture);
  14227. }
  14228. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  14229. results.push(this.bumpTexture);
  14230. }
  14231. return results;
  14232. };
  14233. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  14234. if (this.diffuseTexture) {
  14235. this.diffuseTexture.dispose();
  14236. }
  14237. if (this.ambientTexture) {
  14238. this.ambientTexture.dispose();
  14239. }
  14240. if (this.opacityTexture) {
  14241. this.opacityTexture.dispose();
  14242. }
  14243. if (this.reflectionTexture) {
  14244. this.reflectionTexture.dispose();
  14245. }
  14246. if (this.emissiveTexture) {
  14247. this.emissiveTexture.dispose();
  14248. }
  14249. if (this.specularTexture) {
  14250. this.specularTexture.dispose();
  14251. }
  14252. if (this.bumpTexture) {
  14253. this.bumpTexture.dispose();
  14254. }
  14255. _super.prototype.dispose.call(this, forceDisposeEffect);
  14256. };
  14257. StandardMaterial.prototype.clone = function (name) {
  14258. var newStandardMaterial = new StandardMaterial(name, this.getScene());
  14259. // Base material
  14260. newStandardMaterial.checkReadyOnEveryCall = this.checkReadyOnEveryCall;
  14261. newStandardMaterial.alpha = this.alpha;
  14262. newStandardMaterial.fillMode = this.fillMode;
  14263. newStandardMaterial.backFaceCulling = this.backFaceCulling;
  14264. // Standard material
  14265. if (this.diffuseTexture && this.diffuseTexture.clone) {
  14266. newStandardMaterial.diffuseTexture = this.diffuseTexture.clone();
  14267. }
  14268. if (this.ambientTexture && this.ambientTexture.clone) {
  14269. newStandardMaterial.ambientTexture = this.ambientTexture.clone();
  14270. }
  14271. if (this.opacityTexture && this.opacityTexture.clone) {
  14272. newStandardMaterial.opacityTexture = this.opacityTexture.clone();
  14273. }
  14274. if (this.reflectionTexture && this.reflectionTexture.clone) {
  14275. newStandardMaterial.reflectionTexture = this.reflectionTexture.clone();
  14276. }
  14277. if (this.emissiveTexture && this.emissiveTexture.clone) {
  14278. newStandardMaterial.emissiveTexture = this.emissiveTexture.clone();
  14279. }
  14280. if (this.specularTexture && this.specularTexture.clone) {
  14281. newStandardMaterial.specularTexture = this.specularTexture.clone();
  14282. }
  14283. if (this.bumpTexture && this.bumpTexture.clone) {
  14284. newStandardMaterial.bumpTexture = this.bumpTexture.clone();
  14285. }
  14286. newStandardMaterial.ambientColor = this.ambientColor.clone();
  14287. newStandardMaterial.diffuseColor = this.diffuseColor.clone();
  14288. newStandardMaterial.specularColor = this.specularColor.clone();
  14289. newStandardMaterial.specularPower = this.specularPower;
  14290. newStandardMaterial.emissiveColor = this.emissiveColor.clone();
  14291. return newStandardMaterial;
  14292. };
  14293. // Statics
  14294. // Flags used to enable or disable a type of texture for all Standard Materials
  14295. StandardMaterial.DiffuseTextureEnabled = true;
  14296. StandardMaterial.AmbientTextureEnabled = true;
  14297. StandardMaterial.OpacityTextureEnabled = true;
  14298. StandardMaterial.ReflectionTextureEnabled = true;
  14299. StandardMaterial.EmissiveTextureEnabled = true;
  14300. StandardMaterial.SpecularTextureEnabled = true;
  14301. StandardMaterial.BumpTextureEnabled = true;
  14302. StandardMaterial.FresnelEnabled = true;
  14303. return StandardMaterial;
  14304. })(BABYLON.Material);
  14305. BABYLON.StandardMaterial = StandardMaterial;
  14306. })(BABYLON || (BABYLON = {}));
  14307. //# sourceMappingURL=babylon.standardMaterial.js.map
  14308. var BABYLON;
  14309. (function (BABYLON) {
  14310. var MultiMaterial = (function (_super) {
  14311. __extends(MultiMaterial, _super);
  14312. function MultiMaterial(name, scene) {
  14313. _super.call(this, name, scene, true);
  14314. this.subMaterials = new Array();
  14315. scene.multiMaterials.push(this);
  14316. }
  14317. // Properties
  14318. MultiMaterial.prototype.getSubMaterial = function (index) {
  14319. if (index < 0 || index >= this.subMaterials.length) {
  14320. return this.getScene().defaultMaterial;
  14321. }
  14322. return this.subMaterials[index];
  14323. };
  14324. // Methods
  14325. MultiMaterial.prototype.isReady = function (mesh) {
  14326. for (var index = 0; index < this.subMaterials.length; index++) {
  14327. var subMaterial = this.subMaterials[index];
  14328. if (subMaterial) {
  14329. if (!this.subMaterials[index].isReady(mesh)) {
  14330. return false;
  14331. }
  14332. }
  14333. }
  14334. return true;
  14335. };
  14336. return MultiMaterial;
  14337. })(BABYLON.Material);
  14338. BABYLON.MultiMaterial = MultiMaterial;
  14339. })(BABYLON || (BABYLON = {}));
  14340. //# sourceMappingURL=babylon.multiMaterial.js.mapvar BABYLON;
  14341. (function (BABYLON) {
  14342. var Database = (function () {
  14343. function Database(urlToScene, callbackManifestChecked) {
  14344. // Handling various flavors of prefixed version of IndexedDB
  14345. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  14346. this.callbackManifestChecked = callbackManifestChecked;
  14347. this.currentSceneUrl = BABYLON.Database.ReturnFullUrlLocation(urlToScene);
  14348. this.db = null;
  14349. this.enableSceneOffline = false;
  14350. this.enableTexturesOffline = false;
  14351. this.manifestVersionFound = 0;
  14352. this.mustUpdateRessources = false;
  14353. this.hasReachedQuota = false;
  14354. this.checkManifestFile();
  14355. }
  14356. Database.prototype.checkManifestFile = function () {
  14357. var _this = this;
  14358. function noManifestFile() {
  14359. //BABYLON.Tools.Log("Valid manifest file not found. Scene & textures will be loaded directly from the web server.");
  14360. that.enableSceneOffline = false;
  14361. that.enableTexturesOffline = false;
  14362. that.callbackManifestChecked(false);
  14363. }
  14364. var that = this;
  14365. var manifestURL = this.currentSceneUrl + ".manifest";
  14366. var xhr = new XMLHttpRequest();
  14367. var manifestURLTimeStamped = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  14368. xhr.open("GET", manifestURLTimeStamped, true);
  14369. xhr.addEventListener("load", function () {
  14370. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  14371. try {
  14372. var manifestFile = JSON.parse(xhr.response);
  14373. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  14374. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  14375. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  14376. _this.manifestVersionFound = manifestFile.version;
  14377. }
  14378. if (_this.callbackManifestChecked) {
  14379. _this.callbackManifestChecked(true);
  14380. }
  14381. }
  14382. catch (ex) {
  14383. noManifestFile();
  14384. }
  14385. }
  14386. else {
  14387. noManifestFile();
  14388. }
  14389. }, false);
  14390. xhr.addEventListener("error", function (event) {
  14391. noManifestFile();
  14392. }, false);
  14393. try {
  14394. xhr.send();
  14395. }
  14396. catch (ex) {
  14397. BABYLON.Tools.Error("Error on XHR send request.");
  14398. that.callbackManifestChecked(false);
  14399. }
  14400. };
  14401. Database.prototype.openAsync = function (successCallback, errorCallback) {
  14402. var _this = this;
  14403. function handleError() {
  14404. that.isSupported = false;
  14405. if (errorCallback)
  14406. errorCallback();
  14407. }
  14408. var that = this;
  14409. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  14410. // Your browser doesn't support IndexedDB
  14411. this.isSupported = false;
  14412. if (errorCallback)
  14413. errorCallback();
  14414. }
  14415. else {
  14416. // If the DB hasn't been opened or created yet
  14417. if (!this.db) {
  14418. this.hasReachedQuota = false;
  14419. this.isSupported = true;
  14420. var request = this.idbFactory.open("babylonjs", 1);
  14421. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  14422. request.onerror = function (event) {
  14423. handleError();
  14424. };
  14425. // executes when a version change transaction cannot complete due to other active transactions
  14426. request.onblocked = function (event) {
  14427. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  14428. handleError();
  14429. };
  14430. // DB has been opened successfully
  14431. request.onsuccess = function (event) {
  14432. _this.db = request.result;
  14433. successCallback();
  14434. };
  14435. // Initialization of the DB. Creating Scenes & Textures stores
  14436. request.onupgradeneeded = function (event) {
  14437. _this.db = (event.target).result;
  14438. try {
  14439. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  14440. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  14441. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  14442. }
  14443. catch (ex) {
  14444. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  14445. handleError();
  14446. }
  14447. };
  14448. }
  14449. else {
  14450. if (successCallback)
  14451. successCallback();
  14452. }
  14453. }
  14454. };
  14455. Database.prototype.loadImageFromDB = function (url, image) {
  14456. var _this = this;
  14457. var completeURL = Database.ReturnFullUrlLocation(url);
  14458. var saveAndLoadImage = function () {
  14459. if (!_this.hasReachedQuota && _this.db !== null) {
  14460. // the texture is not yet in the DB, let's try to save it
  14461. _this._saveImageIntoDBAsync(completeURL, image);
  14462. }
  14463. else {
  14464. image.src = url;
  14465. }
  14466. };
  14467. if (!this.mustUpdateRessources) {
  14468. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  14469. }
  14470. else {
  14471. saveAndLoadImage();
  14472. }
  14473. };
  14474. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  14475. if (this.isSupported && this.db !== null) {
  14476. var texture;
  14477. var transaction = this.db.transaction(["textures"]);
  14478. transaction.onabort = function (event) {
  14479. image.src = url;
  14480. };
  14481. transaction.oncomplete = function (event) {
  14482. var blobTextureURL;
  14483. if (texture) {
  14484. var URL = window.URL || window.webkitURL;
  14485. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  14486. image.onerror = function () {
  14487. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  14488. image.src = url;
  14489. };
  14490. image.src = blobTextureURL;
  14491. }
  14492. else {
  14493. notInDBCallback();
  14494. }
  14495. };
  14496. var getRequest = transaction.objectStore("textures").get(url);
  14497. getRequest.onsuccess = function (event) {
  14498. texture = (event.target).result;
  14499. };
  14500. getRequest.onerror = function (event) {
  14501. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  14502. image.src = url;
  14503. };
  14504. }
  14505. else {
  14506. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  14507. image.src = url;
  14508. }
  14509. };
  14510. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  14511. var _this = this;
  14512. if (this.isSupported) {
  14513. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  14514. var generateBlobUrl = function () {
  14515. var blobTextureURL;
  14516. if (blob) {
  14517. var URL = window.URL || window.webkitURL;
  14518. try {
  14519. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  14520. }
  14521. catch (ex) {
  14522. blobTextureURL = URL.createObjectURL(blob);
  14523. }
  14524. }
  14525. image.src = blobTextureURL;
  14526. };
  14527. if (Database.isUASupportingBlobStorage) {
  14528. var xhr = new XMLHttpRequest(), blob;
  14529. xhr.open("GET", url, true);
  14530. xhr.responseType = "blob";
  14531. xhr.addEventListener("load", function () {
  14532. if (xhr.status === 200) {
  14533. // Blob as response (XHR2)
  14534. blob = xhr.response;
  14535. var transaction = _this.db.transaction(["textures"], "readwrite");
  14536. // the transaction could abort because of a QuotaExceededError error
  14537. transaction.onabort = function (event) {
  14538. try {
  14539. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  14540. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  14541. this.hasReachedQuota = true;
  14542. }
  14543. }
  14544. catch (ex) {
  14545. }
  14546. generateBlobUrl();
  14547. };
  14548. transaction.oncomplete = function (event) {
  14549. generateBlobUrl();
  14550. };
  14551. var newTexture = { textureUrl: url, data: blob };
  14552. try {
  14553. // Put the blob into the dabase
  14554. var addRequest = transaction.objectStore("textures").put(newTexture);
  14555. addRequest.onsuccess = function (event) {
  14556. };
  14557. addRequest.onerror = function (event) {
  14558. generateBlobUrl();
  14559. };
  14560. }
  14561. catch (ex) {
  14562. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  14563. if (ex.code === 25) {
  14564. Database.isUASupportingBlobStorage = false;
  14565. }
  14566. image.src = url;
  14567. }
  14568. }
  14569. else {
  14570. image.src = url;
  14571. }
  14572. }, false);
  14573. xhr.addEventListener("error", function (event) {
  14574. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  14575. image.src = url;
  14576. }, false);
  14577. xhr.send();
  14578. }
  14579. else {
  14580. image.src = url;
  14581. }
  14582. }
  14583. else {
  14584. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  14585. image.src = url;
  14586. }
  14587. };
  14588. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  14589. var _this = this;
  14590. var updateVersion = function (event) {
  14591. // the version is not yet in the DB or we need to update it
  14592. _this._saveVersionIntoDBAsync(url, versionLoaded);
  14593. };
  14594. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  14595. };
  14596. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  14597. var _this = this;
  14598. if (this.isSupported) {
  14599. var version;
  14600. try {
  14601. var transaction = this.db.transaction(["versions"]);
  14602. transaction.oncomplete = function (event) {
  14603. if (version) {
  14604. // If the version in the JSON file is > than the version in DB
  14605. if (_this.manifestVersionFound > version.data) {
  14606. _this.mustUpdateRessources = true;
  14607. updateInDBCallback();
  14608. }
  14609. else {
  14610. callback(version.data);
  14611. }
  14612. }
  14613. else {
  14614. _this.mustUpdateRessources = true;
  14615. updateInDBCallback();
  14616. }
  14617. };
  14618. transaction.onabort = function (event) {
  14619. callback(-1);
  14620. };
  14621. var getRequest = transaction.objectStore("versions").get(url);
  14622. getRequest.onsuccess = function (event) {
  14623. version = (event.target).result;
  14624. };
  14625. getRequest.onerror = function (event) {
  14626. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  14627. callback(-1);
  14628. };
  14629. }
  14630. catch (ex) {
  14631. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  14632. callback(-1);
  14633. }
  14634. }
  14635. else {
  14636. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  14637. callback(-1);
  14638. }
  14639. };
  14640. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  14641. var _this = this;
  14642. if (this.isSupported && !this.hasReachedQuota) {
  14643. try {
  14644. // Open a transaction to the database
  14645. var transaction = this.db.transaction(["versions"], "readwrite");
  14646. // the transaction could abort because of a QuotaExceededError error
  14647. transaction.onabort = function (event) {
  14648. try {
  14649. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  14650. _this.hasReachedQuota = true;
  14651. }
  14652. }
  14653. catch (ex) {
  14654. }
  14655. callback(-1);
  14656. };
  14657. transaction.oncomplete = function (event) {
  14658. callback(_this.manifestVersionFound);
  14659. };
  14660. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  14661. // Put the scene into the database
  14662. var addRequest = transaction.objectStore("versions").put(newVersion);
  14663. addRequest.onsuccess = function (event) {
  14664. };
  14665. addRequest.onerror = function (event) {
  14666. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  14667. };
  14668. }
  14669. catch (ex) {
  14670. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  14671. callback(-1);
  14672. }
  14673. }
  14674. else {
  14675. callback(-1);
  14676. }
  14677. };
  14678. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  14679. var _this = this;
  14680. var completeUrl = Database.ReturnFullUrlLocation(url);
  14681. var saveAndLoadFile = function (event) {
  14682. // the scene is not yet in the DB, let's try to save it
  14683. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  14684. };
  14685. this._checkVersionFromDB(completeUrl, function (version) {
  14686. if (version !== -1) {
  14687. if (!_this.mustUpdateRessources) {
  14688. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  14689. }
  14690. else {
  14691. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  14692. }
  14693. }
  14694. else {
  14695. errorCallback();
  14696. }
  14697. });
  14698. };
  14699. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  14700. if (this.isSupported) {
  14701. var targetStore;
  14702. if (url.indexOf(".babylon") !== -1) {
  14703. targetStore = "scenes";
  14704. }
  14705. else {
  14706. targetStore = "textures";
  14707. }
  14708. var file;
  14709. var transaction = this.db.transaction([targetStore]);
  14710. transaction.oncomplete = function (event) {
  14711. if (file) {
  14712. callback(file.data);
  14713. }
  14714. else {
  14715. notInDBCallback();
  14716. }
  14717. };
  14718. transaction.onabort = function (event) {
  14719. notInDBCallback();
  14720. };
  14721. var getRequest = transaction.objectStore(targetStore).get(url);
  14722. getRequest.onsuccess = function (event) {
  14723. file = (event.target).result;
  14724. };
  14725. getRequest.onerror = function (event) {
  14726. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  14727. notInDBCallback();
  14728. };
  14729. }
  14730. else {
  14731. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  14732. callback();
  14733. }
  14734. };
  14735. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  14736. var _this = this;
  14737. if (this.isSupported) {
  14738. var targetStore;
  14739. if (url.indexOf(".babylon") !== -1) {
  14740. targetStore = "scenes";
  14741. }
  14742. else {
  14743. targetStore = "textures";
  14744. }
  14745. // Create XHR
  14746. var xhr = new XMLHttpRequest(), fileData;
  14747. xhr.open("GET", url, true);
  14748. if (useArrayBuffer) {
  14749. xhr.responseType = "arraybuffer";
  14750. }
  14751. xhr.onprogress = progressCallback;
  14752. xhr.addEventListener("load", function () {
  14753. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  14754. // Blob as response (XHR2)
  14755. //fileData = xhr.responseText;
  14756. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  14757. if (!_this.hasReachedQuota) {
  14758. // Open a transaction to the database
  14759. var transaction = _this.db.transaction([targetStore], "readwrite");
  14760. // the transaction could abort because of a QuotaExceededError error
  14761. transaction.onabort = function (event) {
  14762. try {
  14763. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  14764. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  14765. this.hasReachedQuota = true;
  14766. }
  14767. }
  14768. catch (ex) {
  14769. }
  14770. callback(fileData);
  14771. };
  14772. transaction.oncomplete = function (event) {
  14773. callback(fileData);
  14774. };
  14775. var newFile;
  14776. if (targetStore === "scenes") {
  14777. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  14778. }
  14779. else {
  14780. newFile = { textureUrl: url, data: fileData };
  14781. }
  14782. try {
  14783. // Put the scene into the database
  14784. var addRequest = transaction.objectStore(targetStore).put(newFile);
  14785. addRequest.onsuccess = function (event) {
  14786. };
  14787. addRequest.onerror = function (event) {
  14788. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  14789. };
  14790. }
  14791. catch (ex) {
  14792. callback(fileData);
  14793. }
  14794. }
  14795. else {
  14796. callback(fileData);
  14797. }
  14798. }
  14799. else {
  14800. callback();
  14801. }
  14802. }, false);
  14803. xhr.addEventListener("error", function (event) {
  14804. BABYLON.Tools.Error("error on XHR request.");
  14805. callback();
  14806. }, false);
  14807. xhr.send();
  14808. }
  14809. else {
  14810. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  14811. callback();
  14812. }
  14813. };
  14814. Database.isUASupportingBlobStorage = true;
  14815. Database.parseURL = function (url) {
  14816. var a = document.createElement('a');
  14817. a.href = url;
  14818. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  14819. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  14820. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  14821. return absLocation;
  14822. };
  14823. Database.ReturnFullUrlLocation = function (url) {
  14824. if (url.indexOf("http:/") === -1) {
  14825. return (BABYLON.Database.parseURL(window.location.href) + url);
  14826. }
  14827. else {
  14828. return url;
  14829. }
  14830. };
  14831. return Database;
  14832. })();
  14833. BABYLON.Database = Database;
  14834. })(BABYLON || (BABYLON = {}));
  14835. //# sourceMappingURL=babylon.database.js.mapvar BABYLON;
  14836. (function (BABYLON) {
  14837. var SpriteManager = (function () {
  14838. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon) {
  14839. this.name = name;
  14840. this.cellSize = cellSize;
  14841. this.sprites = new Array();
  14842. this.renderingGroupId = 0;
  14843. this.fogEnabled = true;
  14844. this._vertexDeclaration = [3, 4, 4, 4];
  14845. this._vertexStrideSize = 15 * 4; // 15 floats per sprite (x, y, z, angle, size, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color)
  14846. this._capacity = capacity;
  14847. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false);
  14848. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  14849. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  14850. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  14851. this._scene = scene;
  14852. this._scene.spriteManagers.push(this);
  14853. // VBO
  14854. this._vertexDeclaration = [3, 4, 4, 4];
  14855. this._vertexStrideSize = 15 * 4;
  14856. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  14857. var indices = [];
  14858. var index = 0;
  14859. for (var count = 0; count < capacity; count++) {
  14860. indices.push(index);
  14861. indices.push(index + 1);
  14862. indices.push(index + 2);
  14863. indices.push(index);
  14864. indices.push(index + 2);
  14865. indices.push(index + 3);
  14866. index += 4;
  14867. }
  14868. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  14869. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  14870. // Effects
  14871. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  14872. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  14873. }
  14874. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  14875. var arrayOffset = index * 15;
  14876. if (offsetX == 0)
  14877. offsetX = this._epsilon;
  14878. else if (offsetX == 1)
  14879. offsetX = 1 - this._epsilon;
  14880. if (offsetY == 0)
  14881. offsetY = this._epsilon;
  14882. else if (offsetY == 1)
  14883. offsetY = 1 - this._epsilon;
  14884. this._vertices[arrayOffset] = sprite.position.x;
  14885. this._vertices[arrayOffset + 1] = sprite.position.y;
  14886. this._vertices[arrayOffset + 2] = sprite.position.z;
  14887. this._vertices[arrayOffset + 3] = sprite.angle;
  14888. this._vertices[arrayOffset + 4] = sprite.size;
  14889. this._vertices[arrayOffset + 5] = offsetX;
  14890. this._vertices[arrayOffset + 6] = offsetY;
  14891. this._vertices[arrayOffset + 7] = sprite.invertU ? 1 : 0;
  14892. this._vertices[arrayOffset + 8] = sprite.invertV ? 1 : 0;
  14893. var offset = (sprite.cellIndex / rowSize) >> 0;
  14894. this._vertices[arrayOffset + 9] = sprite.cellIndex - offset * rowSize;
  14895. this._vertices[arrayOffset + 10] = offset;
  14896. // Color
  14897. this._vertices[arrayOffset + 11] = sprite.color.r;
  14898. this._vertices[arrayOffset + 12] = sprite.color.g;
  14899. this._vertices[arrayOffset + 13] = sprite.color.b;
  14900. this._vertices[arrayOffset + 14] = sprite.color.a;
  14901. };
  14902. SpriteManager.prototype.render = function () {
  14903. // Check
  14904. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  14905. return;
  14906. var engine = this._scene.getEngine();
  14907. var baseSize = this._spriteTexture.getBaseSize();
  14908. // Sprites
  14909. var deltaTime = engine.getDeltaTime();
  14910. var max = Math.min(this._capacity, this.sprites.length);
  14911. var rowSize = baseSize.width / this.cellSize;
  14912. var offset = 0;
  14913. for (var index = 0; index < max; index++) {
  14914. var sprite = this.sprites[index];
  14915. if (!sprite) {
  14916. continue;
  14917. }
  14918. sprite._animate(deltaTime);
  14919. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  14920. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  14921. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  14922. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  14923. }
  14924. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  14925. // Render
  14926. var effect = this._effectBase;
  14927. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  14928. effect = this._effectFog;
  14929. }
  14930. engine.enableEffect(effect);
  14931. var viewMatrix = this._scene.getViewMatrix();
  14932. effect.setTexture("diffuseSampler", this._spriteTexture);
  14933. effect.setMatrix("view", viewMatrix);
  14934. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  14935. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  14936. // Fog
  14937. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  14938. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  14939. effect.setColor3("vFogColor", this._scene.fogColor);
  14940. }
  14941. // VBOs
  14942. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  14943. // Draw order
  14944. effect.setBool("alphaTest", true);
  14945. engine.setColorWrite(false);
  14946. engine.draw(true, 0, max * 6);
  14947. engine.setColorWrite(true);
  14948. effect.setBool("alphaTest", false);
  14949. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  14950. engine.draw(true, 0, max * 6);
  14951. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  14952. };
  14953. SpriteManager.prototype.dispose = function () {
  14954. if (this._vertexBuffer) {
  14955. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  14956. this._vertexBuffer = null;
  14957. }
  14958. if (this._indexBuffer) {
  14959. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  14960. this._indexBuffer = null;
  14961. }
  14962. if (this._spriteTexture) {
  14963. this._spriteTexture.dispose();
  14964. this._spriteTexture = null;
  14965. }
  14966. // Remove from scene
  14967. var index = this._scene.spriteManagers.indexOf(this);
  14968. this._scene.spriteManagers.splice(index, 1);
  14969. // Callback
  14970. if (this.onDispose) {
  14971. this.onDispose();
  14972. }
  14973. };
  14974. return SpriteManager;
  14975. })();
  14976. BABYLON.SpriteManager = SpriteManager;
  14977. })(BABYLON || (BABYLON = {}));
  14978. //# sourceMappingURL=babylon.spriteManager.js.mapvar BABYLON;
  14979. (function (BABYLON) {
  14980. var Sprite = (function () {
  14981. function Sprite(name, manager) {
  14982. this.name = name;
  14983. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  14984. this.size = 1.0;
  14985. this.angle = 0;
  14986. this.cellIndex = 0;
  14987. this.invertU = 0;
  14988. this.invertV = 0;
  14989. this.animations = new Array();
  14990. this._animationStarted = false;
  14991. this._loopAnimation = false;
  14992. this._fromIndex = 0;
  14993. this._toIndex = 0;
  14994. this._delay = 0;
  14995. this._direction = 1;
  14996. this._frameCount = 0;
  14997. this._time = 0;
  14998. this._manager = manager;
  14999. this._manager.sprites.push(this);
  15000. this.position = BABYLON.Vector3.Zero();
  15001. }
  15002. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  15003. this._fromIndex = from;
  15004. this._toIndex = to;
  15005. this._loopAnimation = loop;
  15006. this._delay = delay;
  15007. this._animationStarted = true;
  15008. this._direction = from < to ? 1 : -1;
  15009. this.cellIndex = from;
  15010. this._time = 0;
  15011. };
  15012. Sprite.prototype.stopAnimation = function () {
  15013. this._animationStarted = false;
  15014. };
  15015. Sprite.prototype._animate = function (deltaTime) {
  15016. if (!this._animationStarted)
  15017. return;
  15018. this._time += deltaTime;
  15019. if (this._time > this._delay) {
  15020. this._time = this._time % this._delay;
  15021. this.cellIndex += this._direction;
  15022. if (this.cellIndex == this._toIndex) {
  15023. if (this._loopAnimation) {
  15024. this.cellIndex = this._fromIndex;
  15025. }
  15026. else {
  15027. this._animationStarted = false;
  15028. if (this.disposeWhenFinishedAnimating) {
  15029. this.dispose();
  15030. }
  15031. }
  15032. }
  15033. }
  15034. };
  15035. Sprite.prototype.dispose = function () {
  15036. for (var i = 0; i < this._manager.sprites.length; i++) {
  15037. if (this._manager.sprites[i] == this) {
  15038. this._manager.sprites.splice(i, 1);
  15039. }
  15040. }
  15041. };
  15042. return Sprite;
  15043. })();
  15044. BABYLON.Sprite = Sprite;
  15045. })(BABYLON || (BABYLON = {}));
  15046. //# sourceMappingURL=babylon.sprite.js.mapvar BABYLON;
  15047. (function (BABYLON) {
  15048. var Layer = (function () {
  15049. function Layer(name, imgUrl, scene, isBackground, color) {
  15050. this.name = name;
  15051. this._vertexDeclaration = [2];
  15052. this._vertexStrideSize = 2 * 4;
  15053. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  15054. this.isBackground = isBackground === undefined ? true : isBackground;
  15055. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  15056. this._scene = scene;
  15057. this._scene.layers.push(this);
  15058. // VBO
  15059. var vertices = [];
  15060. vertices.push(1, 1);
  15061. vertices.push(-1, 1);
  15062. vertices.push(-1, -1);
  15063. vertices.push(1, -1);
  15064. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  15065. // Indices
  15066. var indices = [];
  15067. indices.push(0);
  15068. indices.push(1);
  15069. indices.push(2);
  15070. indices.push(0);
  15071. indices.push(2);
  15072. indices.push(3);
  15073. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  15074. // Effects
  15075. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color"], ["textureSampler"], "");
  15076. }
  15077. Layer.prototype.render = function () {
  15078. // Check
  15079. if (!this._effect.isReady() || !this.texture || !this.texture.isReady())
  15080. return;
  15081. var engine = this._scene.getEngine();
  15082. // Render
  15083. engine.enableEffect(this._effect);
  15084. engine.setState(false);
  15085. // Texture
  15086. this._effect.setTexture("textureSampler", this.texture);
  15087. this._effect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  15088. // Color
  15089. this._effect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  15090. // VBOs
  15091. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  15092. // Draw order
  15093. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  15094. engine.draw(true, 0, 6);
  15095. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  15096. };
  15097. Layer.prototype.dispose = function () {
  15098. if (this._vertexBuffer) {
  15099. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  15100. this._vertexBuffer = null;
  15101. }
  15102. if (this._indexBuffer) {
  15103. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  15104. this._indexBuffer = null;
  15105. }
  15106. if (this.texture) {
  15107. this.texture.dispose();
  15108. this.texture = null;
  15109. }
  15110. // Remove from scene
  15111. var index = this._scene.layers.indexOf(this);
  15112. this._scene.layers.splice(index, 1);
  15113. // Callback
  15114. if (this.onDispose) {
  15115. this.onDispose();
  15116. }
  15117. };
  15118. return Layer;
  15119. })();
  15120. BABYLON.Layer = Layer;
  15121. })(BABYLON || (BABYLON = {}));
  15122. //# sourceMappingURL=babylon.layer.js.mapvar BABYLON;
  15123. (function (BABYLON) {
  15124. var Particle = (function () {
  15125. function Particle() {
  15126. this.position = BABYLON.Vector3.Zero();
  15127. this.direction = BABYLON.Vector3.Zero();
  15128. this.color = new BABYLON.Color4(0, 0, 0, 0);
  15129. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  15130. this.lifeTime = 1.0;
  15131. this.age = 0;
  15132. this.size = 0;
  15133. this.angle = 0;
  15134. this.angularSpeed = 0;
  15135. }
  15136. Particle.prototype.copyTo = function (other) {
  15137. other.position.copyFrom(this.position);
  15138. other.direction.copyFrom(this.direction);
  15139. other.color.copyFrom(this.color);
  15140. other.colorStep.copyFrom(this.colorStep);
  15141. other.lifeTime = this.lifeTime;
  15142. other.age = this.age;
  15143. other.size = this.size;
  15144. other.angle = this.angle;
  15145. other.angularSpeed = this.angularSpeed;
  15146. };
  15147. return Particle;
  15148. })();
  15149. BABYLON.Particle = Particle;
  15150. })(BABYLON || (BABYLON = {}));
  15151. //# sourceMappingURL=babylon.particle.js.mapvar BABYLON;
  15152. (function (BABYLON) {
  15153. var randomNumber = function (min, max) {
  15154. if (min === max) {
  15155. return (min);
  15156. }
  15157. var random = Math.random();
  15158. return ((random * (max - min)) + min);
  15159. };
  15160. var ParticleSystem = (function () {
  15161. function ParticleSystem(name, capacity, scene, customEffect) {
  15162. var _this = this;
  15163. this.name = name;
  15164. this.renderingGroupId = 0;
  15165. this.emitter = null;
  15166. this.emitRate = 10;
  15167. this.manualEmitCount = -1;
  15168. this.updateSpeed = 0.01;
  15169. this.targetStopDuration = 0;
  15170. this.disposeOnStop = false;
  15171. this.minEmitPower = 1;
  15172. this.maxEmitPower = 1;
  15173. this.minLifeTime = 1;
  15174. this.maxLifeTime = 1;
  15175. this.minSize = 1;
  15176. this.maxSize = 1;
  15177. this.minAngularSpeed = 0;
  15178. this.maxAngularSpeed = 0;
  15179. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  15180. this.forceDepthWrite = false;
  15181. this.gravity = BABYLON.Vector3.Zero();
  15182. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  15183. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  15184. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  15185. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  15186. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  15187. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  15188. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  15189. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  15190. this.particles = new Array();
  15191. this._vertexDeclaration = [3, 4, 4];
  15192. this._vertexStrideSize = 11 * 4; // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY)
  15193. this._stockParticles = new Array();
  15194. this._newPartsExcess = 0;
  15195. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  15196. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  15197. this._scaledDirection = BABYLON.Vector3.Zero();
  15198. this._scaledGravity = BABYLON.Vector3.Zero();
  15199. this._currentRenderId = -1;
  15200. this._started = false;
  15201. this._stopped = false;
  15202. this._actualFrame = 0;
  15203. this.id = name;
  15204. this._capacity = capacity;
  15205. this._scene = scene;
  15206. this._customEffect = customEffect;
  15207. scene.particleSystems.push(this);
  15208. // VBO
  15209. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  15210. var indices = [];
  15211. var index = 0;
  15212. for (var count = 0; count < capacity; count++) {
  15213. indices.push(index);
  15214. indices.push(index + 1);
  15215. indices.push(index + 2);
  15216. indices.push(index);
  15217. indices.push(index + 2);
  15218. indices.push(index + 3);
  15219. index += 4;
  15220. }
  15221. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  15222. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  15223. // Default behaviors
  15224. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate) {
  15225. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  15226. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  15227. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  15228. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  15229. };
  15230. this.startPositionFunction = function (worldMatrix, positionToUpdate) {
  15231. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  15232. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  15233. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  15234. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  15235. };
  15236. this.updateFunction = function (particles) {
  15237. for (var index = 0; index < particles.length; index++) {
  15238. var particle = particles[index];
  15239. particle.age += _this._scaledUpdateSpeed;
  15240. if (particle.age >= particle.lifeTime) {
  15241. _this.recycleParticle(particle);
  15242. index--;
  15243. continue;
  15244. }
  15245. else {
  15246. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  15247. particle.color.addInPlace(_this._scaledColorStep);
  15248. if (particle.color.a < 0)
  15249. particle.color.a = 0;
  15250. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  15251. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  15252. particle.position.addInPlace(_this._scaledDirection);
  15253. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  15254. particle.direction.addInPlace(_this._scaledGravity);
  15255. }
  15256. }
  15257. };
  15258. }
  15259. ParticleSystem.prototype.recycleParticle = function (particle) {
  15260. var lastParticle = this.particles.pop();
  15261. if (lastParticle !== particle) {
  15262. lastParticle.copyTo(particle);
  15263. this._stockParticles.push(lastParticle);
  15264. }
  15265. };
  15266. ParticleSystem.prototype.getCapacity = function () {
  15267. return this._capacity;
  15268. };
  15269. ParticleSystem.prototype.isAlive = function () {
  15270. return this._alive;
  15271. };
  15272. ParticleSystem.prototype.isStarted = function () {
  15273. return this._started;
  15274. };
  15275. ParticleSystem.prototype.start = function () {
  15276. this._started = true;
  15277. this._stopped = false;
  15278. this._actualFrame = 0;
  15279. };
  15280. ParticleSystem.prototype.stop = function () {
  15281. this._stopped = true;
  15282. };
  15283. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  15284. var offset = index * 11;
  15285. this._vertices[offset] = particle.position.x;
  15286. this._vertices[offset + 1] = particle.position.y;
  15287. this._vertices[offset + 2] = particle.position.z;
  15288. this._vertices[offset + 3] = particle.color.r;
  15289. this._vertices[offset + 4] = particle.color.g;
  15290. this._vertices[offset + 5] = particle.color.b;
  15291. this._vertices[offset + 6] = particle.color.a;
  15292. this._vertices[offset + 7] = particle.angle;
  15293. this._vertices[offset + 8] = particle.size;
  15294. this._vertices[offset + 9] = offsetX;
  15295. this._vertices[offset + 10] = offsetY;
  15296. };
  15297. ParticleSystem.prototype._update = function (newParticles) {
  15298. // Update current
  15299. this._alive = this.particles.length > 0;
  15300. this.updateFunction(this.particles);
  15301. // Add new ones
  15302. var worldMatrix;
  15303. if (this.emitter.position) {
  15304. worldMatrix = this.emitter.getWorldMatrix();
  15305. }
  15306. else {
  15307. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  15308. }
  15309. for (var index = 0; index < newParticles; index++) {
  15310. if (this.particles.length === this._capacity) {
  15311. break;
  15312. }
  15313. if (this._stockParticles.length !== 0) {
  15314. var particle = this._stockParticles.pop();
  15315. particle.age = 0;
  15316. }
  15317. else {
  15318. particle = new BABYLON.Particle();
  15319. }
  15320. this.particles.push(particle);
  15321. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  15322. this.startDirectionFunction(emitPower, worldMatrix, particle.direction);
  15323. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  15324. particle.size = randomNumber(this.minSize, this.maxSize);
  15325. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  15326. this.startPositionFunction(worldMatrix, particle.position);
  15327. var step = randomNumber(0, 1.0);
  15328. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  15329. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  15330. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  15331. }
  15332. };
  15333. ParticleSystem.prototype._getEffect = function () {
  15334. if (this._customEffect) {
  15335. return this._customEffect;
  15336. }
  15337. ;
  15338. var defines = [];
  15339. if (this._scene.clipPlane) {
  15340. defines.push("#define CLIPPLANE");
  15341. }
  15342. // Effect
  15343. var join = defines.join("\n");
  15344. if (this._cachedDefines !== join) {
  15345. this._cachedDefines = join;
  15346. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  15347. }
  15348. return this._effect;
  15349. };
  15350. ParticleSystem.prototype.animate = function () {
  15351. if (!this._started)
  15352. return;
  15353. var effect = this._getEffect();
  15354. // Check
  15355. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  15356. return;
  15357. if (this._currentRenderId === this._scene.getRenderId()) {
  15358. return;
  15359. }
  15360. this._currentRenderId = this._scene.getRenderId();
  15361. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  15362. // determine the number of particles we need to create
  15363. var emitCout;
  15364. if (this.manualEmitCount > -1) {
  15365. emitCout = this.manualEmitCount;
  15366. this.manualEmitCount = 0;
  15367. }
  15368. else {
  15369. emitCout = this.emitRate;
  15370. }
  15371. var newParticles = ((emitCout * this._scaledUpdateSpeed) >> 0);
  15372. this._newPartsExcess += emitCout * this._scaledUpdateSpeed - newParticles;
  15373. if (this._newPartsExcess > 1.0) {
  15374. newParticles += this._newPartsExcess >> 0;
  15375. this._newPartsExcess -= this._newPartsExcess >> 0;
  15376. }
  15377. this._alive = false;
  15378. if (!this._stopped) {
  15379. this._actualFrame += this._scaledUpdateSpeed;
  15380. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  15381. this.stop();
  15382. }
  15383. else {
  15384. newParticles = 0;
  15385. }
  15386. this._update(newParticles);
  15387. // Stopped?
  15388. if (this._stopped) {
  15389. if (!this._alive) {
  15390. this._started = false;
  15391. if (this.disposeOnStop) {
  15392. this._scene._toBeDisposed.push(this);
  15393. }
  15394. }
  15395. }
  15396. // Update VBO
  15397. var offset = 0;
  15398. for (var index = 0; index < this.particles.length; index++) {
  15399. var particle = this.particles[index];
  15400. this._appendParticleVertex(offset++, particle, 0, 0);
  15401. this._appendParticleVertex(offset++, particle, 1, 0);
  15402. this._appendParticleVertex(offset++, particle, 1, 1);
  15403. this._appendParticleVertex(offset++, particle, 0, 1);
  15404. }
  15405. var engine = this._scene.getEngine();
  15406. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  15407. };
  15408. ParticleSystem.prototype.render = function () {
  15409. var effect = this._getEffect();
  15410. // Check
  15411. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  15412. return 0;
  15413. var engine = this._scene.getEngine();
  15414. // Render
  15415. engine.enableEffect(effect);
  15416. engine.setState(false);
  15417. var viewMatrix = this._scene.getViewMatrix();
  15418. effect.setTexture("diffuseSampler", this.particleTexture);
  15419. effect.setMatrix("view", viewMatrix);
  15420. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  15421. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  15422. if (this._scene.clipPlane) {
  15423. var clipPlane = this._scene.clipPlane;
  15424. var invView = viewMatrix.clone();
  15425. invView.invert();
  15426. effect.setMatrix("invView", invView);
  15427. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  15428. }
  15429. // VBOs
  15430. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  15431. // Draw order
  15432. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  15433. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  15434. }
  15435. else {
  15436. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  15437. }
  15438. if (this.forceDepthWrite) {
  15439. engine.setDepthWrite(true);
  15440. }
  15441. engine.draw(true, 0, this.particles.length * 6);
  15442. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  15443. return this.particles.length;
  15444. };
  15445. ParticleSystem.prototype.dispose = function () {
  15446. if (this._vertexBuffer) {
  15447. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  15448. this._vertexBuffer = null;
  15449. }
  15450. if (this._indexBuffer) {
  15451. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  15452. this._indexBuffer = null;
  15453. }
  15454. if (this.particleTexture) {
  15455. this.particleTexture.dispose();
  15456. this.particleTexture = null;
  15457. }
  15458. // Remove from scene
  15459. var index = this._scene.particleSystems.indexOf(this);
  15460. this._scene.particleSystems.splice(index, 1);
  15461. // Callback
  15462. if (this.onDispose) {
  15463. this.onDispose();
  15464. }
  15465. };
  15466. // Clone
  15467. ParticleSystem.prototype.clone = function (name, newEmitter) {
  15468. var result = new ParticleSystem(name, this._capacity, this._scene);
  15469. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  15470. if (newEmitter === undefined) {
  15471. newEmitter = this.emitter;
  15472. }
  15473. result.emitter = newEmitter;
  15474. if (this.particleTexture) {
  15475. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  15476. }
  15477. result.start();
  15478. return result;
  15479. };
  15480. // Statics
  15481. ParticleSystem.BLENDMODE_ONEONE = 0;
  15482. ParticleSystem.BLENDMODE_STANDARD = 1;
  15483. return ParticleSystem;
  15484. })();
  15485. BABYLON.ParticleSystem = ParticleSystem;
  15486. })(BABYLON || (BABYLON = {}));
  15487. //# sourceMappingURL=babylon.particleSystem.js.mapvar BABYLON;
  15488. (function (BABYLON) {
  15489. var Animation = (function () {
  15490. function Animation(name, targetProperty, framePerSecond, dataType, loopMode) {
  15491. this.name = name;
  15492. this.targetProperty = targetProperty;
  15493. this.framePerSecond = framePerSecond;
  15494. this.dataType = dataType;
  15495. this.loopMode = loopMode;
  15496. this._offsetsCache = {};
  15497. this._highLimitsCache = {};
  15498. this._stopped = false;
  15499. this.targetPropertyPath = targetProperty.split(".");
  15500. this.dataType = dataType;
  15501. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  15502. }
  15503. Animation.CreateAndStartAnimation = function (name, mesh, tartgetProperty, framePerSecond, totalFrame, from, to, loopMode) {
  15504. var dataType = undefined;
  15505. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  15506. dataType = Animation.ANIMATIONTYPE_FLOAT;
  15507. }
  15508. else if (from instanceof BABYLON.Quaternion) {
  15509. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  15510. }
  15511. else if (from instanceof BABYLON.Vector3) {
  15512. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  15513. }
  15514. else if (from instanceof BABYLON.Vector2) {
  15515. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  15516. }
  15517. else if (from instanceof BABYLON.Color3) {
  15518. dataType = Animation.ANIMATIONTYPE_COLOR3;
  15519. }
  15520. if (dataType == undefined) {
  15521. return null;
  15522. }
  15523. var animation = new Animation(name, tartgetProperty, framePerSecond, dataType, loopMode);
  15524. var keys = [];
  15525. keys.push({ frame: 0, value: from });
  15526. keys.push({ frame: totalFrame, value: to });
  15527. animation.setKeys(keys);
  15528. mesh.animations.push(animation);
  15529. return mesh.getScene().beginAnimation(mesh, 0, totalFrame, (animation.loopMode === 1));
  15530. };
  15531. // Methods
  15532. Animation.prototype.isStopped = function () {
  15533. return this._stopped;
  15534. };
  15535. Animation.prototype.getKeys = function () {
  15536. return this._keys;
  15537. };
  15538. Animation.prototype.getEasingFunction = function () {
  15539. return this._easingFunction;
  15540. };
  15541. Animation.prototype.setEasingFunction = function (easingFunction) {
  15542. this._easingFunction = easingFunction;
  15543. };
  15544. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  15545. return startValue + (endValue - startValue) * gradient;
  15546. };
  15547. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  15548. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  15549. };
  15550. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  15551. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  15552. };
  15553. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  15554. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  15555. };
  15556. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  15557. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  15558. };
  15559. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  15560. var startScale = new BABYLON.Vector3(0, 0, 0);
  15561. var startRotation = new BABYLON.Quaternion();
  15562. var startTranslation = new BABYLON.Vector3(0, 0, 0);
  15563. startValue.decompose(startScale, startRotation, startTranslation);
  15564. var endScale = new BABYLON.Vector3(0, 0, 0);
  15565. var endRotation = new BABYLON.Quaternion();
  15566. var endTranslation = new BABYLON.Vector3(0, 0, 0);
  15567. endValue.decompose(endScale, endRotation, endTranslation);
  15568. var resultScale = this.vector3InterpolateFunction(startScale, endScale, gradient);
  15569. var resultRotation = this.quaternionInterpolateFunction(startRotation, endRotation, gradient);
  15570. var resultTranslation = this.vector3InterpolateFunction(startTranslation, endTranslation, gradient);
  15571. var result = BABYLON.Matrix.Compose(resultScale, resultRotation, resultTranslation);
  15572. return result;
  15573. };
  15574. Animation.prototype.clone = function () {
  15575. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  15576. clone.setKeys(this._keys);
  15577. return clone;
  15578. };
  15579. Animation.prototype.setKeys = function (values) {
  15580. this._keys = values.slice(0);
  15581. this._offsetsCache = {};
  15582. this._highLimitsCache = {};
  15583. };
  15584. Animation.prototype._getKeyValue = function (value) {
  15585. if (typeof value === "function") {
  15586. return value();
  15587. }
  15588. return value;
  15589. };
  15590. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  15591. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  15592. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  15593. }
  15594. this.currentFrame = currentFrame;
  15595. for (var key = 0; key < this._keys.length; key++) {
  15596. // for each frame, we need the key just before the frame superior
  15597. if (this._keys[key + 1].frame >= currentFrame) {
  15598. var startValue = this._getKeyValue(this._keys[key].value);
  15599. var endValue = this._getKeyValue(this._keys[key + 1].value);
  15600. // gradient : percent of currentFrame between the frame inf and the frame sup
  15601. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  15602. // check for easingFunction and correction of gradient
  15603. if (this._easingFunction != null) {
  15604. gradient = this._easingFunction.ease(gradient);
  15605. }
  15606. switch (this.dataType) {
  15607. case Animation.ANIMATIONTYPE_FLOAT:
  15608. switch (loopMode) {
  15609. case Animation.ANIMATIONLOOPMODE_CYCLE:
  15610. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  15611. return this.floatInterpolateFunction(startValue, endValue, gradient);
  15612. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  15613. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  15614. }
  15615. break;
  15616. case Animation.ANIMATIONTYPE_QUATERNION:
  15617. var quaternion = null;
  15618. switch (loopMode) {
  15619. case Animation.ANIMATIONLOOPMODE_CYCLE:
  15620. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  15621. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  15622. break;
  15623. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  15624. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  15625. break;
  15626. }
  15627. return quaternion;
  15628. case Animation.ANIMATIONTYPE_VECTOR3:
  15629. switch (loopMode) {
  15630. case Animation.ANIMATIONLOOPMODE_CYCLE:
  15631. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  15632. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  15633. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  15634. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  15635. }
  15636. case Animation.ANIMATIONTYPE_VECTOR2:
  15637. switch (loopMode) {
  15638. case Animation.ANIMATIONLOOPMODE_CYCLE:
  15639. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  15640. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  15641. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  15642. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  15643. }
  15644. case Animation.ANIMATIONTYPE_COLOR3:
  15645. switch (loopMode) {
  15646. case Animation.ANIMATIONLOOPMODE_CYCLE:
  15647. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  15648. return this.color3InterpolateFunction(startValue, endValue, gradient);
  15649. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  15650. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  15651. }
  15652. case Animation.ANIMATIONTYPE_MATRIX:
  15653. switch (loopMode) {
  15654. case Animation.ANIMATIONLOOPMODE_CYCLE:
  15655. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  15656. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  15657. return startValue;
  15658. }
  15659. default:
  15660. break;
  15661. }
  15662. break;
  15663. }
  15664. }
  15665. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  15666. };
  15667. Animation.prototype.animate = function (delay, from, to, loop, speedRatio) {
  15668. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  15669. this._stopped = true;
  15670. return false;
  15671. }
  15672. var returnValue = true;
  15673. // Adding a start key at frame 0 if missing
  15674. if (this._keys[0].frame !== 0) {
  15675. var newKey = { frame: 0, value: this._keys[0].value };
  15676. this._keys.splice(0, 0, newKey);
  15677. }
  15678. // Check limits
  15679. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  15680. from = this._keys[0].frame;
  15681. }
  15682. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  15683. to = this._keys[this._keys.length - 1].frame;
  15684. }
  15685. // Compute ratio
  15686. var range = to - from;
  15687. var offsetValue;
  15688. // ratio represents the frame delta between from and to
  15689. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  15690. var highLimitValue = 0;
  15691. if (ratio > range && !loop) {
  15692. returnValue = false;
  15693. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  15694. }
  15695. else {
  15696. // Get max value if required
  15697. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  15698. var keyOffset = to.toString() + from.toString();
  15699. if (!this._offsetsCache[keyOffset]) {
  15700. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  15701. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  15702. switch (this.dataType) {
  15703. case Animation.ANIMATIONTYPE_FLOAT:
  15704. this._offsetsCache[keyOffset] = toValue - fromValue;
  15705. break;
  15706. case Animation.ANIMATIONTYPE_QUATERNION:
  15707. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  15708. break;
  15709. case Animation.ANIMATIONTYPE_VECTOR3:
  15710. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  15711. case Animation.ANIMATIONTYPE_VECTOR2:
  15712. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  15713. case Animation.ANIMATIONTYPE_COLOR3:
  15714. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  15715. default:
  15716. break;
  15717. }
  15718. this._highLimitsCache[keyOffset] = toValue;
  15719. }
  15720. highLimitValue = this._highLimitsCache[keyOffset];
  15721. offsetValue = this._offsetsCache[keyOffset];
  15722. }
  15723. }
  15724. if (offsetValue === undefined) {
  15725. switch (this.dataType) {
  15726. case Animation.ANIMATIONTYPE_FLOAT:
  15727. offsetValue = 0;
  15728. break;
  15729. case Animation.ANIMATIONTYPE_QUATERNION:
  15730. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  15731. break;
  15732. case Animation.ANIMATIONTYPE_VECTOR3:
  15733. offsetValue = BABYLON.Vector3.Zero();
  15734. break;
  15735. case Animation.ANIMATIONTYPE_VECTOR2:
  15736. offsetValue = BABYLON.Vector2.Zero();
  15737. break;
  15738. case Animation.ANIMATIONTYPE_COLOR3:
  15739. offsetValue = BABYLON.Color3.Black();
  15740. }
  15741. }
  15742. // Compute value
  15743. var repeatCount = (ratio / range) >> 0;
  15744. var currentFrame = returnValue ? from + ratio % range : to;
  15745. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  15746. // Set value
  15747. if (this.targetPropertyPath.length > 1) {
  15748. var property = this._target[this.targetPropertyPath[0]];
  15749. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  15750. property = property[this.targetPropertyPath[index]];
  15751. }
  15752. property[this.targetPropertyPath[this.targetPropertyPath.length - 1]] = currentValue;
  15753. }
  15754. else {
  15755. this._target[this.targetPropertyPath[0]] = currentValue;
  15756. }
  15757. if (this._target.markAsDirty) {
  15758. this._target.markAsDirty(this.targetProperty);
  15759. }
  15760. if (!returnValue) {
  15761. this._stopped = true;
  15762. }
  15763. return returnValue;
  15764. };
  15765. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  15766. get: function () {
  15767. return Animation._ANIMATIONTYPE_FLOAT;
  15768. },
  15769. enumerable: true,
  15770. configurable: true
  15771. });
  15772. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  15773. get: function () {
  15774. return Animation._ANIMATIONTYPE_VECTOR3;
  15775. },
  15776. enumerable: true,
  15777. configurable: true
  15778. });
  15779. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  15780. get: function () {
  15781. return Animation._ANIMATIONTYPE_VECTOR2;
  15782. },
  15783. enumerable: true,
  15784. configurable: true
  15785. });
  15786. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  15787. get: function () {
  15788. return Animation._ANIMATIONTYPE_QUATERNION;
  15789. },
  15790. enumerable: true,
  15791. configurable: true
  15792. });
  15793. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  15794. get: function () {
  15795. return Animation._ANIMATIONTYPE_MATRIX;
  15796. },
  15797. enumerable: true,
  15798. configurable: true
  15799. });
  15800. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  15801. get: function () {
  15802. return Animation._ANIMATIONTYPE_COLOR3;
  15803. },
  15804. enumerable: true,
  15805. configurable: true
  15806. });
  15807. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  15808. get: function () {
  15809. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  15810. },
  15811. enumerable: true,
  15812. configurable: true
  15813. });
  15814. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  15815. get: function () {
  15816. return Animation._ANIMATIONLOOPMODE_CYCLE;
  15817. },
  15818. enumerable: true,
  15819. configurable: true
  15820. });
  15821. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  15822. get: function () {
  15823. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  15824. },
  15825. enumerable: true,
  15826. configurable: true
  15827. });
  15828. // Statics
  15829. Animation._ANIMATIONTYPE_FLOAT = 0;
  15830. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  15831. Animation._ANIMATIONTYPE_QUATERNION = 2;
  15832. Animation._ANIMATIONTYPE_MATRIX = 3;
  15833. Animation._ANIMATIONTYPE_COLOR3 = 4;
  15834. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  15835. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  15836. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  15837. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  15838. return Animation;
  15839. })();
  15840. BABYLON.Animation = Animation;
  15841. })(BABYLON || (BABYLON = {}));
  15842. //# sourceMappingURL=babylon.animation.js.mapvar BABYLON;
  15843. (function (BABYLON) {
  15844. var Animatable = (function () {
  15845. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  15846. if (fromFrame === void 0) { fromFrame = 0; }
  15847. if (toFrame === void 0) { toFrame = 100; }
  15848. if (loopAnimation === void 0) { loopAnimation = false; }
  15849. if (speedRatio === void 0) { speedRatio = 1.0; }
  15850. this.target = target;
  15851. this.fromFrame = fromFrame;
  15852. this.toFrame = toFrame;
  15853. this.loopAnimation = loopAnimation;
  15854. this.speedRatio = speedRatio;
  15855. this.onAnimationEnd = onAnimationEnd;
  15856. this._animations = new Array();
  15857. this._paused = false;
  15858. this.animationStarted = false;
  15859. if (animations) {
  15860. this.appendAnimations(target, animations);
  15861. }
  15862. this._scene = scene;
  15863. scene._activeAnimatables.push(this);
  15864. }
  15865. // Methods
  15866. Animatable.prototype.appendAnimations = function (target, animations) {
  15867. for (var index = 0; index < animations.length; index++) {
  15868. var animation = animations[index];
  15869. animation._target = target;
  15870. this._animations.push(animation);
  15871. }
  15872. };
  15873. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  15874. var animations = this._animations;
  15875. for (var index = 0; index < animations.length; index++) {
  15876. if (animations[index].targetProperty === property) {
  15877. return animations[index];
  15878. }
  15879. }
  15880. return null;
  15881. };
  15882. Animatable.prototype.pause = function () {
  15883. if (this._paused) {
  15884. return;
  15885. }
  15886. this._paused = true;
  15887. };
  15888. Animatable.prototype.restart = function () {
  15889. this._paused = false;
  15890. };
  15891. Animatable.prototype.stop = function () {
  15892. var index = this._scene._activeAnimatables.indexOf(this);
  15893. if (index > -1) {
  15894. this._scene._activeAnimatables.splice(index, 1);
  15895. }
  15896. if (this.onAnimationEnd) {
  15897. this.onAnimationEnd();
  15898. }
  15899. };
  15900. Animatable.prototype._animate = function (delay) {
  15901. if (this._paused) {
  15902. if (!this._pausedDelay) {
  15903. this._pausedDelay = delay;
  15904. }
  15905. return true;
  15906. }
  15907. if (!this._localDelayOffset) {
  15908. this._localDelayOffset = delay;
  15909. }
  15910. else if (this._pausedDelay) {
  15911. this._localDelayOffset += delay - this._pausedDelay;
  15912. this._pausedDelay = null;
  15913. }
  15914. // Animating
  15915. var running = false;
  15916. var animations = this._animations;
  15917. for (var index = 0; index < animations.length; index++) {
  15918. var animation = animations[index];
  15919. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  15920. running = running || isRunning;
  15921. }
  15922. if (!running && this.onAnimationEnd) {
  15923. this.onAnimationEnd();
  15924. }
  15925. return running;
  15926. };
  15927. return Animatable;
  15928. })();
  15929. BABYLON.Animatable = Animatable;
  15930. })(BABYLON || (BABYLON = {}));
  15931. //# sourceMappingURL=babylon.animatable.js.map
  15932. var BABYLON;
  15933. (function (BABYLON) {
  15934. var EasingFunction = (function () {
  15935. function EasingFunction() {
  15936. // Properties
  15937. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  15938. }
  15939. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  15940. get: function () {
  15941. return EasingFunction._EASINGMODE_EASEIN;
  15942. },
  15943. enumerable: true,
  15944. configurable: true
  15945. });
  15946. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  15947. get: function () {
  15948. return EasingFunction._EASINGMODE_EASEOUT;
  15949. },
  15950. enumerable: true,
  15951. configurable: true
  15952. });
  15953. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  15954. get: function () {
  15955. return EasingFunction._EASINGMODE_EASEINOUT;
  15956. },
  15957. enumerable: true,
  15958. configurable: true
  15959. });
  15960. EasingFunction.prototype.setEasingMode = function (easingMode) {
  15961. var n = Math.min(Math.max(easingMode, 0), 2);
  15962. this._easingMode = n;
  15963. };
  15964. EasingFunction.prototype.getEasingMode = function () {
  15965. return this._easingMode;
  15966. };
  15967. EasingFunction.prototype.easeInCore = function (gradient) {
  15968. throw new Error('You must implement this method');
  15969. };
  15970. EasingFunction.prototype.ease = function (gradient) {
  15971. switch (this._easingMode) {
  15972. case EasingFunction.EASINGMODE_EASEIN:
  15973. return this.easeInCore(gradient);
  15974. case EasingFunction.EASINGMODE_EASEOUT:
  15975. return (1 - this.easeInCore(1 - gradient));
  15976. }
  15977. if (gradient >= 0.5) {
  15978. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  15979. }
  15980. return (this.easeInCore(gradient * 2) * 0.5);
  15981. };
  15982. //Statics
  15983. EasingFunction._EASINGMODE_EASEIN = 0;
  15984. EasingFunction._EASINGMODE_EASEOUT = 1;
  15985. EasingFunction._EASINGMODE_EASEINOUT = 2;
  15986. return EasingFunction;
  15987. })();
  15988. BABYLON.EasingFunction = EasingFunction;
  15989. var CircleEase = (function (_super) {
  15990. __extends(CircleEase, _super);
  15991. function CircleEase() {
  15992. _super.apply(this, arguments);
  15993. }
  15994. CircleEase.prototype.easeInCore = function (gradient) {
  15995. gradient = Math.max(0, Math.min(1, gradient));
  15996. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  15997. };
  15998. return CircleEase;
  15999. })(EasingFunction);
  16000. BABYLON.CircleEase = CircleEase;
  16001. var BackEase = (function (_super) {
  16002. __extends(BackEase, _super);
  16003. function BackEase(amplitude) {
  16004. if (amplitude === void 0) { amplitude = 1; }
  16005. _super.call(this);
  16006. this.amplitude = amplitude;
  16007. }
  16008. BackEase.prototype.easeInCore = function (gradient) {
  16009. var num = Math.max(0, this.amplitude);
  16010. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  16011. };
  16012. return BackEase;
  16013. })(EasingFunction);
  16014. BABYLON.BackEase = BackEase;
  16015. var BounceEase = (function (_super) {
  16016. __extends(BounceEase, _super);
  16017. function BounceEase(bounces, bounciness) {
  16018. if (bounces === void 0) { bounces = 3; }
  16019. if (bounciness === void 0) { bounciness = 2; }
  16020. _super.call(this);
  16021. this.bounces = bounces;
  16022. this.bounciness = bounciness;
  16023. }
  16024. BounceEase.prototype.easeInCore = function (gradient) {
  16025. var y = Math.max(0.0, this.bounces);
  16026. var bounciness = this.bounciness;
  16027. if (bounciness <= 1.0) {
  16028. bounciness = 1.001;
  16029. }
  16030. var num9 = Math.pow(bounciness, y);
  16031. var num5 = 1.0 - bounciness;
  16032. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  16033. var num15 = gradient * num4;
  16034. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  16035. var num3 = Math.floor(num65);
  16036. var num13 = num3 + 1.0;
  16037. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  16038. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  16039. var num7 = (num8 + num12) * 0.5;
  16040. var num6 = gradient - num7;
  16041. var num2 = num7 - num8;
  16042. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  16043. };
  16044. return BounceEase;
  16045. })(EasingFunction);
  16046. BABYLON.BounceEase = BounceEase;
  16047. var CubicEase = (function (_super) {
  16048. __extends(CubicEase, _super);
  16049. function CubicEase() {
  16050. _super.apply(this, arguments);
  16051. }
  16052. CubicEase.prototype.easeInCore = function (gradient) {
  16053. return (gradient * gradient * gradient);
  16054. };
  16055. return CubicEase;
  16056. })(EasingFunction);
  16057. BABYLON.CubicEase = CubicEase;
  16058. var ElasticEase = (function (_super) {
  16059. __extends(ElasticEase, _super);
  16060. function ElasticEase(oscillations, springiness) {
  16061. if (oscillations === void 0) { oscillations = 3; }
  16062. if (springiness === void 0) { springiness = 3; }
  16063. _super.call(this);
  16064. this.oscillations = oscillations;
  16065. this.springiness = springiness;
  16066. }
  16067. ElasticEase.prototype.easeInCore = function (gradient) {
  16068. var num2;
  16069. var num3 = Math.max(0.0, this.oscillations);
  16070. var num = Math.max(0.0, this.springiness);
  16071. if (num == 0) {
  16072. num2 = gradient;
  16073. }
  16074. else {
  16075. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  16076. }
  16077. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  16078. };
  16079. return ElasticEase;
  16080. })(EasingFunction);
  16081. BABYLON.ElasticEase = ElasticEase;
  16082. var ExponentialEase = (function (_super) {
  16083. __extends(ExponentialEase, _super);
  16084. function ExponentialEase(exponent) {
  16085. if (exponent === void 0) { exponent = 2; }
  16086. _super.call(this);
  16087. this.exponent = exponent;
  16088. }
  16089. ExponentialEase.prototype.easeInCore = function (gradient) {
  16090. if (this.exponent <= 0) {
  16091. return gradient;
  16092. }
  16093. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  16094. };
  16095. return ExponentialEase;
  16096. })(EasingFunction);
  16097. BABYLON.ExponentialEase = ExponentialEase;
  16098. var PowerEase = (function (_super) {
  16099. __extends(PowerEase, _super);
  16100. function PowerEase(power) {
  16101. if (power === void 0) { power = 2; }
  16102. _super.call(this);
  16103. this.power = power;
  16104. }
  16105. PowerEase.prototype.easeInCore = function (gradient) {
  16106. var y = Math.max(0.0, this.power);
  16107. return Math.pow(gradient, y);
  16108. };
  16109. return PowerEase;
  16110. })(EasingFunction);
  16111. BABYLON.PowerEase = PowerEase;
  16112. var QuadraticEase = (function (_super) {
  16113. __extends(QuadraticEase, _super);
  16114. function QuadraticEase() {
  16115. _super.apply(this, arguments);
  16116. }
  16117. QuadraticEase.prototype.easeInCore = function (gradient) {
  16118. return (gradient * gradient);
  16119. };
  16120. return QuadraticEase;
  16121. })(EasingFunction);
  16122. BABYLON.QuadraticEase = QuadraticEase;
  16123. var QuarticEase = (function (_super) {
  16124. __extends(QuarticEase, _super);
  16125. function QuarticEase() {
  16126. _super.apply(this, arguments);
  16127. }
  16128. QuarticEase.prototype.easeInCore = function (gradient) {
  16129. return (gradient * gradient * gradient * gradient);
  16130. };
  16131. return QuarticEase;
  16132. })(EasingFunction);
  16133. BABYLON.QuarticEase = QuarticEase;
  16134. var QuinticEase = (function (_super) {
  16135. __extends(QuinticEase, _super);
  16136. function QuinticEase() {
  16137. _super.apply(this, arguments);
  16138. }
  16139. QuinticEase.prototype.easeInCore = function (gradient) {
  16140. return (gradient * gradient * gradient * gradient * gradient);
  16141. };
  16142. return QuinticEase;
  16143. })(EasingFunction);
  16144. BABYLON.QuinticEase = QuinticEase;
  16145. var SineEase = (function (_super) {
  16146. __extends(SineEase, _super);
  16147. function SineEase() {
  16148. _super.apply(this, arguments);
  16149. }
  16150. SineEase.prototype.easeInCore = function (gradient) {
  16151. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  16152. };
  16153. return SineEase;
  16154. })(EasingFunction);
  16155. BABYLON.SineEase = SineEase;
  16156. var BezierCurveEase = (function (_super) {
  16157. __extends(BezierCurveEase, _super);
  16158. function BezierCurveEase(x1, y1, x2, y2) {
  16159. if (x1 === void 0) { x1 = 0; }
  16160. if (y1 === void 0) { y1 = 0; }
  16161. if (x2 === void 0) { x2 = 1; }
  16162. if (y2 === void 0) { y2 = 1; }
  16163. _super.call(this);
  16164. this.x1 = x1;
  16165. this.y1 = y1;
  16166. this.x2 = x2;
  16167. this.y2 = y2;
  16168. }
  16169. BezierCurveEase.prototype.easeInCore = function (gradient) {
  16170. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  16171. };
  16172. return BezierCurveEase;
  16173. })(EasingFunction);
  16174. BABYLON.BezierCurveEase = BezierCurveEase;
  16175. })(BABYLON || (BABYLON = {}));
  16176. //# sourceMappingURL=babylon.easing.js.mapvar BABYLON;
  16177. (function (BABYLON) {
  16178. var Octree = (function () {
  16179. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  16180. if (maxDepth === void 0) { maxDepth = 2; }
  16181. this.maxDepth = maxDepth;
  16182. this.dynamicContent = new Array();
  16183. this._maxBlockCapacity = maxBlockCapacity || 64;
  16184. this._selectionContent = new BABYLON.SmartArray(1024);
  16185. this._creationFunc = creationFunc;
  16186. }
  16187. // Methods
  16188. Octree.prototype.update = function (worldMin, worldMax, entries) {
  16189. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  16190. };
  16191. Octree.prototype.addMesh = function (entry) {
  16192. for (var index = 0; index < this.blocks.length; index++) {
  16193. var block = this.blocks[index];
  16194. block.addEntry(entry);
  16195. }
  16196. };
  16197. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  16198. this._selectionContent.reset();
  16199. for (var index = 0; index < this.blocks.length; index++) {
  16200. var block = this.blocks[index];
  16201. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  16202. }
  16203. if (allowDuplicate) {
  16204. this._selectionContent.concat(this.dynamicContent);
  16205. }
  16206. else {
  16207. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  16208. }
  16209. return this._selectionContent;
  16210. };
  16211. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  16212. this._selectionContent.reset();
  16213. for (var index = 0; index < this.blocks.length; index++) {
  16214. var block = this.blocks[index];
  16215. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  16216. }
  16217. if (allowDuplicate) {
  16218. this._selectionContent.concat(this.dynamicContent);
  16219. }
  16220. else {
  16221. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  16222. }
  16223. return this._selectionContent;
  16224. };
  16225. Octree.prototype.intersectsRay = function (ray) {
  16226. this._selectionContent.reset();
  16227. for (var index = 0; index < this.blocks.length; index++) {
  16228. var block = this.blocks[index];
  16229. block.intersectsRay(ray, this._selectionContent);
  16230. }
  16231. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  16232. return this._selectionContent;
  16233. };
  16234. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  16235. target.blocks = new Array();
  16236. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  16237. for (var x = 0; x < 2; x++) {
  16238. for (var y = 0; y < 2; y++) {
  16239. for (var z = 0; z < 2; z++) {
  16240. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  16241. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  16242. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  16243. block.addEntries(entries);
  16244. target.blocks.push(block);
  16245. }
  16246. }
  16247. }
  16248. };
  16249. Octree.CreationFuncForMeshes = function (entry, block) {
  16250. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  16251. block.entries.push(entry);
  16252. }
  16253. };
  16254. Octree.CreationFuncForSubMeshes = function (entry, block) {
  16255. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  16256. block.entries.push(entry);
  16257. }
  16258. };
  16259. return Octree;
  16260. })();
  16261. BABYLON.Octree = Octree;
  16262. })(BABYLON || (BABYLON = {}));
  16263. //# sourceMappingURL=babylon.octree.js.mapvar BABYLON;
  16264. (function (BABYLON) {
  16265. var OctreeBlock = (function () {
  16266. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  16267. this.entries = new Array();
  16268. this._boundingVectors = new Array();
  16269. this._capacity = capacity;
  16270. this._depth = depth;
  16271. this._maxDepth = maxDepth;
  16272. this._creationFunc = creationFunc;
  16273. this._minPoint = minPoint;
  16274. this._maxPoint = maxPoint;
  16275. this._boundingVectors.push(minPoint.clone());
  16276. this._boundingVectors.push(maxPoint.clone());
  16277. this._boundingVectors.push(minPoint.clone());
  16278. this._boundingVectors[2].x = maxPoint.x;
  16279. this._boundingVectors.push(minPoint.clone());
  16280. this._boundingVectors[3].y = maxPoint.y;
  16281. this._boundingVectors.push(minPoint.clone());
  16282. this._boundingVectors[4].z = maxPoint.z;
  16283. this._boundingVectors.push(maxPoint.clone());
  16284. this._boundingVectors[5].z = minPoint.z;
  16285. this._boundingVectors.push(maxPoint.clone());
  16286. this._boundingVectors[6].x = minPoint.x;
  16287. this._boundingVectors.push(maxPoint.clone());
  16288. this._boundingVectors[7].y = minPoint.y;
  16289. }
  16290. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  16291. // Property
  16292. get: function () {
  16293. return this._capacity;
  16294. },
  16295. enumerable: true,
  16296. configurable: true
  16297. });
  16298. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  16299. get: function () {
  16300. return this._minPoint;
  16301. },
  16302. enumerable: true,
  16303. configurable: true
  16304. });
  16305. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  16306. get: function () {
  16307. return this._maxPoint;
  16308. },
  16309. enumerable: true,
  16310. configurable: true
  16311. });
  16312. // Methods
  16313. OctreeBlock.prototype.addEntry = function (entry) {
  16314. if (this.blocks) {
  16315. for (var index = 0; index < this.blocks.length; index++) {
  16316. var block = this.blocks[index];
  16317. block.addEntry(entry);
  16318. }
  16319. return;
  16320. }
  16321. this._creationFunc(entry, this);
  16322. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  16323. this.createInnerBlocks();
  16324. }
  16325. };
  16326. OctreeBlock.prototype.addEntries = function (entries) {
  16327. for (var index = 0; index < entries.length; index++) {
  16328. var mesh = entries[index];
  16329. this.addEntry(mesh);
  16330. }
  16331. };
  16332. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  16333. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  16334. if (this.blocks) {
  16335. for (var index = 0; index < this.blocks.length; index++) {
  16336. var block = this.blocks[index];
  16337. block.select(frustumPlanes, selection, allowDuplicate);
  16338. }
  16339. return;
  16340. }
  16341. if (allowDuplicate) {
  16342. selection.concat(this.entries);
  16343. }
  16344. else {
  16345. selection.concatWithNoDuplicate(this.entries);
  16346. }
  16347. }
  16348. };
  16349. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  16350. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  16351. if (this.blocks) {
  16352. for (var index = 0; index < this.blocks.length; index++) {
  16353. var block = this.blocks[index];
  16354. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  16355. }
  16356. return;
  16357. }
  16358. if (allowDuplicate) {
  16359. selection.concat(this.entries);
  16360. }
  16361. else {
  16362. selection.concatWithNoDuplicate(this.entries);
  16363. }
  16364. }
  16365. };
  16366. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  16367. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  16368. if (this.blocks) {
  16369. for (var index = 0; index < this.blocks.length; index++) {
  16370. var block = this.blocks[index];
  16371. block.intersectsRay(ray, selection);
  16372. }
  16373. return;
  16374. }
  16375. selection.concatWithNoDuplicate(this.entries);
  16376. }
  16377. };
  16378. OctreeBlock.prototype.createInnerBlocks = function () {
  16379. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  16380. };
  16381. return OctreeBlock;
  16382. })();
  16383. BABYLON.OctreeBlock = OctreeBlock;
  16384. })(BABYLON || (BABYLON = {}));
  16385. //# sourceMappingURL=babylon.octreeBlock.js.mapvar BABYLON;
  16386. (function (BABYLON) {
  16387. var Bone = (function () {
  16388. function Bone(name, skeleton, parentBone, matrix) {
  16389. this.name = name;
  16390. this.children = new Array();
  16391. this.animations = new Array();
  16392. this._worldTransform = new BABYLON.Matrix();
  16393. this._absoluteTransform = new BABYLON.Matrix();
  16394. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  16395. this._skeleton = skeleton;
  16396. this._matrix = matrix;
  16397. this._baseMatrix = matrix;
  16398. skeleton.bones.push(this);
  16399. if (parentBone) {
  16400. this._parent = parentBone;
  16401. parentBone.children.push(this);
  16402. }
  16403. else {
  16404. this._parent = null;
  16405. }
  16406. this._updateDifferenceMatrix();
  16407. }
  16408. // Members
  16409. Bone.prototype.getParent = function () {
  16410. return this._parent;
  16411. };
  16412. Bone.prototype.getLocalMatrix = function () {
  16413. return this._matrix;
  16414. };
  16415. Bone.prototype.getBaseMatrix = function () {
  16416. return this._baseMatrix;
  16417. };
  16418. Bone.prototype.getWorldMatrix = function () {
  16419. return this._worldTransform;
  16420. };
  16421. Bone.prototype.getInvertedAbsoluteTransform = function () {
  16422. return this._invertedAbsoluteTransform;
  16423. };
  16424. Bone.prototype.getAbsoluteMatrix = function () {
  16425. var matrix = this._matrix.clone();
  16426. var parent = this._parent;
  16427. while (parent) {
  16428. matrix = matrix.multiply(parent.getLocalMatrix());
  16429. parent = parent.getParent();
  16430. }
  16431. return matrix;
  16432. };
  16433. // Methods
  16434. Bone.prototype.updateMatrix = function (matrix) {
  16435. this._matrix = matrix;
  16436. this._skeleton._markAsDirty();
  16437. this._updateDifferenceMatrix();
  16438. };
  16439. Bone.prototype._updateDifferenceMatrix = function () {
  16440. if (this._parent) {
  16441. this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  16442. }
  16443. else {
  16444. this._absoluteTransform.copyFrom(this._matrix);
  16445. }
  16446. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  16447. for (var index = 0; index < this.children.length; index++) {
  16448. this.children[index]._updateDifferenceMatrix();
  16449. }
  16450. };
  16451. Bone.prototype.markAsDirty = function () {
  16452. this._skeleton._markAsDirty();
  16453. };
  16454. return Bone;
  16455. })();
  16456. BABYLON.Bone = Bone;
  16457. })(BABYLON || (BABYLON = {}));
  16458. //# sourceMappingURL=babylon.bone.js.mapvar BABYLON;
  16459. (function (BABYLON) {
  16460. var Skeleton = (function () {
  16461. function Skeleton(name, id, scene) {
  16462. this.name = name;
  16463. this.id = id;
  16464. this.bones = new Array();
  16465. this._isDirty = true;
  16466. this._identity = BABYLON.Matrix.Identity();
  16467. this.bones = [];
  16468. this._scene = scene;
  16469. scene.skeletons.push(this);
  16470. }
  16471. // Members
  16472. Skeleton.prototype.getTransformMatrices = function () {
  16473. return this._transformMatrices;
  16474. };
  16475. // Methods
  16476. Skeleton.prototype._markAsDirty = function () {
  16477. this._isDirty = true;
  16478. };
  16479. Skeleton.prototype.prepare = function () {
  16480. if (!this._isDirty) {
  16481. return;
  16482. }
  16483. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  16484. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  16485. }
  16486. for (var index = 0; index < this.bones.length; index++) {
  16487. var bone = this.bones[index];
  16488. var parentBone = bone.getParent();
  16489. if (parentBone) {
  16490. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  16491. }
  16492. else {
  16493. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  16494. }
  16495. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), this._transformMatrices, index * 16);
  16496. }
  16497. this._identity.copyToArray(this._transformMatrices, this.bones.length * 16);
  16498. this._isDirty = false;
  16499. this._scene._activeBones += this.bones.length;
  16500. };
  16501. Skeleton.prototype.getAnimatables = function () {
  16502. if (!this._animatables || this._animatables.length !== this.bones.length) {
  16503. this._animatables = [];
  16504. for (var index = 0; index < this.bones.length; index++) {
  16505. this._animatables.push(this.bones[index]);
  16506. }
  16507. }
  16508. return this._animatables;
  16509. };
  16510. Skeleton.prototype.clone = function (name, id) {
  16511. var result = new Skeleton(name, id || name, this._scene);
  16512. for (var index = 0; index < this.bones.length; index++) {
  16513. var source = this.bones[index];
  16514. var parentBone = null;
  16515. if (source.getParent()) {
  16516. var parentIndex = this.bones.indexOf(source.getParent());
  16517. parentBone = result.bones[parentIndex];
  16518. }
  16519. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix());
  16520. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  16521. }
  16522. return result;
  16523. };
  16524. return Skeleton;
  16525. })();
  16526. BABYLON.Skeleton = Skeleton;
  16527. })(BABYLON || (BABYLON = {}));
  16528. //# sourceMappingURL=babylon.skeleton.js.mapvar BABYLON;
  16529. (function (BABYLON) {
  16530. var PostProcess = (function () {
  16531. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable, defines) {
  16532. this.name = name;
  16533. this.width = -1;
  16534. this.height = -1;
  16535. this._reusable = false;
  16536. this._textures = new BABYLON.SmartArray(2);
  16537. this._currentRenderTextureInd = 0;
  16538. if (camera != null) {
  16539. this._camera = camera;
  16540. this._scene = camera.getScene();
  16541. camera.attachPostProcess(this);
  16542. this._engine = this._scene.getEngine();
  16543. }
  16544. else {
  16545. this._engine = engine;
  16546. }
  16547. this._renderRatio = ratio;
  16548. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  16549. this._reusable = reusable || false;
  16550. samplers = samplers || [];
  16551. samplers.push("textureSampler");
  16552. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: fragmentUrl }, ["position"], parameters || [], samplers, defines !== undefined ? defines : "");
  16553. }
  16554. PostProcess.prototype.isReusable = function () {
  16555. return this._reusable;
  16556. };
  16557. PostProcess.prototype.activate = function (camera, sourceTexture) {
  16558. camera = camera || this._camera;
  16559. var scene = camera.getScene();
  16560. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  16561. var desiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  16562. var desiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  16563. desiredWidth = BABYLON.Tools.GetExponantOfTwo(desiredWidth, maxSize);
  16564. desiredHeight = BABYLON.Tools.GetExponantOfTwo(desiredHeight, maxSize);
  16565. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  16566. if (this._textures.length > 0) {
  16567. for (var i = 0; i < this._textures.length; i++) {
  16568. this._engine._releaseTexture(this._textures.data[i]);
  16569. }
  16570. this._textures.reset();
  16571. }
  16572. this.width = desiredWidth;
  16573. this.height = desiredHeight;
  16574. 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 }));
  16575. if (this._reusable) {
  16576. 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 }));
  16577. }
  16578. if (this.onSizeChanged) {
  16579. this.onSizeChanged();
  16580. }
  16581. }
  16582. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  16583. if (this.onActivate) {
  16584. this.onActivate(camera);
  16585. }
  16586. // Clear
  16587. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  16588. if (this._reusable) {
  16589. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  16590. }
  16591. };
  16592. PostProcess.prototype.apply = function () {
  16593. // Check
  16594. if (!this._effect.isReady())
  16595. return null;
  16596. // States
  16597. this._engine.enableEffect(this._effect);
  16598. this._engine.setState(false);
  16599. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  16600. this._engine.setDepthBuffer(false);
  16601. this._engine.setDepthWrite(false);
  16602. // Texture
  16603. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  16604. // Parameters
  16605. if (this.onApply) {
  16606. this.onApply(this._effect);
  16607. }
  16608. return this._effect;
  16609. };
  16610. PostProcess.prototype.dispose = function (camera) {
  16611. camera = camera || this._camera;
  16612. if (this._textures.length > 0) {
  16613. for (var i = 0; i < this._textures.length; i++) {
  16614. this._engine._releaseTexture(this._textures.data[i]);
  16615. }
  16616. this._textures.reset();
  16617. }
  16618. camera.detachPostProcess(this);
  16619. var index = camera._postProcesses.indexOf(this);
  16620. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  16621. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1; // invalidate frameBuffer to hint the postprocess to create a depth buffer
  16622. }
  16623. };
  16624. return PostProcess;
  16625. })();
  16626. BABYLON.PostProcess = PostProcess;
  16627. })(BABYLON || (BABYLON = {}));
  16628. //# sourceMappingURL=babylon.postProcess.js.mapvar BABYLON;
  16629. (function (BABYLON) {
  16630. var PostProcessManager = (function () {
  16631. function PostProcessManager(scene) {
  16632. this._vertexDeclaration = [2];
  16633. this._vertexStrideSize = 2 * 4;
  16634. this._scene = scene;
  16635. // VBO
  16636. var vertices = [];
  16637. vertices.push(1, 1);
  16638. vertices.push(-1, 1);
  16639. vertices.push(-1, -1);
  16640. vertices.push(1, -1);
  16641. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  16642. // Indices
  16643. var indices = [];
  16644. indices.push(0);
  16645. indices.push(1);
  16646. indices.push(2);
  16647. indices.push(0);
  16648. indices.push(2);
  16649. indices.push(3);
  16650. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  16651. }
  16652. // Methods
  16653. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  16654. var postProcesses = this._scene.activeCamera._postProcesses;
  16655. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  16656. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  16657. return false;
  16658. }
  16659. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  16660. return true;
  16661. };
  16662. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture) {
  16663. var postProcesses = this._scene.activeCamera._postProcesses;
  16664. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  16665. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  16666. return;
  16667. }
  16668. var engine = this._scene.getEngine();
  16669. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  16670. if (index < postProcessesTakenIndices.length - 1) {
  16671. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera);
  16672. }
  16673. else {
  16674. if (targetTexture) {
  16675. engine.bindFramebuffer(targetTexture);
  16676. }
  16677. else {
  16678. engine.restoreDefaultFramebuffer();
  16679. }
  16680. }
  16681. if (doNotPresent) {
  16682. break;
  16683. }
  16684. var pp = postProcesses[postProcessesTakenIndices[index]];
  16685. var effect = pp.apply();
  16686. if (effect) {
  16687. if (pp.onBeforeRender) {
  16688. pp.onBeforeRender(effect);
  16689. }
  16690. // VBOs
  16691. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  16692. // Draw order
  16693. engine.draw(true, 0, 6);
  16694. }
  16695. }
  16696. // Restore depth buffer
  16697. engine.setDepthBuffer(true);
  16698. engine.setDepthWrite(true);
  16699. };
  16700. PostProcessManager.prototype.dispose = function () {
  16701. if (this._vertexBuffer) {
  16702. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  16703. this._vertexBuffer = null;
  16704. }
  16705. if (this._indexBuffer) {
  16706. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  16707. this._indexBuffer = null;
  16708. }
  16709. };
  16710. return PostProcessManager;
  16711. })();
  16712. BABYLON.PostProcessManager = PostProcessManager;
  16713. })(BABYLON || (BABYLON = {}));
  16714. //# sourceMappingURL=babylon.postProcessManager.js.map
  16715. var BABYLON;
  16716. (function (BABYLON) {
  16717. var PassPostProcess = (function (_super) {
  16718. __extends(PassPostProcess, _super);
  16719. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  16720. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  16721. }
  16722. return PassPostProcess;
  16723. })(BABYLON.PostProcess);
  16724. BABYLON.PassPostProcess = PassPostProcess;
  16725. })(BABYLON || (BABYLON = {}));
  16726. //# sourceMappingURL=babylon.passPostProcess.js.map
  16727. var BABYLON;
  16728. (function (BABYLON) {
  16729. var BlurPostProcess = (function (_super) {
  16730. __extends(BlurPostProcess, _super);
  16731. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  16732. var _this = this;
  16733. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  16734. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  16735. this.direction = direction;
  16736. this.blurWidth = blurWidth;
  16737. this.onApply = function (effect) {
  16738. effect.setFloat2("screenSize", _this.width, _this.height);
  16739. effect.setVector2("direction", _this.direction);
  16740. effect.setFloat("blurWidth", _this.blurWidth);
  16741. };
  16742. }
  16743. return BlurPostProcess;
  16744. })(BABYLON.PostProcess);
  16745. BABYLON.BlurPostProcess = BlurPostProcess;
  16746. })(BABYLON || (BABYLON = {}));
  16747. //# sourceMappingURL=babylon.blurPostProcess.js.map
  16748. var BABYLON;
  16749. (function (BABYLON) {
  16750. var FilterPostProcess = (function (_super) {
  16751. __extends(FilterPostProcess, _super);
  16752. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  16753. var _this = this;
  16754. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  16755. this.kernelMatrix = kernelMatrix;
  16756. this.onApply = function (effect) {
  16757. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  16758. };
  16759. }
  16760. return FilterPostProcess;
  16761. })(BABYLON.PostProcess);
  16762. BABYLON.FilterPostProcess = FilterPostProcess;
  16763. })(BABYLON || (BABYLON = {}));
  16764. //# sourceMappingURL=babylon.filterPostProcess.js.map
  16765. var BABYLON;
  16766. (function (BABYLON) {
  16767. var RefractionPostProcess = (function (_super) {
  16768. __extends(RefractionPostProcess, _super);
  16769. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  16770. var _this = this;
  16771. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  16772. this.color = color;
  16773. this.depth = depth;
  16774. this.colorLevel = colorLevel;
  16775. this.onActivate = function (cam) {
  16776. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  16777. };
  16778. this.onApply = function (effect) {
  16779. effect.setColor3("baseColor", _this.color);
  16780. effect.setFloat("depth", _this.depth);
  16781. effect.setFloat("colorLevel", _this.colorLevel);
  16782. effect.setTexture("refractionSampler", _this._refRexture);
  16783. };
  16784. }
  16785. // Methods
  16786. RefractionPostProcess.prototype.dispose = function (camera) {
  16787. if (this._refRexture) {
  16788. this._refRexture.dispose();
  16789. }
  16790. _super.prototype.dispose.call(this, camera);
  16791. };
  16792. return RefractionPostProcess;
  16793. })(BABYLON.PostProcess);
  16794. BABYLON.RefractionPostProcess = RefractionPostProcess;
  16795. })(BABYLON || (BABYLON = {}));
  16796. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  16797. var BABYLON;
  16798. (function (BABYLON) {
  16799. var BlackAndWhitePostProcess = (function (_super) {
  16800. __extends(BlackAndWhitePostProcess, _super);
  16801. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  16802. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  16803. }
  16804. return BlackAndWhitePostProcess;
  16805. })(BABYLON.PostProcess);
  16806. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  16807. })(BABYLON || (BABYLON = {}));
  16808. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  16809. var BABYLON;
  16810. (function (BABYLON) {
  16811. var ConvolutionPostProcess = (function (_super) {
  16812. __extends(ConvolutionPostProcess, _super);
  16813. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  16814. var _this = this;
  16815. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  16816. this.kernel = kernel;
  16817. this.onApply = function (effect) {
  16818. effect.setFloat2("screenSize", _this.width, _this.height);
  16819. effect.setArray("kernel", _this.kernel);
  16820. };
  16821. }
  16822. // Statics
  16823. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  16824. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  16825. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  16826. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  16827. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  16828. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  16829. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  16830. return ConvolutionPostProcess;
  16831. })(BABYLON.PostProcess);
  16832. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  16833. })(BABYLON || (BABYLON = {}));
  16834. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  16835. var BABYLON;
  16836. (function (BABYLON) {
  16837. var FxaaPostProcess = (function (_super) {
  16838. __extends(FxaaPostProcess, _super);
  16839. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  16840. var _this = this;
  16841. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  16842. this.onSizeChanged = function () {
  16843. _this.texelWidth = 1.0 / _this.width;
  16844. _this.texelHeight = 1.0 / _this.height;
  16845. };
  16846. this.onApply = function (effect) {
  16847. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  16848. };
  16849. }
  16850. return FxaaPostProcess;
  16851. })(BABYLON.PostProcess);
  16852. BABYLON.FxaaPostProcess = FxaaPostProcess;
  16853. })(BABYLON || (BABYLON = {}));
  16854. //# sourceMappingURL=babylon.fxaaPostProcess.js.mapvar BABYLON;
  16855. (function (BABYLON) {
  16856. var LensFlare = (function () {
  16857. function LensFlare(size, position, color, imgUrl, system) {
  16858. this.size = size;
  16859. this.position = position;
  16860. this.dispose = function () {
  16861. if (this.texture) {
  16862. this.texture.dispose();
  16863. }
  16864. // Remove from scene
  16865. var index = this._system.lensFlares.indexOf(this);
  16866. this._system.lensFlares.splice(index, 1);
  16867. };
  16868. this.color = color || new BABYLON.Color3(1, 1, 1);
  16869. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  16870. this._system = system;
  16871. system.lensFlares.push(this);
  16872. }
  16873. return LensFlare;
  16874. })();
  16875. BABYLON.LensFlare = LensFlare;
  16876. })(BABYLON || (BABYLON = {}));
  16877. //# sourceMappingURL=babylon.lensFlare.js.mapvar BABYLON;
  16878. (function (BABYLON) {
  16879. var LensFlareSystem = (function () {
  16880. function LensFlareSystem(name, emitter, scene) {
  16881. this.name = name;
  16882. this.lensFlares = new Array();
  16883. this.borderLimit = 300;
  16884. this._vertexDeclaration = [2];
  16885. this._vertexStrideSize = 2 * 4;
  16886. this._isEnabled = true;
  16887. this._scene = scene;
  16888. this._emitter = emitter;
  16889. scene.lensFlareSystems.push(this);
  16890. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  16891. // VBO
  16892. var vertices = [];
  16893. vertices.push(1, 1);
  16894. vertices.push(-1, 1);
  16895. vertices.push(-1, -1);
  16896. vertices.push(1, -1);
  16897. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  16898. // Indices
  16899. var indices = [];
  16900. indices.push(0);
  16901. indices.push(1);
  16902. indices.push(2);
  16903. indices.push(0);
  16904. indices.push(2);
  16905. indices.push(3);
  16906. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  16907. // Effects
  16908. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  16909. }
  16910. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  16911. get: function () {
  16912. return this._isEnabled;
  16913. },
  16914. set: function (value) {
  16915. this._isEnabled = value;
  16916. },
  16917. enumerable: true,
  16918. configurable: true
  16919. });
  16920. LensFlareSystem.prototype.getScene = function () {
  16921. return this._scene;
  16922. };
  16923. LensFlareSystem.prototype.getEmitter = function () {
  16924. return this._emitter;
  16925. };
  16926. LensFlareSystem.prototype.getEmitterPosition = function () {
  16927. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  16928. };
  16929. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  16930. var position = this.getEmitterPosition();
  16931. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  16932. this._positionX = position.x;
  16933. this._positionY = position.y;
  16934. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  16935. if (position.z > 0) {
  16936. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  16937. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  16938. return true;
  16939. }
  16940. }
  16941. return false;
  16942. };
  16943. LensFlareSystem.prototype._isVisible = function () {
  16944. if (!this._isEnabled) {
  16945. return false;
  16946. }
  16947. var emitterPosition = this.getEmitterPosition();
  16948. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  16949. var distance = direction.length();
  16950. direction.normalize();
  16951. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  16952. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  16953. return !pickInfo.hit || pickInfo.distance > distance;
  16954. };
  16955. LensFlareSystem.prototype.render = function () {
  16956. if (!this._effect.isReady())
  16957. return false;
  16958. var engine = this._scene.getEngine();
  16959. var viewport = this._scene.activeCamera.viewport;
  16960. var globalViewport = viewport.toGlobal(engine);
  16961. // Position
  16962. if (!this.computeEffectivePosition(globalViewport)) {
  16963. return false;
  16964. }
  16965. // Visibility
  16966. if (!this._isVisible()) {
  16967. return false;
  16968. }
  16969. // Intensity
  16970. var awayX;
  16971. var awayY;
  16972. if (this._positionX < this.borderLimit + globalViewport.x) {
  16973. awayX = this.borderLimit + globalViewport.x - this._positionX;
  16974. }
  16975. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  16976. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  16977. }
  16978. else {
  16979. awayX = 0;
  16980. }
  16981. if (this._positionY < this.borderLimit + globalViewport.y) {
  16982. awayY = this.borderLimit + globalViewport.y - this._positionY;
  16983. }
  16984. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  16985. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  16986. }
  16987. else {
  16988. awayY = 0;
  16989. }
  16990. var away = (awayX > awayY) ? awayX : awayY;
  16991. if (away > this.borderLimit) {
  16992. away = this.borderLimit;
  16993. }
  16994. var intensity = 1.0 - (away / this.borderLimit);
  16995. if (intensity < 0) {
  16996. return false;
  16997. }
  16998. if (intensity > 1.0) {
  16999. intensity = 1.0;
  17000. }
  17001. // Position
  17002. var centerX = globalViewport.x + globalViewport.width / 2;
  17003. var centerY = globalViewport.y + globalViewport.height / 2;
  17004. var distX = centerX - this._positionX;
  17005. var distY = centerY - this._positionY;
  17006. // Effects
  17007. engine.enableEffect(this._effect);
  17008. engine.setState(false);
  17009. engine.setDepthBuffer(false);
  17010. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  17011. // VBOs
  17012. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  17013. for (var index = 0; index < this.lensFlares.length; index++) {
  17014. var flare = this.lensFlares[index];
  17015. var x = centerX - (distX * flare.position);
  17016. var y = centerY - (distY * flare.position);
  17017. var cw = flare.size;
  17018. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera);
  17019. var cx = 2 * (x / globalViewport.width) - 1.0;
  17020. var cy = 1.0 - 2 * (y / globalViewport.height);
  17021. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  17022. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  17023. // Texture
  17024. this._effect.setTexture("textureSampler", flare.texture);
  17025. // Color
  17026. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  17027. // Draw order
  17028. engine.draw(true, 0, 6);
  17029. }
  17030. engine.setDepthBuffer(true);
  17031. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  17032. return true;
  17033. };
  17034. LensFlareSystem.prototype.dispose = function () {
  17035. if (this._vertexBuffer) {
  17036. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  17037. this._vertexBuffer = null;
  17038. }
  17039. if (this._indexBuffer) {
  17040. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  17041. this._indexBuffer = null;
  17042. }
  17043. while (this.lensFlares.length) {
  17044. this.lensFlares[0].dispose();
  17045. }
  17046. // Remove from scene
  17047. var index = this._scene.lensFlareSystems.indexOf(this);
  17048. this._scene.lensFlareSystems.splice(index, 1);
  17049. };
  17050. return LensFlareSystem;
  17051. })();
  17052. BABYLON.LensFlareSystem = LensFlareSystem;
  17053. })(BABYLON || (BABYLON = {}));
  17054. //# sourceMappingURL=babylon.lensFlareSystem.js.mapvar BABYLON;
  17055. (function (BABYLON) {
  17056. var IntersectionInfo = (function () {
  17057. function IntersectionInfo(bu, bv, distance) {
  17058. this.bu = bu;
  17059. this.bv = bv;
  17060. this.distance = distance;
  17061. this.faceId = 0;
  17062. this.subMeshId = 0;
  17063. }
  17064. return IntersectionInfo;
  17065. })();
  17066. BABYLON.IntersectionInfo = IntersectionInfo;
  17067. var PickingInfo = (function () {
  17068. function PickingInfo() {
  17069. this.hit = false;
  17070. this.distance = 0;
  17071. this.pickedPoint = null;
  17072. this.pickedMesh = null;
  17073. this.bu = 0;
  17074. this.bv = 0;
  17075. this.faceId = -1;
  17076. this.subMeshId = 0;
  17077. }
  17078. // Methods
  17079. PickingInfo.prototype.getNormal = function () {
  17080. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  17081. return null;
  17082. }
  17083. var indices = this.pickedMesh.getIndices();
  17084. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  17085. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  17086. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  17087. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  17088. normal0 = normal0.scale(this.bu);
  17089. normal1 = normal1.scale(this.bv);
  17090. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  17091. return new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  17092. };
  17093. PickingInfo.prototype.getTextureCoordinates = function () {
  17094. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  17095. return null;
  17096. }
  17097. var indices = this.pickedMesh.getIndices();
  17098. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  17099. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  17100. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  17101. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  17102. uv0 = uv0.scale(this.bu);
  17103. uv1 = uv1.scale(this.bv);
  17104. uv2 = uv2.scale(1.0 - this.bu - this.bv);
  17105. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  17106. };
  17107. return PickingInfo;
  17108. })();
  17109. BABYLON.PickingInfo = PickingInfo;
  17110. })(BABYLON || (BABYLON = {}));
  17111. //# sourceMappingURL=babylon.pickingInfo.js.mapvar BABYLON;
  17112. (function (BABYLON) {
  17113. var FilesInput = (function () {
  17114. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  17115. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  17116. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  17117. this.engine = p_engine;
  17118. this.canvas = p_canvas;
  17119. this.currentScene = p_scene;
  17120. this.sceneLoadedCallback = p_sceneLoadedCallback;
  17121. this.progressCallback = p_progressCallback;
  17122. this.additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  17123. this.textureLoadingCallback = p_textureLoadingCallback;
  17124. this.startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  17125. }
  17126. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  17127. var _this = this;
  17128. if (p_elementToMonitor) {
  17129. this.elementToMonitor = p_elementToMonitor;
  17130. this.elementToMonitor.addEventListener("dragenter", function (e) {
  17131. _this.drag(e);
  17132. }, false);
  17133. this.elementToMonitor.addEventListener("dragover", function (e) {
  17134. _this.drag(e);
  17135. }, false);
  17136. this.elementToMonitor.addEventListener("drop", function (e) {
  17137. _this.drop(e);
  17138. }, false);
  17139. }
  17140. };
  17141. FilesInput.prototype.renderFunction = function () {
  17142. if (this.additionnalRenderLoopLogicCallback) {
  17143. this.additionnalRenderLoopLogicCallback();
  17144. }
  17145. if (this.currentScene) {
  17146. if (this.textureLoadingCallback) {
  17147. var remaining = this.currentScene.getWaitingItemsCount();
  17148. if (remaining > 0) {
  17149. this.textureLoadingCallback(remaining);
  17150. }
  17151. }
  17152. this.currentScene.render();
  17153. }
  17154. };
  17155. FilesInput.prototype.drag = function (e) {
  17156. e.stopPropagation();
  17157. e.preventDefault();
  17158. };
  17159. FilesInput.prototype.drop = function (eventDrop) {
  17160. eventDrop.stopPropagation();
  17161. eventDrop.preventDefault();
  17162. this.loadFiles(eventDrop);
  17163. };
  17164. FilesInput.prototype.loadFiles = function (event) {
  17165. var _this = this;
  17166. var that = this;
  17167. if (this.startingProcessingFilesCallback)
  17168. this.startingProcessingFilesCallback();
  17169. var sceneFileToLoad;
  17170. var filesToLoad;
  17171. // Handling data transfer via drag'n'drop
  17172. if (event && event.dataTransfer && event.dataTransfer.files) {
  17173. filesToLoad = event.dataTransfer.files;
  17174. }
  17175. // Handling files from input files
  17176. if (event && event.target && event.target.files) {
  17177. filesToLoad = event.target.files;
  17178. }
  17179. if (filesToLoad && filesToLoad.length > 0) {
  17180. for (var i = 0; i < filesToLoad.length; i++) {
  17181. switch (filesToLoad[i].type) {
  17182. case "image/jpeg":
  17183. case "image/png":
  17184. case "image/bmp":
  17185. FilesInput.FilesTextures[filesToLoad[i].name] = filesToLoad[i];
  17186. break;
  17187. case "image/targa":
  17188. case "image/vnd.ms-dds":
  17189. case "audio/wav":
  17190. case "audio/x-wav":
  17191. case "audio/mp3":
  17192. case "audio/mpeg":
  17193. case "audio/mpeg3":
  17194. case "audio/x-mpeg-3":
  17195. case "audio/ogg":
  17196. FilesInput.FilesToLoad[filesToLoad[i].name] = filesToLoad[i];
  17197. break;
  17198. default:
  17199. if (filesToLoad[i].name.indexOf(".babylon") !== -1 && filesToLoad[i].name.indexOf(".manifest") === -1 && filesToLoad[i].name.indexOf(".incremental") === -1 && filesToLoad[i].name.indexOf(".babylonmeshdata") === -1 && filesToLoad[i].name.indexOf(".babylongeometrydata") === -1) {
  17200. sceneFileToLoad = filesToLoad[i];
  17201. }
  17202. break;
  17203. }
  17204. }
  17205. // If a ".babylon" file has been provided
  17206. if (sceneFileToLoad) {
  17207. if (this.currentScene) {
  17208. this.engine.stopRenderLoop();
  17209. this.currentScene.dispose();
  17210. }
  17211. BABYLON.SceneLoader.Load("file:", sceneFileToLoad, this.engine, function (newScene) {
  17212. that.currentScene = newScene;
  17213. // Wait for textures and shaders to be ready
  17214. that.currentScene.executeWhenReady(function () {
  17215. // Attach camera to canvas inputs
  17216. if (that.currentScene.activeCamera) {
  17217. that.currentScene.activeCamera.attachControl(that.canvas);
  17218. }
  17219. if (that.sceneLoadedCallback) {
  17220. that.sceneLoadedCallback(sceneFileToLoad, that.currentScene);
  17221. }
  17222. that.engine.runRenderLoop(function () {
  17223. that.renderFunction();
  17224. });
  17225. });
  17226. }, function (progress) {
  17227. if (_this.progressCallback) {
  17228. _this.progressCallback(progress);
  17229. }
  17230. });
  17231. }
  17232. else {
  17233. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  17234. }
  17235. }
  17236. };
  17237. FilesInput.FilesTextures = new Array();
  17238. FilesInput.FilesToLoad = new Array();
  17239. return FilesInput;
  17240. })();
  17241. BABYLON.FilesInput = FilesInput;
  17242. })(BABYLON || (BABYLON = {}));
  17243. //# sourceMappingURL=babylon.filesInput.js.mapvar BABYLON;
  17244. (function (BABYLON) {
  17245. var OimoJSPlugin = (function () {
  17246. function OimoJSPlugin() {
  17247. this._registeredMeshes = [];
  17248. /**
  17249. * Update the body position according to the mesh position
  17250. * @param mesh
  17251. */
  17252. this.updateBodyPosition = function (mesh) {
  17253. for (var index = 0; index < this._registeredMeshes.length; index++) {
  17254. var registeredMesh = this._registeredMeshes[index];
  17255. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  17256. var body = registeredMesh.body.body;
  17257. mesh.computeWorldMatrix(true);
  17258. var center = mesh.getBoundingInfo().boundingBox.center;
  17259. body.setPosition(center.x, center.y, center.z);
  17260. body.setRotation(mesh.rotation.x, mesh.rotation.y, mesh.rotation.z);
  17261. return;
  17262. }
  17263. // Case where the parent has been updated
  17264. if (registeredMesh.mesh.parent === mesh) {
  17265. mesh.computeWorldMatrix(true);
  17266. registeredMesh.mesh.computeWorldMatrix(true);
  17267. var absolutePosition = registeredMesh.mesh.getAbsolutePosition();
  17268. var absoluteRotation = mesh.rotation;
  17269. body = registeredMesh.body.body;
  17270. body.setPosition(absolutePosition.x, absolutePosition.y, absolutePosition.z);
  17271. body.setRotation(absoluteRotation.x, absoluteRotation.y, absoluteRotation.z);
  17272. return;
  17273. }
  17274. }
  17275. };
  17276. }
  17277. OimoJSPlugin.prototype._checkWithEpsilon = function (value) {
  17278. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  17279. };
  17280. OimoJSPlugin.prototype.initialize = function (iterations) {
  17281. this._world = new OIMO.World();
  17282. this._world.clear();
  17283. };
  17284. OimoJSPlugin.prototype.setGravity = function (gravity) {
  17285. this._world.gravity = gravity;
  17286. };
  17287. OimoJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  17288. var body = null;
  17289. this.unregisterMesh(mesh);
  17290. mesh.computeWorldMatrix(true);
  17291. var initialRotation = null;
  17292. if (mesh.rotationQuaternion) {
  17293. initialRotation = mesh.rotationQuaternion.clone();
  17294. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  17295. mesh.computeWorldMatrix(true);
  17296. }
  17297. var bbox = mesh.getBoundingInfo().boundingBox;
  17298. // The delta between the mesh position and the mesh bounding box center
  17299. var deltaPosition = mesh.position.subtract(bbox.center);
  17300. // Transform delta position with the rotation
  17301. if (initialRotation) {
  17302. var m = new BABYLON.Matrix();
  17303. initialRotation.toRotationMatrix(m);
  17304. deltaPosition = BABYLON.Vector3.TransformCoordinates(deltaPosition, m);
  17305. }
  17306. switch (impostor) {
  17307. case BABYLON.PhysicsEngine.SphereImpostor:
  17308. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  17309. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  17310. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  17311. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  17312. body = new OIMO.Body({
  17313. type: 'sphere',
  17314. size: [size],
  17315. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  17316. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  17317. move: options.mass != 0,
  17318. config: [options.mass, options.friction, options.restitution],
  17319. world: this._world
  17320. });
  17321. break;
  17322. case BABYLON.PhysicsEngine.PlaneImpostor:
  17323. case BABYLON.PhysicsEngine.CylinderImpostor:
  17324. case BABYLON.PhysicsEngine.BoxImpostor:
  17325. var min = bbox.minimumWorld;
  17326. var max = bbox.maximumWorld;
  17327. var box = max.subtract(min);
  17328. var sizeX = this._checkWithEpsilon(box.x);
  17329. var sizeY = this._checkWithEpsilon(box.y);
  17330. var sizeZ = this._checkWithEpsilon(box.z);
  17331. body = new OIMO.Body({
  17332. type: 'box',
  17333. size: [sizeX, sizeY, sizeZ],
  17334. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  17335. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  17336. move: options.mass != 0,
  17337. config: [options.mass, options.friction, options.restitution],
  17338. world: this._world
  17339. });
  17340. break;
  17341. }
  17342. //If quaternion was set as the rotation of the object
  17343. if (initialRotation) {
  17344. //We have to access the rigid body's properties to set the quaternion.
  17345. //The setQuaternion function of Oimo only sets the newOrientation that is only set after an impulse is given or a collision.
  17346. body.body.orientation = new OIMO.Quat(initialRotation.w, initialRotation.x, initialRotation.y, initialRotation.z);
  17347. //update the internal rotation matrix
  17348. body.body.syncShapes();
  17349. }
  17350. this._registeredMeshes.push({
  17351. mesh: mesh,
  17352. body: body,
  17353. delta: deltaPosition
  17354. });
  17355. return body;
  17356. };
  17357. OimoJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  17358. var types = [], sizes = [], positions = [], rotations = [];
  17359. var initialMesh = parts[0].mesh;
  17360. for (var index = 0; index < parts.length; index++) {
  17361. var part = parts[index];
  17362. var bodyParameters = this._createBodyAsCompound(part, options, initialMesh);
  17363. types.push(bodyParameters.type);
  17364. sizes.push.apply(sizes, bodyParameters.size);
  17365. positions.push.apply(positions, bodyParameters.pos);
  17366. rotations.push.apply(rotations, bodyParameters.rot);
  17367. }
  17368. var body = new OIMO.Body({
  17369. type: types,
  17370. size: sizes,
  17371. pos: positions,
  17372. rot: rotations,
  17373. move: options.mass != 0,
  17374. config: [options.mass, options.friction, options.restitution],
  17375. world: this._world
  17376. });
  17377. this._registeredMeshes.push({
  17378. mesh: initialMesh,
  17379. body: body
  17380. });
  17381. return body;
  17382. };
  17383. OimoJSPlugin.prototype._createBodyAsCompound = function (part, options, initialMesh) {
  17384. var bodyParameters = null;
  17385. var mesh = part.mesh;
  17386. // We need the bounding box/sphere info to compute the physics body
  17387. mesh.computeWorldMatrix();
  17388. switch (part.impostor) {
  17389. case BABYLON.PhysicsEngine.SphereImpostor:
  17390. var bbox = mesh.getBoundingInfo().boundingBox;
  17391. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  17392. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  17393. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  17394. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  17395. bodyParameters = {
  17396. type: 'sphere',
  17397. /* bug with oimo : sphere needs 3 sizes in this case */
  17398. size: [size, -1, -1],
  17399. pos: [mesh.position.x, mesh.position.y, mesh.position.z],
  17400. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  17401. };
  17402. break;
  17403. case BABYLON.PhysicsEngine.PlaneImpostor:
  17404. case BABYLON.PhysicsEngine.BoxImpostor:
  17405. bbox = mesh.getBoundingInfo().boundingBox;
  17406. var min = bbox.minimumWorld;
  17407. var max = bbox.maximumWorld;
  17408. var box = max.subtract(min);
  17409. var sizeX = this._checkWithEpsilon(box.x);
  17410. var sizeY = this._checkWithEpsilon(box.y);
  17411. var sizeZ = this._checkWithEpsilon(box.z);
  17412. var relativePosition = mesh.position;
  17413. bodyParameters = {
  17414. type: 'box',
  17415. size: [sizeX, sizeY, sizeZ],
  17416. pos: [relativePosition.x, relativePosition.y, relativePosition.z],
  17417. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  17418. };
  17419. break;
  17420. }
  17421. return bodyParameters;
  17422. };
  17423. OimoJSPlugin.prototype.unregisterMesh = function (mesh) {
  17424. for (var index = 0; index < this._registeredMeshes.length; index++) {
  17425. var registeredMesh = this._registeredMeshes[index];
  17426. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  17427. if (registeredMesh.body) {
  17428. this._world.removeRigidBody(registeredMesh.body.body);
  17429. this._unbindBody(registeredMesh.body);
  17430. }
  17431. this._registeredMeshes.splice(index, 1);
  17432. return;
  17433. }
  17434. }
  17435. };
  17436. OimoJSPlugin.prototype._unbindBody = function (body) {
  17437. for (var index = 0; index < this._registeredMeshes.length; index++) {
  17438. var registeredMesh = this._registeredMeshes[index];
  17439. if (registeredMesh.body === body) {
  17440. registeredMesh.body = null;
  17441. }
  17442. }
  17443. };
  17444. OimoJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  17445. for (var index = 0; index < this._registeredMeshes.length; index++) {
  17446. var registeredMesh = this._registeredMeshes[index];
  17447. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  17448. // Get object mass to have a behaviour similar to cannon.js
  17449. var mass = registeredMesh.body.body.massInfo.mass;
  17450. // The force is scaled with the mass of object
  17451. registeredMesh.body.body.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  17452. return;
  17453. }
  17454. }
  17455. };
  17456. OimoJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  17457. var body1 = null, body2 = null;
  17458. for (var index = 0; index < this._registeredMeshes.length; index++) {
  17459. var registeredMesh = this._registeredMeshes[index];
  17460. if (registeredMesh.mesh === mesh1) {
  17461. body1 = registeredMesh.body.body;
  17462. }
  17463. else if (registeredMesh.mesh === mesh2) {
  17464. body2 = registeredMesh.body.body;
  17465. }
  17466. }
  17467. if (!body1 || !body2) {
  17468. return false;
  17469. }
  17470. if (!options) {
  17471. options = {};
  17472. }
  17473. new OIMO.Link({
  17474. type: options.type,
  17475. body1: body1,
  17476. body2: body2,
  17477. min: options.min,
  17478. max: options.max,
  17479. axe1: options.axe1,
  17480. axe2: options.axe2,
  17481. pos1: [pivot1.x, pivot1.y, pivot1.z],
  17482. pos2: [pivot2.x, pivot2.y, pivot2.z],
  17483. collision: options.collision,
  17484. spring: options.spring,
  17485. world: this._world
  17486. });
  17487. return true;
  17488. };
  17489. OimoJSPlugin.prototype.dispose = function () {
  17490. this._world.clear();
  17491. while (this._registeredMeshes.length) {
  17492. this.unregisterMesh(this._registeredMeshes[0].mesh);
  17493. }
  17494. };
  17495. OimoJSPlugin.prototype.isSupported = function () {
  17496. return OIMO !== undefined;
  17497. };
  17498. OimoJSPlugin.prototype._getLastShape = function (body) {
  17499. var lastShape = body.shapes;
  17500. while (lastShape.next) {
  17501. lastShape = lastShape.next;
  17502. }
  17503. return lastShape;
  17504. };
  17505. OimoJSPlugin.prototype.runOneStep = function (time) {
  17506. this._world.step();
  17507. // Update the position of all registered meshes
  17508. var i = this._registeredMeshes.length;
  17509. var m;
  17510. while (i--) {
  17511. var body = this._registeredMeshes[i].body.body;
  17512. var mesh = this._registeredMeshes[i].mesh;
  17513. var delta = this._registeredMeshes[i].delta;
  17514. if (!body.sleeping) {
  17515. if (body.shapes.next) {
  17516. var parentShape = this._getLastShape(body);
  17517. mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  17518. mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  17519. mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  17520. var mtx = BABYLON.Matrix.FromArray(body.getMatrix());
  17521. if (!mesh.rotationQuaternion) {
  17522. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  17523. }
  17524. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  17525. mesh.computeWorldMatrix();
  17526. }
  17527. else {
  17528. m = body.getMatrix();
  17529. mtx = BABYLON.Matrix.FromArray(m);
  17530. // Body position
  17531. var bodyX = mtx.m[12], bodyY = mtx.m[13], bodyZ = mtx.m[14];
  17532. if (!delta) {
  17533. mesh.position.x = bodyX;
  17534. mesh.position.y = bodyY;
  17535. mesh.position.z = bodyZ;
  17536. }
  17537. else {
  17538. mesh.position.x = bodyX + delta.x;
  17539. mesh.position.y = bodyY + delta.y;
  17540. mesh.position.z = bodyZ + delta.z;
  17541. }
  17542. if (!mesh.rotationQuaternion) {
  17543. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  17544. }
  17545. BABYLON.Quaternion.FromRotationMatrixToRef(mtx, mesh.rotationQuaternion);
  17546. mesh.computeWorldMatrix();
  17547. }
  17548. }
  17549. }
  17550. };
  17551. return OimoJSPlugin;
  17552. })();
  17553. BABYLON.OimoJSPlugin = OimoJSPlugin;
  17554. })(BABYLON || (BABYLON = {}));
  17555. //# sourceMappingURL=babylon.oimoJSPlugin.js.mapvar BABYLON;
  17556. (function (BABYLON) {
  17557. var PhysicsEngine = (function () {
  17558. function PhysicsEngine(plugin) {
  17559. this._currentPlugin = plugin || new BABYLON.OimoJSPlugin();
  17560. }
  17561. PhysicsEngine.prototype._initialize = function (gravity) {
  17562. this._currentPlugin.initialize();
  17563. this._setGravity(gravity);
  17564. };
  17565. PhysicsEngine.prototype._runOneStep = function (delta) {
  17566. if (delta > 0.1) {
  17567. delta = 0.1;
  17568. }
  17569. else if (delta <= 0) {
  17570. delta = 1.0 / 60.0;
  17571. }
  17572. this._currentPlugin.runOneStep(delta);
  17573. };
  17574. PhysicsEngine.prototype._setGravity = function (gravity) {
  17575. this.gravity = gravity || new BABYLON.Vector3(0, -9.82, 0);
  17576. this._currentPlugin.setGravity(this.gravity);
  17577. };
  17578. PhysicsEngine.prototype._registerMesh = function (mesh, impostor, options) {
  17579. return this._currentPlugin.registerMesh(mesh, impostor, options);
  17580. };
  17581. PhysicsEngine.prototype._registerMeshesAsCompound = function (parts, options) {
  17582. return this._currentPlugin.registerMeshesAsCompound(parts, options);
  17583. };
  17584. PhysicsEngine.prototype._unregisterMesh = function (mesh) {
  17585. this._currentPlugin.unregisterMesh(mesh);
  17586. };
  17587. PhysicsEngine.prototype._applyImpulse = function (mesh, force, contactPoint) {
  17588. this._currentPlugin.applyImpulse(mesh, force, contactPoint);
  17589. };
  17590. PhysicsEngine.prototype._createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  17591. return this._currentPlugin.createLink(mesh1, mesh2, pivot1, pivot2, options);
  17592. };
  17593. PhysicsEngine.prototype._updateBodyPosition = function (mesh) {
  17594. this._currentPlugin.updateBodyPosition(mesh);
  17595. };
  17596. PhysicsEngine.prototype.dispose = function () {
  17597. this._currentPlugin.dispose();
  17598. };
  17599. PhysicsEngine.prototype.isSupported = function () {
  17600. return this._currentPlugin.isSupported();
  17601. };
  17602. // Statics
  17603. PhysicsEngine.NoImpostor = 0;
  17604. PhysicsEngine.SphereImpostor = 1;
  17605. PhysicsEngine.BoxImpostor = 2;
  17606. PhysicsEngine.PlaneImpostor = 3;
  17607. PhysicsEngine.MeshImpostor = 4;
  17608. PhysicsEngine.CapsuleImpostor = 5;
  17609. PhysicsEngine.ConeImpostor = 6;
  17610. PhysicsEngine.CylinderImpostor = 7;
  17611. PhysicsEngine.ConvexHullImpostor = 8;
  17612. PhysicsEngine.Epsilon = 0.001;
  17613. return PhysicsEngine;
  17614. })();
  17615. BABYLON.PhysicsEngine = PhysicsEngine;
  17616. })(BABYLON || (BABYLON = {}));
  17617. //# sourceMappingURL=babylon.physicsEngine.js.mapvar BABYLON;
  17618. (function (BABYLON) {
  17619. var serializeLight = function (light) {
  17620. var serializationObject = {};
  17621. serializationObject.name = light.name;
  17622. serializationObject.id = light.id;
  17623. serializationObject.tags = BABYLON.Tags.GetTags(light);
  17624. if (light instanceof BABYLON.PointLight) {
  17625. serializationObject.type = 0;
  17626. serializationObject.position = light.position.asArray();
  17627. }
  17628. else if (light instanceof BABYLON.DirectionalLight) {
  17629. serializationObject.type = 1;
  17630. var directionalLight = light;
  17631. serializationObject.position = directionalLight.position.asArray();
  17632. serializationObject.direction = directionalLight.direction.asArray();
  17633. }
  17634. else if (light instanceof BABYLON.SpotLight) {
  17635. serializationObject.type = 2;
  17636. var spotLight = light;
  17637. serializationObject.position = spotLight.position.asArray();
  17638. serializationObject.direction = spotLight.position.asArray();
  17639. serializationObject.angle = spotLight.angle;
  17640. serializationObject.exponent = spotLight.exponent;
  17641. }
  17642. else if (light instanceof BABYLON.HemisphericLight) {
  17643. serializationObject.type = 3;
  17644. var hemisphericLight = light;
  17645. serializationObject.direction = hemisphericLight.direction.asArray();
  17646. serializationObject.groundColor = hemisphericLight.groundColor.asArray();
  17647. }
  17648. if (light.intensity) {
  17649. serializationObject.intensity = light.intensity;
  17650. }
  17651. serializationObject.range = light.range;
  17652. serializationObject.diffuse = light.diffuse.asArray();
  17653. serializationObject.specular = light.specular.asArray();
  17654. return serializationObject;
  17655. };
  17656. var serializeFresnelParameter = function (fresnelParameter) {
  17657. var serializationObject = {};
  17658. serializationObject.isEnabled = fresnelParameter.isEnabled;
  17659. serializationObject.leftColor = fresnelParameter.leftColor;
  17660. serializationObject.rightColor = fresnelParameter.rightColor;
  17661. serializationObject.bias = fresnelParameter.bias;
  17662. serializationObject.power = fresnelParameter.power;
  17663. return serializationObject;
  17664. };
  17665. var serializeCamera = function (camera) {
  17666. var serializationObject = {};
  17667. serializationObject.name = camera.name;
  17668. serializationObject.tags = BABYLON.Tags.GetTags(camera);
  17669. serializationObject.id = camera.id;
  17670. serializationObject.position = camera.position.asArray();
  17671. // Parent
  17672. if (camera.parent) {
  17673. serializationObject.parentId = camera.parent.id;
  17674. }
  17675. // Target
  17676. serializationObject.rotation = camera.rotation.asArray();
  17677. // Locked target
  17678. if (camera.lockedTarget && camera.lockedTarget.id) {
  17679. serializationObject.lockedTargetId = camera.lockedTarget.id;
  17680. }
  17681. serializationObject.fov = camera.fov;
  17682. serializationObject.minZ = camera.minZ;
  17683. serializationObject.maxZ = camera.maxZ;
  17684. serializationObject.speed = camera.speed;
  17685. serializationObject.inertia = camera.inertia;
  17686. serializationObject.checkCollisions = camera.checkCollisions;
  17687. serializationObject.applyGravity = camera.applyGravity;
  17688. if (camera.ellipsoid) {
  17689. serializationObject.ellipsoid = camera.ellipsoid.asArray();
  17690. }
  17691. // Animations
  17692. appendAnimations(camera, serializationObject);
  17693. // Layer mask
  17694. serializationObject.layerMask = camera.layerMask;
  17695. return serializationObject;
  17696. };
  17697. var appendAnimations = function (source, destination) {
  17698. if (source.animations) {
  17699. destination.animations = [];
  17700. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  17701. var animation = source.animations[animationIndex];
  17702. destination.animations.push(serializeAnimation(animation));
  17703. }
  17704. }
  17705. };
  17706. var serializeAnimation = function (animation) {
  17707. var serializationObject = {};
  17708. serializationObject.name = animation.name;
  17709. serializationObject.property = animation.targetProperty;
  17710. serializationObject.framePerSecond = animation.framePerSecond;
  17711. serializationObject.dataType = animation.dataType;
  17712. serializationObject.loopBehavior = animation.loopMode;
  17713. var dataType = animation.dataType;
  17714. serializationObject.keys = [];
  17715. var keys = animation.getKeys();
  17716. for (var index = 0; index < keys.length; index++) {
  17717. var animationKey = keys[index];
  17718. var key = {};
  17719. key.frame = animationKey.frame;
  17720. switch (dataType) {
  17721. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  17722. key.values = [animationKey.value];
  17723. break;
  17724. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  17725. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  17726. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  17727. key.values = animationKey.value.asArray();
  17728. break;
  17729. }
  17730. serializationObject.keys.push(key);
  17731. }
  17732. return serializationObject;
  17733. };
  17734. var serializeMultiMaterial = function (material) {
  17735. var serializationObject = {};
  17736. serializationObject.name = material.name;
  17737. serializationObject.id = material.id;
  17738. serializationObject.tags = BABYLON.Tags.GetTags(material);
  17739. serializationObject.materials = [];
  17740. for (var matIndex = 0; matIndex < material.subMaterials.length; matIndex++) {
  17741. var subMat = material.subMaterials[matIndex];
  17742. if (subMat) {
  17743. serializationObject.materials.push(subMat.id);
  17744. }
  17745. else {
  17746. serializationObject.materials.push(null);
  17747. }
  17748. }
  17749. return serializationObject;
  17750. };
  17751. var serializeMaterial = function (material) {
  17752. var serializationObject = {};
  17753. serializationObject.name = material.name;
  17754. serializationObject.ambient = material.ambientColor.asArray();
  17755. serializationObject.diffuse = material.diffuseColor.asArray();
  17756. serializationObject.specular = material.specularColor.asArray();
  17757. serializationObject.specularPower = material.specularPower;
  17758. serializationObject.emissive = material.emissiveColor.asArray();
  17759. serializationObject.alpha = material.alpha;
  17760. serializationObject.id = material.id;
  17761. serializationObject.tags = BABYLON.Tags.GetTags(material);
  17762. serializationObject.backFaceCulling = material.backFaceCulling;
  17763. if (material.diffuseTexture) {
  17764. serializationObject.diffuseTexture = serializeTexture(material.diffuseTexture);
  17765. }
  17766. if (material.diffuseFresnelParameters) {
  17767. serializationObject.diffuseFresnelParameters = serializeFresnelParameter(material.diffuseFresnelParameters);
  17768. }
  17769. if (material.ambientTexture) {
  17770. serializationObject.ambientTexture = serializeTexture(material.ambientTexture);
  17771. }
  17772. if (material.opacityTexture) {
  17773. serializationObject.opacityTexture = serializeTexture(material.opacityTexture);
  17774. }
  17775. if (material.opacityFresnelParameters) {
  17776. serializationObject.opacityFresnelParameters = serializeFresnelParameter(material.opacityFresnelParameters);
  17777. }
  17778. if (material.reflectionTexture) {
  17779. serializationObject.reflectionTexture = serializeTexture(material.reflectionTexture);
  17780. }
  17781. if (material.reflectionFresnelParameters) {
  17782. serializationObject.reflectionFresnelParameters = serializeFresnelParameter(material.reflectionFresnelParameters);
  17783. }
  17784. if (material.emissiveTexture) {
  17785. serializationObject.emissiveTexture = serializeTexture(material.emissiveTexture);
  17786. }
  17787. if (material.emissiveFresnelParameters) {
  17788. serializationObject.emissiveFresnelParameters = serializeFresnelParameter(material.emissiveFresnelParameters);
  17789. }
  17790. if (material.specularTexture) {
  17791. serializationObject.specularTexture = serializeTexture(material.specularTexture);
  17792. }
  17793. if (material.bumpTexture) {
  17794. serializationObject.bumpTexture = serializeTexture(material.bumpTexture);
  17795. }
  17796. return serializationObject;
  17797. };
  17798. var serializeTexture = function (texture) {
  17799. var serializationObject = {};
  17800. if (!texture.name) {
  17801. return null;
  17802. }
  17803. if (texture instanceof BABYLON.CubeTexture) {
  17804. serializationObject.name = texture.name;
  17805. serializationObject.hasAlpha = texture.hasAlpha;
  17806. serializationObject.level = texture.level;
  17807. serializationObject.coordinatesMode = texture.coordinatesMode;
  17808. return serializationObject;
  17809. }
  17810. if (texture instanceof BABYLON.MirrorTexture) {
  17811. var mirrorTexture = texture;
  17812. serializationObject.renderTargetSize = mirrorTexture.getRenderSize();
  17813. serializationObject.renderList = [];
  17814. for (var index = 0; index < mirrorTexture.renderList.length; index++) {
  17815. serializationObject.renderList.push(mirrorTexture.renderList[index].id);
  17816. }
  17817. serializationObject.mirrorPlane = mirrorTexture.mirrorPlane.asArray();
  17818. }
  17819. else if (texture instanceof BABYLON.RenderTargetTexture) {
  17820. var renderTargetTexture = texture;
  17821. serializationObject.renderTargetSize = renderTargetTexture.getRenderSize();
  17822. serializationObject.renderList = [];
  17823. for (index = 0; index < renderTargetTexture.renderList.length; index++) {
  17824. serializationObject.renderList.push(renderTargetTexture.renderList[index].id);
  17825. }
  17826. }
  17827. var regularTexture = texture;
  17828. serializationObject.name = texture.name;
  17829. serializationObject.hasAlpha = texture.hasAlpha;
  17830. serializationObject.level = texture.level;
  17831. serializationObject.coordinatesIndex = texture.coordinatesIndex;
  17832. serializationObject.coordinatesMode = texture.coordinatesMode;
  17833. serializationObject.uOffset = regularTexture.uOffset;
  17834. serializationObject.vOffset = regularTexture.vOffset;
  17835. serializationObject.uScale = regularTexture.uScale;
  17836. serializationObject.vScale = regularTexture.vScale;
  17837. serializationObject.uAng = regularTexture.uAng;
  17838. serializationObject.vAng = regularTexture.vAng;
  17839. serializationObject.wAng = regularTexture.wAng;
  17840. serializationObject.wrapU = texture.wrapU;
  17841. serializationObject.wrapV = texture.wrapV;
  17842. // Animations
  17843. appendAnimations(texture, serializationObject);
  17844. return serializationObject;
  17845. };
  17846. var serializeSkeleton = function (skeleton) {
  17847. var serializationObject = {};
  17848. serializationObject.name = skeleton.name;
  17849. serializationObject.id = skeleton.id;
  17850. serializationObject.bones = [];
  17851. for (var index = 0; index < skeleton.bones.length; index++) {
  17852. var bone = skeleton.bones[index];
  17853. var serializedBone = {
  17854. parentBoneIndex: bone.getParent() ? skeleton.bones.indexOf(bone.getParent()) : -1,
  17855. name: bone.name,
  17856. matrix: bone.getLocalMatrix().toArray()
  17857. };
  17858. serializationObject.bones.push(serializedBone);
  17859. if (bone.animations && bone.animations.length > 0) {
  17860. serializedBone.animation = serializeAnimation(bone.animations[0]);
  17861. }
  17862. }
  17863. return serializationObject;
  17864. };
  17865. var serializeParticleSystem = function (particleSystem) {
  17866. var serializationObject = {};
  17867. serializationObject.emitterId = particleSystem.emitter.id;
  17868. serializationObject.capacity = particleSystem.getCapacity();
  17869. if (particleSystem.particleTexture) {
  17870. serializationObject.textureName = particleSystem.particleTexture.name;
  17871. }
  17872. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  17873. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  17874. serializationObject.minSize = particleSystem.minSize;
  17875. serializationObject.maxSize = particleSystem.maxSize;
  17876. serializationObject.minLifeTime = particleSystem.minLifeTime;
  17877. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  17878. serializationObject.emitRate = particleSystem.emitRate;
  17879. serializationObject.minEmitBox = particleSystem.minEmitBox.asArray();
  17880. serializationObject.maxEmitBox = particleSystem.maxEmitBox.asArray();
  17881. serializationObject.gravity = particleSystem.gravity.asArray();
  17882. serializationObject.direction1 = particleSystem.direction1.asArray();
  17883. serializationObject.direction2 = particleSystem.direction2.asArray();
  17884. serializationObject.color1 = particleSystem.color1.asArray();
  17885. serializationObject.color2 = particleSystem.color2.asArray();
  17886. serializationObject.colorDead = particleSystem.colorDead.asArray();
  17887. serializationObject.updateSpeed = particleSystem.updateSpeed;
  17888. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  17889. serializationObject.textureMask = particleSystem.textureMask.asArray();
  17890. serializationObject.blendMode = particleSystem.blendMode;
  17891. return serializationObject;
  17892. };
  17893. var serializeLensFlareSystem = function (lensFlareSystem) {
  17894. var serializationObject = {};
  17895. serializationObject.emitterId = lensFlareSystem.getEmitter().id;
  17896. serializationObject.borderLimit = lensFlareSystem.borderLimit;
  17897. serializationObject.flares = [];
  17898. for (var index = 0; index < lensFlareSystem.lensFlares.length; index++) {
  17899. var flare = lensFlareSystem.lensFlares[index];
  17900. serializationObject.flares.push({
  17901. size: flare.size,
  17902. position: flare.position,
  17903. color: flare.color.asArray(),
  17904. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  17905. });
  17906. }
  17907. return serializationObject;
  17908. };
  17909. var serializeShadowGenerator = function (light) {
  17910. var serializationObject = {};
  17911. var shadowGenerator = light.getShadowGenerator();
  17912. serializationObject.lightId = light.id;
  17913. serializationObject.mapSize = shadowGenerator.getShadowMap().getRenderSize();
  17914. serializationObject.useVarianceShadowMap = shadowGenerator.useVarianceShadowMap;
  17915. serializationObject.usePoissonSampling = shadowGenerator.usePoissonSampling;
  17916. serializationObject.renderList = [];
  17917. for (var meshIndex = 0; meshIndex < shadowGenerator.getShadowMap().renderList.length; meshIndex++) {
  17918. var mesh = shadowGenerator.getShadowMap().renderList[meshIndex];
  17919. serializationObject.renderList.push(mesh.id);
  17920. }
  17921. return serializationObject;
  17922. };
  17923. var serializedGeometries = [];
  17924. var serializeGeometry = function (geometry, serializationGeometries) {
  17925. if (serializedGeometries[geometry.id]) {
  17926. return;
  17927. }
  17928. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  17929. serializationGeometries.boxes.push(serializeBox(geometry));
  17930. }
  17931. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  17932. serializationGeometries.spheres.push(serializeSphere(geometry));
  17933. }
  17934. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  17935. serializationGeometries.cylinders.push(serializeCylinder(geometry));
  17936. }
  17937. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  17938. serializationGeometries.toruses.push(serializeTorus(geometry));
  17939. }
  17940. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  17941. serializationGeometries.grounds.push(serializeGround(geometry));
  17942. }
  17943. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  17944. serializationGeometries.planes.push(serializePlane(geometry));
  17945. }
  17946. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  17947. serializationGeometries.torusKnots.push(serializeTorusKnot(geometry));
  17948. }
  17949. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  17950. throw new Error("Unknow primitive type");
  17951. }
  17952. else {
  17953. serializationGeometries.vertexData.push(serializeVertexData(geometry));
  17954. }
  17955. serializedGeometries[geometry.id] = true;
  17956. };
  17957. var serializeGeometryBase = function (geometry) {
  17958. var serializationObject = {};
  17959. serializationObject.id = geometry.id;
  17960. if (BABYLON.Tags.HasTags(geometry)) {
  17961. serializationObject.tags = BABYLON.Tags.GetTags(geometry);
  17962. }
  17963. return serializationObject;
  17964. };
  17965. var serializeVertexData = function (vertexData) {
  17966. var serializationObject = serializeGeometryBase(vertexData);
  17967. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  17968. serializationObject.positions = vertexData.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17969. }
  17970. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  17971. serializationObject.normals = vertexData.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  17972. }
  17973. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  17974. serializationObject.uvs = vertexData.getVerticesData(BABYLON.VertexBuffer.UVKind);
  17975. }
  17976. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  17977. serializationObject.uvs2 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  17978. }
  17979. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  17980. serializationObject.colors = vertexData.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  17981. }
  17982. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  17983. serializationObject.matricesIndices = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  17984. serializationObject.matricesIndices._isExpanded = true;
  17985. }
  17986. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  17987. serializationObject.matricesWeights = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  17988. }
  17989. serializationObject.indices = vertexData.getIndices();
  17990. return serializationObject;
  17991. };
  17992. var serializePrimitive = function (primitive) {
  17993. var serializationObject = serializeGeometryBase(primitive);
  17994. serializationObject.canBeRegenerated = primitive.canBeRegenerated();
  17995. return serializationObject;
  17996. };
  17997. var serializeBox = function (box) {
  17998. var serializationObject = serializePrimitive(box);
  17999. serializationObject.size = box.size;
  18000. return serializationObject;
  18001. };
  18002. var serializeSphere = function (sphere) {
  18003. var serializationObject = serializePrimitive(sphere);
  18004. serializationObject.segments = sphere.segments;
  18005. serializationObject.diameter = sphere.diameter;
  18006. return serializationObject;
  18007. };
  18008. var serializeCylinder = function (cylinder) {
  18009. var serializationObject = serializePrimitive(cylinder);
  18010. serializationObject.height = cylinder.height;
  18011. serializationObject.diameterTop = cylinder.diameterTop;
  18012. serializationObject.diameterBottom = cylinder.diameterBottom;
  18013. serializationObject.tessellation = cylinder.tessellation;
  18014. return serializationObject;
  18015. };
  18016. var serializeTorus = function (torus) {
  18017. var serializationObject = serializePrimitive(torus);
  18018. serializationObject.diameter = torus.diameter;
  18019. serializationObject.thickness = torus.thickness;
  18020. serializationObject.tessellation = torus.tessellation;
  18021. return serializationObject;
  18022. };
  18023. var serializeGround = function (ground) {
  18024. var serializationObject = serializePrimitive(ground);
  18025. serializationObject.width = ground.width;
  18026. serializationObject.height = ground.height;
  18027. serializationObject.subdivisions = ground.subdivisions;
  18028. return serializationObject;
  18029. };
  18030. var serializePlane = function (plane) {
  18031. var serializationObject = serializePrimitive(plane);
  18032. serializationObject.size = plane.size;
  18033. return serializationObject;
  18034. };
  18035. var serializeTorusKnot = function (torusKnot) {
  18036. var serializationObject = serializePrimitive(torusKnot);
  18037. serializationObject.radius = torusKnot.radius;
  18038. serializationObject.tube = torusKnot.tube;
  18039. serializationObject.radialSegments = torusKnot.radialSegments;
  18040. serializationObject.tubularSegments = torusKnot.tubularSegments;
  18041. serializationObject.p = torusKnot.p;
  18042. serializationObject.q = torusKnot.q;
  18043. return serializationObject;
  18044. };
  18045. var serializeMesh = function (mesh, serializationScene) {
  18046. var serializationObject = {};
  18047. serializationObject.name = mesh.name;
  18048. serializationObject.id = mesh.id;
  18049. if (BABYLON.Tags.HasTags(mesh)) {
  18050. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  18051. }
  18052. serializationObject.position = mesh.position.asArray();
  18053. if (mesh.rotationQuaternion) {
  18054. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  18055. }
  18056. else if (mesh.rotation) {
  18057. serializationObject.rotation = mesh.rotation.asArray();
  18058. }
  18059. serializationObject.scaling = mesh.scaling.asArray();
  18060. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  18061. serializationObject.isEnabled = mesh.isEnabled();
  18062. serializationObject.isVisible = mesh.isVisible;
  18063. serializationObject.infiniteDistance = mesh.infiniteDistance;
  18064. serializationObject.pickable = mesh.isPickable;
  18065. serializationObject.receiveShadows = mesh.receiveShadows;
  18066. serializationObject.billboardMode = mesh.billboardMode;
  18067. serializationObject.visibility = mesh.visibility;
  18068. serializationObject.checkCollisions = mesh.checkCollisions;
  18069. // Parent
  18070. if (mesh.parent) {
  18071. serializationObject.parentId = mesh.parent.id;
  18072. }
  18073. // Geometry
  18074. var geometry = mesh._geometry;
  18075. if (geometry) {
  18076. var geometryId = geometry.id;
  18077. serializationObject.geometryId = geometryId;
  18078. if (!mesh.getScene().getGeometryByID(geometryId)) {
  18079. // 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
  18080. serializeGeometry(geometry, serializationScene.geometries);
  18081. }
  18082. // SubMeshes
  18083. serializationObject.subMeshes = [];
  18084. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  18085. var subMesh = mesh.subMeshes[subIndex];
  18086. serializationObject.subMeshes.push({
  18087. materialIndex: subMesh.materialIndex,
  18088. verticesStart: subMesh.verticesStart,
  18089. verticesCount: subMesh.verticesCount,
  18090. indexStart: subMesh.indexStart,
  18091. indexCount: subMesh.indexCount
  18092. });
  18093. }
  18094. }
  18095. // Material
  18096. if (mesh.material) {
  18097. serializationObject.materialId = mesh.material.id;
  18098. }
  18099. else {
  18100. mesh.material = null;
  18101. }
  18102. // Skeleton
  18103. if (mesh.skeleton) {
  18104. serializationObject.skeletonId = mesh.skeleton.id;
  18105. }
  18106. // Physics
  18107. if (mesh.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  18108. serializationObject.physicsMass = mesh.getPhysicsMass();
  18109. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  18110. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  18111. switch (mesh.getPhysicsImpostor()) {
  18112. case BABYLON.PhysicsEngine.BoxImpostor:
  18113. serializationObject.physicsImpostor = 1;
  18114. break;
  18115. case BABYLON.PhysicsEngine.SphereImpostor:
  18116. serializationObject.physicsImpostor = 2;
  18117. break;
  18118. }
  18119. }
  18120. // Instances
  18121. serializationObject.instances = [];
  18122. for (var index = 0; index < mesh.instances.length; index++) {
  18123. var instance = mesh.instances[index];
  18124. var serializationInstance = {
  18125. name: instance.name,
  18126. position: instance.position,
  18127. rotation: instance.rotation,
  18128. rotationQuaternion: instance.rotationQuaternion,
  18129. scaling: instance.scaling
  18130. };
  18131. serializationObject.instances.push(serializationInstance);
  18132. // Animations
  18133. appendAnimations(instance, serializationInstance);
  18134. }
  18135. // Animations
  18136. appendAnimations(mesh, serializationObject);
  18137. // Layer mask
  18138. serializationObject.layerMask = mesh.layerMask;
  18139. return serializationObject;
  18140. };
  18141. var SceneSerializer = (function () {
  18142. function SceneSerializer() {
  18143. }
  18144. SceneSerializer.Serialize = function (scene) {
  18145. var serializationObject = {};
  18146. // Scene
  18147. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  18148. serializationObject.autoClear = scene.autoClear;
  18149. serializationObject.clearColor = scene.clearColor.asArray();
  18150. serializationObject.ambientColor = scene.ambientColor.asArray();
  18151. serializationObject.gravity = scene.gravity.asArray();
  18152. // Fog
  18153. if (scene.fogMode && scene.fogMode !== 0) {
  18154. serializationObject.fogMode = scene.fogMode;
  18155. serializationObject.fogColor = scene.fogColor.asArray();
  18156. serializationObject.fogStart = scene.fogStart;
  18157. serializationObject.fogEnd = scene.fogEnd;
  18158. serializationObject.fogDensity = scene.fogDensity;
  18159. }
  18160. // Lights
  18161. serializationObject.lights = [];
  18162. for (var index = 0; index < scene.lights.length; index++) {
  18163. var light = scene.lights[index];
  18164. serializationObject.lights.push(serializeLight(light));
  18165. }
  18166. // Cameras
  18167. serializationObject.cameras = [];
  18168. for (index = 0; index < scene.cameras.length; index++) {
  18169. var camera = scene.cameras[index];
  18170. if (camera instanceof BABYLON.FreeCamera) {
  18171. serializationObject.cameras.push(serializeCamera(camera));
  18172. }
  18173. }
  18174. if (scene.activeCamera) {
  18175. serializationObject.activeCameraID = scene.activeCamera.id;
  18176. }
  18177. // Materials
  18178. serializationObject.materials = [];
  18179. serializationObject.multiMaterials = [];
  18180. for (index = 0; index < scene.materials.length; index++) {
  18181. var material = scene.materials[index];
  18182. if (material instanceof BABYLON.StandardMaterial) {
  18183. serializationObject.materials.push(serializeMaterial(material));
  18184. }
  18185. else if (material instanceof BABYLON.MultiMaterial) {
  18186. serializationObject.multiMaterials.push(serializeMultiMaterial(material));
  18187. }
  18188. }
  18189. // Skeletons
  18190. serializationObject.skeletons = [];
  18191. for (index = 0; index < scene.skeletons.length; index++) {
  18192. serializationObject.skeletons.push(serializeSkeleton(scene.skeletons[index]));
  18193. }
  18194. // Geometries
  18195. serializationObject.geometries = {};
  18196. serializationObject.geometries.boxes = [];
  18197. serializationObject.geometries.spheres = [];
  18198. serializationObject.geometries.cylinders = [];
  18199. serializationObject.geometries.toruses = [];
  18200. serializationObject.geometries.grounds = [];
  18201. serializationObject.geometries.planes = [];
  18202. serializationObject.geometries.torusKnots = [];
  18203. serializationObject.geometries.vertexData = [];
  18204. serializedGeometries = [];
  18205. var geometries = scene.getGeometries();
  18206. for (var index = 0; index < geometries.length; index++) {
  18207. var geometry = geometries[index];
  18208. if (geometry.isReady()) {
  18209. serializeGeometry(geometry, serializationObject.geometries);
  18210. }
  18211. }
  18212. // Meshes
  18213. serializationObject.meshes = [];
  18214. for (index = 0; index < scene.meshes.length; index++) {
  18215. var abstractMesh = scene.meshes[index];
  18216. if (abstractMesh instanceof BABYLON.Mesh) {
  18217. var mesh = abstractMesh;
  18218. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  18219. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  18220. }
  18221. }
  18222. }
  18223. // Particles Systems
  18224. serializationObject.particleSystems = [];
  18225. for (index = 0; index < scene.particleSystems.length; index++) {
  18226. serializationObject.particleSystems.push(serializeParticleSystem(scene.particleSystems[index]));
  18227. }
  18228. // Lens flares
  18229. serializationObject.lensFlareSystems = [];
  18230. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  18231. serializationObject.lensFlareSystems.push(serializeLensFlareSystem(scene.lensFlareSystems[index]));
  18232. }
  18233. // Shadows
  18234. serializationObject.shadowGenerators = [];
  18235. for (index = 0; index < scene.lights.length; index++) {
  18236. light = scene.lights[index];
  18237. if (light.getShadowGenerator()) {
  18238. serializationObject.shadowGenerators.push(serializeShadowGenerator(light));
  18239. }
  18240. }
  18241. return serializationObject;
  18242. };
  18243. return SceneSerializer;
  18244. })();
  18245. BABYLON.SceneSerializer = SceneSerializer;
  18246. })(BABYLON || (BABYLON = {}));
  18247. //# sourceMappingURL=babylon.sceneSerializer.js.mapvar BABYLON;
  18248. (function (BABYLON) {
  18249. var SceneLoader = (function () {
  18250. function SceneLoader() {
  18251. }
  18252. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  18253. get: function () {
  18254. return SceneLoader._ForceFullSceneLoadingForIncremental;
  18255. },
  18256. set: function (value) {
  18257. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  18258. },
  18259. enumerable: true,
  18260. configurable: true
  18261. });
  18262. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  18263. get: function () {
  18264. return SceneLoader._ShowLoadingScreen;
  18265. },
  18266. set: function (value) {
  18267. SceneLoader._ShowLoadingScreen = value;
  18268. },
  18269. enumerable: true,
  18270. configurable: true
  18271. });
  18272. SceneLoader._getPluginForFilename = function (sceneFilename) {
  18273. var dotPosition = sceneFilename.lastIndexOf(".");
  18274. var queryStringPosition = sceneFilename.indexOf("?");
  18275. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  18276. for (var index = 0; index < this._registeredPlugins.length; index++) {
  18277. var plugin = this._registeredPlugins[index];
  18278. if (plugin.extensions.indexOf(extension) !== -1) {
  18279. return plugin;
  18280. }
  18281. }
  18282. return this._registeredPlugins[this._registeredPlugins.length - 1];
  18283. };
  18284. // Public functions
  18285. SceneLoader.RegisterPlugin = function (plugin) {
  18286. plugin.extensions = plugin.extensions.toLowerCase();
  18287. SceneLoader._registeredPlugins.push(plugin);
  18288. };
  18289. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  18290. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  18291. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  18292. return;
  18293. }
  18294. var manifestChecked = function (success) {
  18295. scene.database = database;
  18296. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  18297. var importMeshFromData = function (data) {
  18298. var meshes = [];
  18299. var particleSystems = [];
  18300. var skeletons = [];
  18301. try {
  18302. if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  18303. if (onerror) {
  18304. onerror(scene, 'unable to load the scene');
  18305. }
  18306. return;
  18307. }
  18308. }
  18309. catch (e) {
  18310. if (onerror) {
  18311. onerror(scene, e);
  18312. }
  18313. return;
  18314. }
  18315. if (onsuccess) {
  18316. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  18317. onsuccess(meshes, particleSystems, skeletons);
  18318. }
  18319. };
  18320. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  18321. // Direct load
  18322. importMeshFromData(sceneFilename.substr(5));
  18323. return;
  18324. }
  18325. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  18326. importMeshFromData(data);
  18327. }, progressCallBack, database);
  18328. };
  18329. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  18330. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  18331. };
  18332. /**
  18333. * Load a scene
  18334. * @param rootUrl a string that defines the root url for scene and resources
  18335. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  18336. * @param engine is the instance of BABYLON.Engine to use to create the scene
  18337. */
  18338. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  18339. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  18340. };
  18341. /**
  18342. * Append a scene
  18343. * @param rootUrl a string that defines the root url for scene and resources
  18344. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  18345. * @param scene is the instance of BABYLON.Scene to append to
  18346. */
  18347. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  18348. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  18349. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  18350. return;
  18351. }
  18352. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  18353. var database;
  18354. if (SceneLoader.ShowLoadingScreen) {
  18355. scene.getEngine().displayLoadingUI();
  18356. }
  18357. var loadSceneFromData = function (data) {
  18358. scene.database = database;
  18359. if (!plugin.load(scene, data, rootUrl)) {
  18360. if (onerror) {
  18361. onerror(scene);
  18362. }
  18363. scene.getEngine().hideLoadingUI();
  18364. return;
  18365. }
  18366. if (onsuccess) {
  18367. onsuccess(scene);
  18368. }
  18369. if (SceneLoader.ShowLoadingScreen) {
  18370. scene.executeWhenReady(function () {
  18371. scene.getEngine().hideLoadingUI();
  18372. });
  18373. }
  18374. };
  18375. var manifestChecked = function (success) {
  18376. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  18377. };
  18378. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  18379. // Direct load
  18380. loadSceneFromData(sceneFilename.substr(5));
  18381. return;
  18382. }
  18383. if (rootUrl.indexOf("file:") === -1) {
  18384. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  18385. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  18386. }
  18387. else {
  18388. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  18389. }
  18390. };
  18391. // Flags
  18392. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  18393. SceneLoader._ShowLoadingScreen = true;
  18394. // Members
  18395. SceneLoader._registeredPlugins = new Array();
  18396. return SceneLoader;
  18397. })();
  18398. BABYLON.SceneLoader = SceneLoader;
  18399. ;
  18400. })(BABYLON || (BABYLON = {}));
  18401. //# sourceMappingURL=babylon.sceneLoader.js.mapvar BABYLON;
  18402. (function (BABYLON) {
  18403. var Internals;
  18404. (function (Internals) {
  18405. var checkColors4 = function (colors, count) {
  18406. // Check if color3 was used
  18407. if (colors.length === count * 3) {
  18408. var colors4 = [];
  18409. for (var index = 0; index < colors.length; index += 3) {
  18410. var newIndex = (index / 3) * 4;
  18411. colors4[newIndex] = colors[index];
  18412. colors4[newIndex + 1] = colors[index + 1];
  18413. colors4[newIndex + 2] = colors[index + 2];
  18414. colors4[newIndex + 3] = 1.0;
  18415. }
  18416. return colors4;
  18417. }
  18418. return colors;
  18419. };
  18420. var loadCubeTexture = function (rootUrl, parsedTexture, scene) {
  18421. var texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene);
  18422. texture.name = parsedTexture.name;
  18423. texture.hasAlpha = parsedTexture.hasAlpha;
  18424. texture.level = parsedTexture.level;
  18425. texture.coordinatesMode = parsedTexture.coordinatesMode;
  18426. return texture;
  18427. };
  18428. var loadTexture = function (rootUrl, parsedTexture, scene) {
  18429. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  18430. return null;
  18431. }
  18432. if (parsedTexture.isCube) {
  18433. return loadCubeTexture(rootUrl, parsedTexture, scene);
  18434. }
  18435. var texture;
  18436. if (parsedTexture.mirrorPlane) {
  18437. texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  18438. texture._waitingRenderList = parsedTexture.renderList;
  18439. texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  18440. }
  18441. else if (parsedTexture.isRenderTarget) {
  18442. texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  18443. texture._waitingRenderList = parsedTexture.renderList;
  18444. }
  18445. else {
  18446. texture = new BABYLON.Texture(rootUrl + parsedTexture.name, scene);
  18447. }
  18448. texture.name = parsedTexture.name;
  18449. texture.hasAlpha = parsedTexture.hasAlpha;
  18450. texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
  18451. texture.level = parsedTexture.level;
  18452. texture.coordinatesIndex = parsedTexture.coordinatesIndex;
  18453. texture.coordinatesMode = parsedTexture.coordinatesMode;
  18454. texture.uOffset = parsedTexture.uOffset;
  18455. texture.vOffset = parsedTexture.vOffset;
  18456. texture.uScale = parsedTexture.uScale;
  18457. texture.vScale = parsedTexture.vScale;
  18458. texture.uAng = parsedTexture.uAng;
  18459. texture.vAng = parsedTexture.vAng;
  18460. texture.wAng = parsedTexture.wAng;
  18461. texture.wrapU = parsedTexture.wrapU;
  18462. texture.wrapV = parsedTexture.wrapV;
  18463. // Animations
  18464. if (parsedTexture.animations) {
  18465. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  18466. var parsedAnimation = parsedTexture.animations[animationIndex];
  18467. texture.animations.push(parseAnimation(parsedAnimation));
  18468. }
  18469. }
  18470. return texture;
  18471. };
  18472. var parseSkeleton = function (parsedSkeleton, scene) {
  18473. var skeleton = new BABYLON.Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  18474. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  18475. var parsedBone = parsedSkeleton.bones[index];
  18476. var parentBone = null;
  18477. if (parsedBone.parentBoneIndex > -1) {
  18478. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  18479. }
  18480. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix));
  18481. if (parsedBone.animation) {
  18482. bone.animations.push(parseAnimation(parsedBone.animation));
  18483. }
  18484. }
  18485. return skeleton;
  18486. };
  18487. var parseFresnelParameters = function (parsedFresnelParameters) {
  18488. var fresnelParameters = new BABYLON.FresnelParameters();
  18489. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  18490. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  18491. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  18492. fresnelParameters.bias = parsedFresnelParameters.bias;
  18493. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  18494. return fresnelParameters;
  18495. };
  18496. var parseMaterial = function (parsedMaterial, scene, rootUrl) {
  18497. var material;
  18498. material = new BABYLON.StandardMaterial(parsedMaterial.name, scene);
  18499. material.ambientColor = BABYLON.Color3.FromArray(parsedMaterial.ambient);
  18500. material.diffuseColor = BABYLON.Color3.FromArray(parsedMaterial.diffuse);
  18501. material.specularColor = BABYLON.Color3.FromArray(parsedMaterial.specular);
  18502. material.specularPower = parsedMaterial.specularPower;
  18503. material.emissiveColor = BABYLON.Color3.FromArray(parsedMaterial.emissive);
  18504. material.alpha = parsedMaterial.alpha;
  18505. material.id = parsedMaterial.id;
  18506. BABYLON.Tags.AddTagsTo(material, parsedMaterial.tags);
  18507. material.backFaceCulling = parsedMaterial.backFaceCulling;
  18508. material.wireframe = parsedMaterial.wireframe;
  18509. if (parsedMaterial.diffuseTexture) {
  18510. material.diffuseTexture = loadTexture(rootUrl, parsedMaterial.diffuseTexture, scene);
  18511. }
  18512. if (parsedMaterial.diffuseFresnelParameters) {
  18513. material.diffuseFresnelParameters = parseFresnelParameters(parsedMaterial.diffuseFresnelParameters);
  18514. }
  18515. if (parsedMaterial.ambientTexture) {
  18516. material.ambientTexture = loadTexture(rootUrl, parsedMaterial.ambientTexture, scene);
  18517. }
  18518. if (parsedMaterial.opacityTexture) {
  18519. material.opacityTexture = loadTexture(rootUrl, parsedMaterial.opacityTexture, scene);
  18520. }
  18521. if (parsedMaterial.opacityFresnelParameters) {
  18522. material.opacityFresnelParameters = parseFresnelParameters(parsedMaterial.opacityFresnelParameters);
  18523. }
  18524. if (parsedMaterial.reflectionTexture) {
  18525. material.reflectionTexture = loadTexture(rootUrl, parsedMaterial.reflectionTexture, scene);
  18526. }
  18527. if (parsedMaterial.reflectionFresnelParameters) {
  18528. material.reflectionFresnelParameters = parseFresnelParameters(parsedMaterial.reflectionFresnelParameters);
  18529. }
  18530. if (parsedMaterial.emissiveTexture) {
  18531. material.emissiveTexture = loadTexture(rootUrl, parsedMaterial.emissiveTexture, scene);
  18532. }
  18533. if (parsedMaterial.emissiveFresnelParameters) {
  18534. material.emissiveFresnelParameters = parseFresnelParameters(parsedMaterial.emissiveFresnelParameters);
  18535. }
  18536. if (parsedMaterial.specularTexture) {
  18537. material.specularTexture = loadTexture(rootUrl, parsedMaterial.specularTexture, scene);
  18538. }
  18539. if (parsedMaterial.bumpTexture) {
  18540. material.bumpTexture = loadTexture(rootUrl, parsedMaterial.bumpTexture, scene);
  18541. }
  18542. return material;
  18543. };
  18544. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  18545. for (var index = 0; index < parsedData.materials.length; index++) {
  18546. var parsedMaterial = parsedData.materials[index];
  18547. if (parsedMaterial.id === id) {
  18548. return parseMaterial(parsedMaterial, scene, rootUrl);
  18549. }
  18550. }
  18551. return null;
  18552. };
  18553. var parseMultiMaterial = function (parsedMultiMaterial, scene) {
  18554. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  18555. multiMaterial.id = parsedMultiMaterial.id;
  18556. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  18557. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  18558. var subMatId = parsedMultiMaterial.materials[matIndex];
  18559. if (subMatId) {
  18560. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  18561. }
  18562. else {
  18563. multiMaterial.subMaterials.push(null);
  18564. }
  18565. }
  18566. return multiMaterial;
  18567. };
  18568. var parseLensFlareSystem = function (parsedLensFlareSystem, scene, rootUrl) {
  18569. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  18570. var lensFlareSystem = new BABYLON.LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  18571. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  18572. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  18573. var parsedFlare = parsedLensFlareSystem.flares[index];
  18574. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  18575. }
  18576. return lensFlareSystem;
  18577. };
  18578. var parseParticleSystem = function (parsedParticleSystem, scene, rootUrl) {
  18579. var emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  18580. var particleSystem = new BABYLON.ParticleSystem("particles#" + emitter.name, parsedParticleSystem.capacity, scene);
  18581. if (parsedParticleSystem.textureName) {
  18582. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  18583. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  18584. }
  18585. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  18586. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  18587. particleSystem.minSize = parsedParticleSystem.minSize;
  18588. particleSystem.maxSize = parsedParticleSystem.maxSize;
  18589. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  18590. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  18591. particleSystem.emitter = emitter;
  18592. particleSystem.emitRate = parsedParticleSystem.emitRate;
  18593. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  18594. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  18595. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  18596. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  18597. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  18598. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  18599. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  18600. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  18601. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  18602. particleSystem.targetStopDuration = parsedParticleSystem.targetStopFrame;
  18603. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  18604. particleSystem.blendMode = parsedParticleSystem.blendMode;
  18605. particleSystem.start();
  18606. return particleSystem;
  18607. };
  18608. var parseShadowGenerator = function (parsedShadowGenerator, scene) {
  18609. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  18610. var shadowGenerator = new BABYLON.ShadowGenerator(parsedShadowGenerator.mapSize, light);
  18611. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  18612. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  18613. shadowGenerator.getShadowMap().renderList.push(mesh);
  18614. }
  18615. if (parsedShadowGenerator.usePoissonSampling) {
  18616. shadowGenerator.usePoissonSampling = true;
  18617. }
  18618. else {
  18619. shadowGenerator.useVarianceShadowMap = parsedShadowGenerator.useVarianceShadowMap;
  18620. }
  18621. return shadowGenerator;
  18622. };
  18623. var parseAnimation = function (parsedAnimation) {
  18624. var animation = new BABYLON.Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  18625. var dataType = parsedAnimation.dataType;
  18626. var keys = [];
  18627. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  18628. var key = parsedAnimation.keys[index];
  18629. var data;
  18630. switch (dataType) {
  18631. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  18632. data = key.values[0];
  18633. break;
  18634. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  18635. data = BABYLON.Quaternion.FromArray(key.values);
  18636. break;
  18637. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  18638. data = BABYLON.Matrix.FromArray(key.values);
  18639. break;
  18640. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  18641. default:
  18642. data = BABYLON.Vector3.FromArray(key.values);
  18643. break;
  18644. }
  18645. keys.push({
  18646. frame: key.frame,
  18647. value: data
  18648. });
  18649. }
  18650. animation.setKeys(keys);
  18651. return animation;
  18652. };
  18653. var parseLight = function (parsedLight, scene) {
  18654. var light;
  18655. switch (parsedLight.type) {
  18656. case 0:
  18657. light = new BABYLON.PointLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), scene);
  18658. break;
  18659. case 1:
  18660. light = new BABYLON.DirectionalLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  18661. light.position = BABYLON.Vector3.FromArray(parsedLight.position);
  18662. break;
  18663. case 2:
  18664. light = new BABYLON.SpotLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), BABYLON.Vector3.FromArray(parsedLight.direction), parsedLight.angle, parsedLight.exponent, scene);
  18665. break;
  18666. case 3:
  18667. light = new BABYLON.HemisphericLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  18668. light.groundColor = BABYLON.Color3.FromArray(parsedLight.groundColor);
  18669. break;
  18670. }
  18671. light.id = parsedLight.id;
  18672. BABYLON.Tags.AddTagsTo(light, parsedLight.tags);
  18673. if (parsedLight.intensity !== undefined) {
  18674. light.intensity = parsedLight.intensity;
  18675. }
  18676. if (parsedLight.range) {
  18677. light.range = parsedLight.range;
  18678. }
  18679. light.diffuse = BABYLON.Color3.FromArray(parsedLight.diffuse);
  18680. light.specular = BABYLON.Color3.FromArray(parsedLight.specular);
  18681. if (parsedLight.excludedMeshesIds) {
  18682. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  18683. }
  18684. // Parent
  18685. if (parsedLight.parentId) {
  18686. light._waitingParentId = parsedLight.parentId;
  18687. }
  18688. if (parsedLight.includedOnlyMeshesIds) {
  18689. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  18690. }
  18691. // Animations
  18692. if (parsedLight.animations) {
  18693. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  18694. var parsedAnimation = parsedLight.animations[animationIndex];
  18695. light.animations.push(parseAnimation(parsedAnimation));
  18696. }
  18697. }
  18698. if (parsedLight.autoAnimate) {
  18699. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, 1.0);
  18700. }
  18701. };
  18702. var parseCamera = function (parsedCamera, scene) {
  18703. var camera;
  18704. var position = BABYLON.Vector3.FromArray(parsedCamera.position);
  18705. var lockedTargetMesh = (parsedCamera.lockedTargetId) ? scene.getLastMeshByID(parsedCamera.lockedTargetId) : null;
  18706. if (parsedCamera.type === "AnaglyphArcRotateCamera" || parsedCamera.type === "ArcRotateCamera") {
  18707. var alpha = parsedCamera.alpha;
  18708. var beta = parsedCamera.beta;
  18709. var radius = parsedCamera.radius;
  18710. if (parsedCamera.type === "AnaglyphArcRotateCamera") {
  18711. var eye_space = parsedCamera.eye_space;
  18712. camera = new BABYLON.AnaglyphArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, eye_space, scene);
  18713. }
  18714. else {
  18715. camera = new BABYLON.ArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, scene);
  18716. }
  18717. }
  18718. else if (parsedCamera.type === "AnaglyphFreeCamera") {
  18719. eye_space = parsedCamera.eye_space;
  18720. camera = new BABYLON.AnaglyphFreeCamera(parsedCamera.name, position, eye_space, scene);
  18721. }
  18722. else if (parsedCamera.type === "DeviceOrientationCamera") {
  18723. camera = new BABYLON.DeviceOrientationCamera(parsedCamera.name, position, scene);
  18724. }
  18725. else if (parsedCamera.type === "FollowCamera") {
  18726. camera = new BABYLON.FollowCamera(parsedCamera.name, position, scene);
  18727. camera.heightOffset = parsedCamera.heightOffset;
  18728. camera.radius = parsedCamera.radius;
  18729. camera.rotationOffset = parsedCamera.rotationOffset;
  18730. if (lockedTargetMesh)
  18731. camera.target = lockedTargetMesh;
  18732. }
  18733. else if (parsedCamera.type === "GamepadCamera") {
  18734. camera = new BABYLON.GamepadCamera(parsedCamera.name, position, scene);
  18735. }
  18736. else if (parsedCamera.type === "OculusCamera") {
  18737. camera = new BABYLON.OculusCamera(parsedCamera.name, position, scene);
  18738. }
  18739. else if (parsedCamera.type === "OculusGamepadCamera") {
  18740. camera = new BABYLON.OculusGamepadCamera(parsedCamera.name, position, scene);
  18741. }
  18742. else if (parsedCamera.type === "TouchCamera") {
  18743. camera = new BABYLON.TouchCamera(parsedCamera.name, position, scene);
  18744. }
  18745. else if (parsedCamera.type === "VirtualJoysticksCamera") {
  18746. camera = new BABYLON.VirtualJoysticksCamera(parsedCamera.name, position, scene);
  18747. }
  18748. else if (parsedCamera.type === "WebVRCamera") {
  18749. camera = new BABYLON.WebVRCamera(parsedCamera.name, position, scene);
  18750. }
  18751. else if (parsedCamera.type === "VRDeviceOrientationCamera") {
  18752. camera = new BABYLON.VRDeviceOrientationCamera(parsedCamera.name, position, scene);
  18753. }
  18754. else {
  18755. // Free Camera is the default value
  18756. camera = new BABYLON.FreeCamera(parsedCamera.name, position, scene);
  18757. }
  18758. // Test for lockedTargetMesh & FreeCamera outside of if-else-if nest, since things like GamepadCamera extend FreeCamera
  18759. if (lockedTargetMesh && camera instanceof BABYLON.FreeCamera) {
  18760. camera.lockedTarget = lockedTargetMesh;
  18761. }
  18762. camera.id = parsedCamera.id;
  18763. BABYLON.Tags.AddTagsTo(camera, parsedCamera.tags);
  18764. // Parent
  18765. if (parsedCamera.parentId) {
  18766. camera._waitingParentId = parsedCamera.parentId;
  18767. }
  18768. // Target
  18769. if (parsedCamera.target) {
  18770. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  18771. }
  18772. else {
  18773. camera.rotation = BABYLON.Vector3.FromArray(parsedCamera.rotation);
  18774. }
  18775. camera.fov = parsedCamera.fov;
  18776. camera.minZ = parsedCamera.minZ;
  18777. camera.maxZ = parsedCamera.maxZ;
  18778. camera.speed = parsedCamera.speed;
  18779. camera.inertia = parsedCamera.inertia;
  18780. camera.checkCollisions = parsedCamera.checkCollisions;
  18781. camera.applyGravity = parsedCamera.applyGravity;
  18782. if (parsedCamera.ellipsoid) {
  18783. camera.ellipsoid = BABYLON.Vector3.FromArray(parsedCamera.ellipsoid);
  18784. }
  18785. // Animations
  18786. if (parsedCamera.animations) {
  18787. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  18788. var parsedAnimation = parsedCamera.animations[animationIndex];
  18789. camera.animations.push(parseAnimation(parsedAnimation));
  18790. }
  18791. }
  18792. if (parsedCamera.autoAnimate) {
  18793. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, 1.0);
  18794. }
  18795. // Layer Mask
  18796. if (parsedCamera.layerMask && (!isNaN(parsedCamera.layerMask))) {
  18797. camera.layerMask = Math.abs(parseInt(parsedCamera.layerMask));
  18798. }
  18799. else {
  18800. camera.layerMask = 0xFFFFFFFF;
  18801. }
  18802. return camera;
  18803. };
  18804. var parseGeometry = function (parsedGeometry, scene) {
  18805. var id = parsedGeometry.id;
  18806. return scene.getGeometryByID(id);
  18807. };
  18808. var parseBox = function (parsedBox, scene) {
  18809. if (parseGeometry(parsedBox, scene)) {
  18810. return null; // null since geometry could be something else than a box...
  18811. }
  18812. var box = new BABYLON.Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  18813. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  18814. scene.pushGeometry(box, true);
  18815. return box;
  18816. };
  18817. var parseSphere = function (parsedSphere, scene) {
  18818. if (parseGeometry(parsedSphere, scene)) {
  18819. return null; // null since geometry could be something else than a sphere...
  18820. }
  18821. var sphere = new BABYLON.Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  18822. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  18823. scene.pushGeometry(sphere, true);
  18824. return sphere;
  18825. };
  18826. var parseCylinder = function (parsedCylinder, scene) {
  18827. if (parseGeometry(parsedCylinder, scene)) {
  18828. return null; // null since geometry could be something else than a cylinder...
  18829. }
  18830. var cylinder = new BABYLON.Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  18831. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  18832. scene.pushGeometry(cylinder, true);
  18833. return cylinder;
  18834. };
  18835. var parseTorus = function (parsedTorus, scene) {
  18836. if (parseGeometry(parsedTorus, scene)) {
  18837. return null; // null since geometry could be something else than a torus...
  18838. }
  18839. var torus = new BABYLON.Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  18840. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  18841. scene.pushGeometry(torus, true);
  18842. return torus;
  18843. };
  18844. var parseGround = function (parsedGround, scene) {
  18845. if (parseGeometry(parsedGround, scene)) {
  18846. return null; // null since geometry could be something else than a ground...
  18847. }
  18848. var ground = new BABYLON.Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  18849. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  18850. scene.pushGeometry(ground, true);
  18851. return ground;
  18852. };
  18853. var parsePlane = function (parsedPlane, scene) {
  18854. if (parseGeometry(parsedPlane, scene)) {
  18855. return null; // null since geometry could be something else than a plane...
  18856. }
  18857. var plane = new BABYLON.Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  18858. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  18859. scene.pushGeometry(plane, true);
  18860. return plane;
  18861. };
  18862. var parseTorusKnot = function (parsedTorusKnot, scene) {
  18863. if (parseGeometry(parsedTorusKnot, scene)) {
  18864. return null; // null since geometry could be something else than a torusKnot...
  18865. }
  18866. 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);
  18867. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  18868. scene.pushGeometry(torusKnot, true);
  18869. return torusKnot;
  18870. };
  18871. var parseVertexData = function (parsedVertexData, scene, rootUrl) {
  18872. if (parseGeometry(parsedVertexData, scene)) {
  18873. return null; // null since geometry could be a primitive
  18874. }
  18875. var geometry = new BABYLON.Geometry(parsedVertexData.id, scene);
  18876. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  18877. if (parsedVertexData.delayLoadingFile) {
  18878. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  18879. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  18880. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  18881. geometry._delayInfo = [];
  18882. if (parsedVertexData.hasUVs) {
  18883. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  18884. }
  18885. if (parsedVertexData.hasUVs2) {
  18886. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  18887. }
  18888. if (parsedVertexData.hasColors) {
  18889. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  18890. }
  18891. if (parsedVertexData.hasMatricesIndices) {
  18892. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  18893. }
  18894. if (parsedVertexData.hasMatricesWeights) {
  18895. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  18896. }
  18897. geometry._delayLoadingFunction = importVertexData;
  18898. }
  18899. else {
  18900. importVertexData(parsedVertexData, geometry);
  18901. }
  18902. scene.pushGeometry(geometry, true);
  18903. return geometry;
  18904. };
  18905. var parseMesh = function (parsedMesh, scene, rootUrl) {
  18906. var mesh = new BABYLON.Mesh(parsedMesh.name, scene);
  18907. mesh.id = parsedMesh.id;
  18908. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  18909. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  18910. if (parsedMesh.rotationQuaternion) {
  18911. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  18912. }
  18913. else if (parsedMesh.rotation) {
  18914. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  18915. }
  18916. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  18917. if (parsedMesh.localMatrix) {
  18918. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  18919. }
  18920. else if (parsedMesh.pivotMatrix) {
  18921. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  18922. }
  18923. mesh.setEnabled(parsedMesh.isEnabled);
  18924. mesh.isVisible = parsedMesh.isVisible;
  18925. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  18926. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  18927. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  18928. if (parsedMesh.applyFog !== undefined) {
  18929. mesh.applyFog = parsedMesh.applyFog;
  18930. }
  18931. if (parsedMesh.pickable !== undefined) {
  18932. mesh.isPickable = parsedMesh.pickable;
  18933. }
  18934. if (parsedMesh.alphaIndex !== undefined) {
  18935. mesh.alphaIndex = parsedMesh.alphaIndex;
  18936. }
  18937. mesh.receiveShadows = parsedMesh.receiveShadows;
  18938. mesh.billboardMode = parsedMesh.billboardMode;
  18939. if (parsedMesh.visibility !== undefined) {
  18940. mesh.visibility = parsedMesh.visibility;
  18941. }
  18942. mesh.checkCollisions = parsedMesh.checkCollisions;
  18943. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  18944. // Parent
  18945. if (parsedMesh.parentId) {
  18946. mesh._waitingParentId = parsedMesh.parentId;
  18947. }
  18948. // Actions
  18949. if (parsedMesh.actions !== undefined) {
  18950. mesh._waitingActions = parsedMesh.actions;
  18951. }
  18952. // Geometry
  18953. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  18954. if (parsedMesh.delayLoadingFile) {
  18955. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  18956. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  18957. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  18958. if (parsedMesh._binaryInfo) {
  18959. mesh._binaryInfo = parsedMesh._binaryInfo;
  18960. }
  18961. mesh._delayInfo = [];
  18962. if (parsedMesh.hasUVs) {
  18963. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  18964. }
  18965. if (parsedMesh.hasUVs2) {
  18966. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  18967. }
  18968. if (parsedMesh.hasColors) {
  18969. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  18970. }
  18971. if (parsedMesh.hasMatricesIndices) {
  18972. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  18973. }
  18974. if (parsedMesh.hasMatricesWeights) {
  18975. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  18976. }
  18977. mesh._delayLoadingFunction = importGeometry;
  18978. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  18979. mesh._checkDelayState();
  18980. }
  18981. }
  18982. else {
  18983. importGeometry(parsedMesh, mesh);
  18984. }
  18985. // Material
  18986. if (parsedMesh.materialId) {
  18987. mesh.setMaterialByID(parsedMesh.materialId);
  18988. }
  18989. else {
  18990. mesh.material = null;
  18991. }
  18992. // Skeleton
  18993. if (parsedMesh.skeletonId > -1) {
  18994. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  18995. }
  18996. // Physics
  18997. if (parsedMesh.physicsImpostor) {
  18998. if (!scene.isPhysicsEnabled()) {
  18999. scene.enablePhysics();
  19000. }
  19001. mesh.setPhysicsState({ impostor: parsedMesh.physicsImpostor, mass: parsedMesh.physicsMass, friction: parsedMesh.physicsFriction, restitution: parsedMesh.physicsRestitution });
  19002. }
  19003. // Animations
  19004. if (parsedMesh.animations) {
  19005. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  19006. var parsedAnimation = parsedMesh.animations[animationIndex];
  19007. mesh.animations.push(parseAnimation(parsedAnimation));
  19008. }
  19009. }
  19010. if (parsedMesh.autoAnimate) {
  19011. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, 1.0);
  19012. }
  19013. // Layer Mask
  19014. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  19015. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  19016. }
  19017. else {
  19018. mesh.layerMask = 0xFFFFFFFF;
  19019. }
  19020. // Instances
  19021. if (parsedMesh.instances) {
  19022. for (var index = 0; index < parsedMesh.instances.length; index++) {
  19023. var parsedInstance = parsedMesh.instances[index];
  19024. var instance = mesh.createInstance(parsedInstance.name);
  19025. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  19026. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  19027. if (parsedInstance.rotationQuaternion) {
  19028. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  19029. }
  19030. else if (parsedInstance.rotation) {
  19031. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  19032. }
  19033. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  19034. instance.checkCollisions = mesh.checkCollisions;
  19035. if (parsedMesh.animations) {
  19036. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  19037. parsedAnimation = parsedMesh.animations[animationIndex];
  19038. instance.animations.push(parseAnimation(parsedAnimation));
  19039. }
  19040. }
  19041. }
  19042. }
  19043. return mesh;
  19044. };
  19045. var parseActions = function (parsedActions, object, scene) {
  19046. var actionManager = new BABYLON.ActionManager(scene);
  19047. if (object === null)
  19048. scene.actionManager = actionManager;
  19049. else
  19050. object.actionManager = actionManager;
  19051. // instanciate a new object
  19052. var instanciate = function (name, params) {
  19053. var newInstance = Object.create(BABYLON[name].prototype);
  19054. newInstance.constructor.apply(newInstance, params);
  19055. return newInstance;
  19056. };
  19057. var parseParameter = function (name, value, target, propertyPath) {
  19058. if (propertyPath === null) {
  19059. // String, boolean or float
  19060. var floatValue = parseFloat(value);
  19061. if (value === "true" || value === "false")
  19062. return value === "true";
  19063. else
  19064. return isNaN(floatValue) ? value : floatValue;
  19065. }
  19066. var effectiveTarget = propertyPath.split(".");
  19067. var values = value.split(",");
  19068. for (var i = 0; i < effectiveTarget.length; i++) {
  19069. target = target[effectiveTarget[i]];
  19070. }
  19071. // Return appropriate value with its type
  19072. if (target instanceof Boolean)
  19073. return values[0] === "true";
  19074. if (target instanceof String)
  19075. return values[0];
  19076. // Parameters with multiple values such as Vector3 etc.
  19077. var split = new Array();
  19078. for (var i = 0; i < values.length; i++)
  19079. split.push(parseFloat(values[i]));
  19080. if (target instanceof BABYLON.Vector3)
  19081. return BABYLON.Vector3.FromArray(split);
  19082. if (target instanceof BABYLON.Vector4)
  19083. return BABYLON.Vector4.FromArray(split);
  19084. if (target instanceof BABYLON.Color3)
  19085. return BABYLON.Color3.FromArray(split);
  19086. if (target instanceof BABYLON.Color4)
  19087. return BABYLON.Color4.FromArray(split);
  19088. return parseFloat(values[0]);
  19089. };
  19090. // traverse graph per trigger
  19091. var traverse = function (parsedAction, trigger, condition, action) {
  19092. if (parsedAction.detached)
  19093. return;
  19094. var parameters = new Array();
  19095. var target = null;
  19096. var propertyPath = null;
  19097. // Parameters
  19098. if (parsedAction.type === 2)
  19099. parameters.push(actionManager);
  19100. else
  19101. parameters.push(trigger);
  19102. for (var i = 0; i < parsedAction.properties.length; i++) {
  19103. var value = parsedAction.properties[i].value;
  19104. var name = parsedAction.properties[i].name;
  19105. if (name === "target")
  19106. value = target = scene.getNodeByName(value);
  19107. else if (name === "parent")
  19108. value = scene.getNodeByName(value);
  19109. else if (name === "sound")
  19110. value = scene.getSoundByName(value);
  19111. else if (name !== "propertyPath") {
  19112. if (parsedAction.type === 2 && name === "operator")
  19113. value = BABYLON.ValueCondition[value];
  19114. else
  19115. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  19116. }
  19117. else {
  19118. propertyPath = value;
  19119. }
  19120. parameters.push(value);
  19121. }
  19122. parameters.push(condition);
  19123. // If interpolate value action
  19124. if (parsedAction.name === "InterpolateValueAction") {
  19125. var param = parameters[parameters.length - 2];
  19126. parameters[parameters.length - 1] = param;
  19127. parameters[parameters.length - 2] = condition;
  19128. }
  19129. // Action or condition(s)
  19130. var newAction = instanciate(parsedAction.name, parameters);
  19131. if (newAction instanceof BABYLON.Condition) {
  19132. condition = newAction;
  19133. newAction = action;
  19134. }
  19135. else {
  19136. condition = null;
  19137. if (action)
  19138. action.then(newAction);
  19139. else
  19140. actionManager.registerAction(newAction);
  19141. }
  19142. for (var i = 0; i < parsedAction.children.length; i++)
  19143. traverse(parsedAction.children[i], trigger, condition, newAction);
  19144. };
  19145. for (var i = 0; i < parsedActions.children.length; i++) {
  19146. var triggerParams;
  19147. var trigger = parsedActions.children[i];
  19148. if (trigger.properties.length > 0) {
  19149. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: scene.getMeshByName(trigger.properties[0].value) };
  19150. }
  19151. else
  19152. triggerParams = BABYLON.ActionManager[trigger.name];
  19153. for (var j = 0; j < trigger.children.length; j++)
  19154. traverse(trigger.children[j], triggerParams, null, null);
  19155. }
  19156. };
  19157. var parseSound = function (parsedSound, scene, rootUrl) {
  19158. var soundName = parsedSound.name;
  19159. var soundUrl = rootUrl + soundName;
  19160. var options = {
  19161. autoplay: parsedSound.autoplay,
  19162. loop: parsedSound.loop,
  19163. volume: parsedSound.volume,
  19164. spatialSound: parsedSound.spatialSound,
  19165. maxDistance: parsedSound.maxDistance,
  19166. rolloffFactor: parsedSound.rolloffFactor,
  19167. refDistance: parsedSound.refDistance,
  19168. distanceModel: parsedSound.distanceModel,
  19169. panningModel: parsedSound.panningModel,
  19170. playbackRate: parsedSound.playbackRate
  19171. };
  19172. var newSound = new BABYLON.Sound(soundName, soundUrl, scene, function () {
  19173. scene._removePendingData(newSound);
  19174. }, options);
  19175. scene._addPendingData(newSound);
  19176. if (parsedSound.position) {
  19177. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  19178. newSound.setPosition(soundPosition);
  19179. }
  19180. if (parsedSound.isDirectional) {
  19181. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  19182. if (parsedSound.localDirectionToMesh) {
  19183. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  19184. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  19185. }
  19186. }
  19187. if (parsedSound.connectedMeshId) {
  19188. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  19189. if (connectedMesh) {
  19190. newSound.attachToMesh(connectedMesh);
  19191. }
  19192. }
  19193. };
  19194. var isDescendantOf = function (mesh, names, hierarchyIds) {
  19195. names = (names instanceof Array) ? names : [names];
  19196. for (var i in names) {
  19197. if (mesh.name === names[i]) {
  19198. hierarchyIds.push(mesh.id);
  19199. return true;
  19200. }
  19201. }
  19202. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  19203. hierarchyIds.push(mesh.id);
  19204. return true;
  19205. }
  19206. return false;
  19207. };
  19208. var importVertexData = function (parsedVertexData, geometry) {
  19209. var vertexData = new BABYLON.VertexData();
  19210. // positions
  19211. var positions = parsedVertexData.positions;
  19212. if (positions) {
  19213. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  19214. }
  19215. // normals
  19216. var normals = parsedVertexData.normals;
  19217. if (normals) {
  19218. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  19219. }
  19220. // uvs
  19221. var uvs = parsedVertexData.uvs;
  19222. if (uvs) {
  19223. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  19224. }
  19225. // uv2s
  19226. var uv2s = parsedVertexData.uv2s;
  19227. if (uv2s) {
  19228. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  19229. }
  19230. // colors
  19231. var colors = parsedVertexData.colors;
  19232. if (colors) {
  19233. vertexData.set(checkColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  19234. }
  19235. // matricesIndices
  19236. var matricesIndices = parsedVertexData.matricesIndices;
  19237. if (matricesIndices) {
  19238. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  19239. }
  19240. // matricesWeights
  19241. var matricesWeights = parsedVertexData.matricesWeights;
  19242. if (matricesWeights) {
  19243. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  19244. }
  19245. // indices
  19246. var indices = parsedVertexData.indices;
  19247. if (indices) {
  19248. vertexData.indices = indices;
  19249. }
  19250. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  19251. };
  19252. var importGeometry = function (parsedGeometry, mesh) {
  19253. var scene = mesh.getScene();
  19254. // Geometry
  19255. var geometryId = parsedGeometry.geometryId;
  19256. if (geometryId) {
  19257. var geometry = scene.getGeometryByID(geometryId);
  19258. if (geometry) {
  19259. geometry.applyToMesh(mesh);
  19260. }
  19261. }
  19262. else if (parsedGeometry instanceof ArrayBuffer) {
  19263. var binaryInfo = mesh._binaryInfo;
  19264. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  19265. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  19266. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  19267. }
  19268. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  19269. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  19270. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  19271. }
  19272. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  19273. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  19274. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  19275. }
  19276. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  19277. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  19278. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  19279. }
  19280. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  19281. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  19282. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false);
  19283. }
  19284. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  19285. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  19286. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  19287. }
  19288. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  19289. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  19290. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  19291. }
  19292. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  19293. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  19294. mesh.setIndices(indicesData);
  19295. }
  19296. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  19297. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  19298. mesh.subMeshes = [];
  19299. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  19300. var materialIndex = subMeshesData[(i * 5) + 0];
  19301. var verticesStart = subMeshesData[(i * 5) + 1];
  19302. var verticesCount = subMeshesData[(i * 5) + 2];
  19303. var indexStart = subMeshesData[(i * 5) + 3];
  19304. var indexCount = subMeshesData[(i * 5) + 4];
  19305. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  19306. }
  19307. }
  19308. }
  19309. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  19310. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  19311. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  19312. if (parsedGeometry.uvs) {
  19313. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  19314. }
  19315. if (parsedGeometry.uvs2) {
  19316. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  19317. }
  19318. if (parsedGeometry.colors) {
  19319. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, checkColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  19320. }
  19321. if (parsedGeometry.matricesIndices) {
  19322. if (!parsedGeometry.matricesIndices._isExpanded) {
  19323. var floatIndices = [];
  19324. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  19325. var matricesIndex = parsedGeometry.matricesIndices[i];
  19326. floatIndices.push(matricesIndex & 0x000000FF);
  19327. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  19328. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  19329. floatIndices.push(matricesIndex >> 24);
  19330. }
  19331. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  19332. }
  19333. else {
  19334. delete parsedGeometry.matricesIndices._isExpanded;
  19335. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  19336. }
  19337. }
  19338. if (parsedGeometry.matricesWeights) {
  19339. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  19340. }
  19341. mesh.setIndices(parsedGeometry.indices);
  19342. // SubMeshes
  19343. if (parsedGeometry.subMeshes) {
  19344. mesh.subMeshes = [];
  19345. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  19346. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  19347. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  19348. }
  19349. }
  19350. }
  19351. // Flat shading
  19352. if (mesh._shouldGenerateFlatShading) {
  19353. mesh.convertToFlatShadedMesh();
  19354. delete mesh._shouldGenerateFlatShading;
  19355. }
  19356. // Update
  19357. mesh.computeWorldMatrix(true);
  19358. // Octree
  19359. if (scene._selectionOctree) {
  19360. scene._selectionOctree.addMesh(mesh);
  19361. }
  19362. };
  19363. BABYLON.SceneLoader.RegisterPlugin({
  19364. extensions: ".babylon",
  19365. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  19366. var parsedData = JSON.parse(data);
  19367. var loadedSkeletonsIds = [];
  19368. var loadedMaterialsIds = [];
  19369. var hierarchyIds = [];
  19370. for (var index = 0; index < parsedData.meshes.length; index++) {
  19371. var parsedMesh = parsedData.meshes[index];
  19372. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  19373. if (meshesNames instanceof Array) {
  19374. // Remove found mesh name from list.
  19375. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  19376. }
  19377. // Material ?
  19378. if (parsedMesh.materialId) {
  19379. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  19380. if (!materialFound) {
  19381. for (var multimatIndex = 0; multimatIndex < parsedData.multiMaterials.length; multimatIndex++) {
  19382. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  19383. if (parsedMultiMaterial.id == parsedMesh.materialId) {
  19384. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  19385. var subMatId = parsedMultiMaterial.materials[matIndex];
  19386. loadedMaterialsIds.push(subMatId);
  19387. parseMaterialById(subMatId, parsedData, scene, rootUrl);
  19388. }
  19389. loadedMaterialsIds.push(parsedMultiMaterial.id);
  19390. parseMultiMaterial(parsedMultiMaterial, scene);
  19391. materialFound = true;
  19392. break;
  19393. }
  19394. }
  19395. }
  19396. if (!materialFound) {
  19397. loadedMaterialsIds.push(parsedMesh.materialId);
  19398. parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  19399. }
  19400. }
  19401. // Skeleton ?
  19402. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  19403. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  19404. if (!skeletonAlreadyLoaded) {
  19405. for (var skeletonIndex = 0; skeletonIndex < parsedData.skeletons.length; skeletonIndex++) {
  19406. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  19407. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  19408. skeletons.push(parseSkeleton(parsedSkeleton, scene));
  19409. loadedSkeletonsIds.push(parsedSkeleton.id);
  19410. }
  19411. }
  19412. }
  19413. }
  19414. var mesh = parseMesh(parsedMesh, scene, rootUrl);
  19415. meshes.push(mesh);
  19416. }
  19417. }
  19418. for (index = 0; index < scene.meshes.length; index++) {
  19419. var currentMesh = scene.meshes[index];
  19420. if (currentMesh._waitingParentId) {
  19421. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  19422. currentMesh._waitingParentId = undefined;
  19423. }
  19424. }
  19425. // Particles
  19426. if (parsedData.particleSystems) {
  19427. for (index = 0; index < parsedData.particleSystems.length; index++) {
  19428. var parsedParticleSystem = parsedData.particleSystems[index];
  19429. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  19430. particleSystems.push(parseParticleSystem(parsedParticleSystem, scene, rootUrl));
  19431. }
  19432. }
  19433. }
  19434. return true;
  19435. },
  19436. load: function (scene, data, rootUrl) {
  19437. var parsedData = JSON.parse(data);
  19438. // Scene
  19439. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  19440. scene.autoClear = parsedData.autoClear;
  19441. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  19442. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  19443. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  19444. // Fog
  19445. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  19446. scene.fogMode = parsedData.fogMode;
  19447. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  19448. scene.fogStart = parsedData.fogStart;
  19449. scene.fogEnd = parsedData.fogEnd;
  19450. scene.fogDensity = parsedData.fogDensity;
  19451. }
  19452. for (var index = 0; index < parsedData.lights.length; index++) {
  19453. var parsedLight = parsedData.lights[index];
  19454. parseLight(parsedLight, scene);
  19455. }
  19456. // Materials
  19457. if (parsedData.materials) {
  19458. for (index = 0; index < parsedData.materials.length; index++) {
  19459. var parsedMaterial = parsedData.materials[index];
  19460. parseMaterial(parsedMaterial, scene, rootUrl);
  19461. }
  19462. }
  19463. if (parsedData.multiMaterials) {
  19464. for (index = 0; index < parsedData.multiMaterials.length; index++) {
  19465. var parsedMultiMaterial = parsedData.multiMaterials[index];
  19466. parseMultiMaterial(parsedMultiMaterial, scene);
  19467. }
  19468. }
  19469. // Skeletons
  19470. if (parsedData.skeletons) {
  19471. for (index = 0; index < parsedData.skeletons.length; index++) {
  19472. var parsedSkeleton = parsedData.skeletons[index];
  19473. parseSkeleton(parsedSkeleton, scene);
  19474. }
  19475. }
  19476. // Geometries
  19477. var geometries = parsedData.geometries;
  19478. if (geometries) {
  19479. // Boxes
  19480. var boxes = geometries.boxes;
  19481. if (boxes) {
  19482. for (index = 0; index < boxes.length; index++) {
  19483. var parsedBox = boxes[index];
  19484. parseBox(parsedBox, scene);
  19485. }
  19486. }
  19487. // Spheres
  19488. var spheres = geometries.spheres;
  19489. if (spheres) {
  19490. for (index = 0; index < spheres.length; index++) {
  19491. var parsedSphere = spheres[index];
  19492. parseSphere(parsedSphere, scene);
  19493. }
  19494. }
  19495. // Cylinders
  19496. var cylinders = geometries.cylinders;
  19497. if (cylinders) {
  19498. for (index = 0; index < cylinders.length; index++) {
  19499. var parsedCylinder = cylinders[index];
  19500. parseCylinder(parsedCylinder, scene);
  19501. }
  19502. }
  19503. // Toruses
  19504. var toruses = geometries.toruses;
  19505. if (toruses) {
  19506. for (index = 0; index < toruses.length; index++) {
  19507. var parsedTorus = toruses[index];
  19508. parseTorus(parsedTorus, scene);
  19509. }
  19510. }
  19511. // Grounds
  19512. var grounds = geometries.grounds;
  19513. if (grounds) {
  19514. for (index = 0; index < grounds.length; index++) {
  19515. var parsedGround = grounds[index];
  19516. parseGround(parsedGround, scene);
  19517. }
  19518. }
  19519. // Planes
  19520. var planes = geometries.planes;
  19521. if (planes) {
  19522. for (index = 0; index < planes.length; index++) {
  19523. var parsedPlane = planes[index];
  19524. parsePlane(parsedPlane, scene);
  19525. }
  19526. }
  19527. // TorusKnots
  19528. var torusKnots = geometries.torusKnots;
  19529. if (torusKnots) {
  19530. for (index = 0; index < torusKnots.length; index++) {
  19531. var parsedTorusKnot = torusKnots[index];
  19532. parseTorusKnot(parsedTorusKnot, scene);
  19533. }
  19534. }
  19535. // VertexData
  19536. var vertexData = geometries.vertexData;
  19537. if (vertexData) {
  19538. for (index = 0; index < vertexData.length; index++) {
  19539. var parsedVertexData = vertexData[index];
  19540. parseVertexData(parsedVertexData, scene, rootUrl);
  19541. }
  19542. }
  19543. }
  19544. for (index = 0; index < parsedData.meshes.length; index++) {
  19545. var parsedMesh = parsedData.meshes[index];
  19546. parseMesh(parsedMesh, scene, rootUrl);
  19547. }
  19548. for (index = 0; index < parsedData.cameras.length; index++) {
  19549. var parsedCamera = parsedData.cameras[index];
  19550. parseCamera(parsedCamera, scene);
  19551. }
  19552. if (parsedData.activeCameraID) {
  19553. scene.setActiveCameraByID(parsedData.activeCameraID);
  19554. }
  19555. for (index = 0; index < scene.cameras.length; index++) {
  19556. var camera = scene.cameras[index];
  19557. if (camera._waitingParentId) {
  19558. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  19559. camera._waitingParentId = undefined;
  19560. }
  19561. }
  19562. for (index = 0; index < scene.lights.length; index++) {
  19563. var light = scene.lights[index];
  19564. if (light._waitingParentId) {
  19565. light.parent = scene.getLastEntryByID(light._waitingParentId);
  19566. light._waitingParentId = undefined;
  19567. }
  19568. }
  19569. // Sounds
  19570. if (parsedData.sounds) {
  19571. for (index = 0; index < parsedData.sounds.length; index++) {
  19572. var parsedSound = parsedData.sounds[index];
  19573. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  19574. parseSound(parsedSound, scene, rootUrl);
  19575. }
  19576. else {
  19577. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  19578. }
  19579. }
  19580. }
  19581. for (index = 0; index < scene.meshes.length; index++) {
  19582. var mesh = scene.meshes[index];
  19583. if (mesh._waitingParentId) {
  19584. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  19585. mesh._waitingParentId = undefined;
  19586. }
  19587. if (mesh._waitingActions) {
  19588. parseActions(mesh._waitingActions, mesh, scene);
  19589. mesh._waitingActions = undefined;
  19590. }
  19591. }
  19592. // Particles Systems
  19593. if (parsedData.particleSystems) {
  19594. for (index = 0; index < parsedData.particleSystems.length; index++) {
  19595. var parsedParticleSystem = parsedData.particleSystems[index];
  19596. parseParticleSystem(parsedParticleSystem, scene, rootUrl);
  19597. }
  19598. }
  19599. // Lens flares
  19600. if (parsedData.lensFlareSystems) {
  19601. for (index = 0; index < parsedData.lensFlareSystems.length; index++) {
  19602. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  19603. parseLensFlareSystem(parsedLensFlareSystem, scene, rootUrl);
  19604. }
  19605. }
  19606. // Shadows
  19607. if (parsedData.shadowGenerators) {
  19608. for (index = 0; index < parsedData.shadowGenerators.length; index++) {
  19609. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  19610. parseShadowGenerator(parsedShadowGenerator, scene);
  19611. }
  19612. }
  19613. // Actions (scene)
  19614. if (parsedData.actions) {
  19615. parseActions(parsedData.actions, null, scene);
  19616. }
  19617. // Finish
  19618. return true;
  19619. }
  19620. });
  19621. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  19622. })(BABYLON || (BABYLON = {}));
  19623. //# sourceMappingURL=babylon.babylonFileLoader.js.mapvar BABYLON;
  19624. (function (BABYLON) {
  19625. // Unique ID when we import meshes from Babylon to CSG
  19626. var currentCSGMeshId = 0;
  19627. // # class Vertex
  19628. // Represents a vertex of a polygon. Use your own vertex class instead of this
  19629. // one to provide additional features like texture coordinates and vertex
  19630. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  19631. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  19632. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  19633. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  19634. // is not used anywhere else.
  19635. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  19636. var Vertex = (function () {
  19637. function Vertex(pos, normal, uv) {
  19638. this.pos = pos;
  19639. this.normal = normal;
  19640. this.uv = uv;
  19641. }
  19642. Vertex.prototype.clone = function () {
  19643. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  19644. };
  19645. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  19646. // orientation of a polygon is flipped.
  19647. Vertex.prototype.flip = function () {
  19648. this.normal = this.normal.scale(-1);
  19649. };
  19650. // Create a new vertex between this vertex and `other` by linearly
  19651. // interpolating all properties using a parameter of `t`. Subclasses should
  19652. // override this to interpolate additional properties.
  19653. Vertex.prototype.interpolate = function (other, t) {
  19654. 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));
  19655. };
  19656. return Vertex;
  19657. })();
  19658. // # class Plane
  19659. // Represents a plane in 3D space.
  19660. var Plane = (function () {
  19661. function Plane(normal, w) {
  19662. this.normal = normal;
  19663. this.w = w;
  19664. }
  19665. Plane.FromPoints = function (a, b, c) {
  19666. var v0 = c.subtract(a);
  19667. var v1 = b.subtract(a);
  19668. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  19669. return null;
  19670. }
  19671. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  19672. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  19673. };
  19674. Plane.prototype.clone = function () {
  19675. return new Plane(this.normal.clone(), this.w);
  19676. };
  19677. Plane.prototype.flip = function () {
  19678. this.normal.scaleInPlace(-1);
  19679. this.w = -this.w;
  19680. };
  19681. // Split `polygon` by this plane if needed, then put the polygon or polygon
  19682. // fragments in the appropriate lists. Coplanar polygons go into either
  19683. // `coplanarFront` or `coplanarBack` depending on their orientation with
  19684. // respect to this plane. Polygons in front or in back of this plane go into
  19685. // either `front` or `back`.
  19686. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  19687. var COPLANAR = 0;
  19688. var FRONT = 1;
  19689. var BACK = 2;
  19690. var SPANNING = 3;
  19691. // Classify each point as well as the entire polygon into one of the above
  19692. // four classes.
  19693. var polygonType = 0;
  19694. var types = [];
  19695. for (var i = 0; i < polygon.vertices.length; i++) {
  19696. var t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  19697. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  19698. polygonType |= type;
  19699. types.push(type);
  19700. }
  19701. switch (polygonType) {
  19702. case COPLANAR:
  19703. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  19704. break;
  19705. case FRONT:
  19706. front.push(polygon);
  19707. break;
  19708. case BACK:
  19709. back.push(polygon);
  19710. break;
  19711. case SPANNING:
  19712. var f = [], b = [];
  19713. for (i = 0; i < polygon.vertices.length; i++) {
  19714. var j = (i + 1) % polygon.vertices.length;
  19715. var ti = types[i], tj = types[j];
  19716. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  19717. if (ti != BACK)
  19718. f.push(vi);
  19719. if (ti != FRONT)
  19720. b.push(ti != BACK ? vi.clone() : vi);
  19721. if ((ti | tj) == SPANNING) {
  19722. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  19723. var v = vi.interpolate(vj, t);
  19724. f.push(v);
  19725. b.push(v.clone());
  19726. }
  19727. }
  19728. if (f.length >= 3) {
  19729. var poly = new Polygon(f, polygon.shared);
  19730. if (poly.plane)
  19731. front.push(poly);
  19732. }
  19733. if (b.length >= 3) {
  19734. poly = new Polygon(b, polygon.shared);
  19735. if (poly.plane)
  19736. back.push(poly);
  19737. }
  19738. break;
  19739. }
  19740. };
  19741. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  19742. // point is on the plane.
  19743. Plane.EPSILON = 1e-5;
  19744. return Plane;
  19745. })();
  19746. // # class Polygon
  19747. // Represents a convex polygon. The vertices used to initialize a polygon must
  19748. // be coplanar and form a convex loop.
  19749. //
  19750. // Each convex polygon has a `shared` property, which is shared between all
  19751. // polygons that are clones of each other or were split from the same polygon.
  19752. // This can be used to define per-polygon properties (such as surface color).
  19753. var Polygon = (function () {
  19754. function Polygon(vertices, shared) {
  19755. this.vertices = vertices;
  19756. this.shared = shared;
  19757. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  19758. }
  19759. Polygon.prototype.clone = function () {
  19760. var vertices = this.vertices.map(function (v) { return v.clone(); });
  19761. return new Polygon(vertices, this.shared);
  19762. };
  19763. Polygon.prototype.flip = function () {
  19764. this.vertices.reverse().map(function (v) {
  19765. v.flip();
  19766. });
  19767. this.plane.flip();
  19768. };
  19769. return Polygon;
  19770. })();
  19771. // # class Node
  19772. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  19773. // by picking a polygon to split along. That polygon (and all other coplanar
  19774. // polygons) are added directly to that node and the other polygons are added to
  19775. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  19776. // no distinction between internal and leaf nodes.
  19777. var Node = (function () {
  19778. function Node(polygons) {
  19779. this.plane = null;
  19780. this.front = null;
  19781. this.back = null;
  19782. this.polygons = [];
  19783. if (polygons) {
  19784. this.build(polygons);
  19785. }
  19786. }
  19787. Node.prototype.clone = function () {
  19788. var node = new Node();
  19789. node.plane = this.plane && this.plane.clone();
  19790. node.front = this.front && this.front.clone();
  19791. node.back = this.back && this.back.clone();
  19792. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  19793. return node;
  19794. };
  19795. // Convert solid space to empty space and empty space to solid space.
  19796. Node.prototype.invert = function () {
  19797. for (var i = 0; i < this.polygons.length; i++) {
  19798. this.polygons[i].flip();
  19799. }
  19800. if (this.plane) {
  19801. this.plane.flip();
  19802. }
  19803. if (this.front) {
  19804. this.front.invert();
  19805. }
  19806. if (this.back) {
  19807. this.back.invert();
  19808. }
  19809. var temp = this.front;
  19810. this.front = this.back;
  19811. this.back = temp;
  19812. };
  19813. // Recursively remove all polygons in `polygons` that are inside this BSP
  19814. // tree.
  19815. Node.prototype.clipPolygons = function (polygons) {
  19816. if (!this.plane)
  19817. return polygons.slice();
  19818. var front = [], back = [];
  19819. for (var i = 0; i < polygons.length; i++) {
  19820. this.plane.splitPolygon(polygons[i], front, back, front, back);
  19821. }
  19822. if (this.front) {
  19823. front = this.front.clipPolygons(front);
  19824. }
  19825. if (this.back) {
  19826. back = this.back.clipPolygons(back);
  19827. }
  19828. else {
  19829. back = [];
  19830. }
  19831. return front.concat(back);
  19832. };
  19833. // Remove all polygons in this BSP tree that are inside the other BSP tree
  19834. // `bsp`.
  19835. Node.prototype.clipTo = function (bsp) {
  19836. this.polygons = bsp.clipPolygons(this.polygons);
  19837. if (this.front)
  19838. this.front.clipTo(bsp);
  19839. if (this.back)
  19840. this.back.clipTo(bsp);
  19841. };
  19842. // Return a list of all polygons in this BSP tree.
  19843. Node.prototype.allPolygons = function () {
  19844. var polygons = this.polygons.slice();
  19845. if (this.front)
  19846. polygons = polygons.concat(this.front.allPolygons());
  19847. if (this.back)
  19848. polygons = polygons.concat(this.back.allPolygons());
  19849. return polygons;
  19850. };
  19851. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  19852. // new polygons are filtered down to the bottom of the tree and become new
  19853. // nodes there. Each set of polygons is partitioned using the first polygon
  19854. // (no heuristic is used to pick a good split).
  19855. Node.prototype.build = function (polygons) {
  19856. if (!polygons.length)
  19857. return;
  19858. if (!this.plane)
  19859. this.plane = polygons[0].plane.clone();
  19860. var front = [], back = [];
  19861. for (var i = 0; i < polygons.length; i++) {
  19862. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  19863. }
  19864. if (front.length) {
  19865. if (!this.front)
  19866. this.front = new Node();
  19867. this.front.build(front);
  19868. }
  19869. if (back.length) {
  19870. if (!this.back)
  19871. this.back = new Node();
  19872. this.back.build(back);
  19873. }
  19874. };
  19875. return Node;
  19876. })();
  19877. var CSG = (function () {
  19878. function CSG() {
  19879. this.polygons = new Array();
  19880. }
  19881. // Convert BABYLON.Mesh to BABYLON.CSG
  19882. CSG.FromMesh = function (mesh) {
  19883. var vertex, normal, uv, position, polygon, polygons = [], vertices;
  19884. if (mesh instanceof BABYLON.Mesh) {
  19885. mesh.computeWorldMatrix(true);
  19886. var matrix = mesh.getWorldMatrix();
  19887. var meshPosition = mesh.position.clone();
  19888. var meshRotation = mesh.rotation.clone();
  19889. var meshScaling = mesh.scaling.clone();
  19890. }
  19891. else {
  19892. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  19893. }
  19894. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  19895. var subMeshes = mesh.subMeshes;
  19896. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  19897. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  19898. vertices = [];
  19899. for (var j = 0; j < 3; j++) {
  19900. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  19901. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  19902. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  19903. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  19904. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  19905. vertex = new Vertex(position, normal, uv);
  19906. vertices.push(vertex);
  19907. }
  19908. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  19909. // To handle the case of degenerated triangle
  19910. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  19911. if (polygon.plane)
  19912. polygons.push(polygon);
  19913. }
  19914. }
  19915. var csg = CSG.FromPolygons(polygons);
  19916. csg.matrix = matrix;
  19917. csg.position = meshPosition;
  19918. csg.rotation = meshRotation;
  19919. csg.scaling = meshScaling;
  19920. currentCSGMeshId++;
  19921. return csg;
  19922. };
  19923. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  19924. CSG.FromPolygons = function (polygons) {
  19925. var csg = new BABYLON.CSG();
  19926. csg.polygons = polygons;
  19927. return csg;
  19928. };
  19929. CSG.prototype.clone = function () {
  19930. var csg = new BABYLON.CSG();
  19931. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  19932. csg.copyTransformAttributes(this);
  19933. return csg;
  19934. };
  19935. CSG.prototype.toPolygons = function () {
  19936. return this.polygons;
  19937. };
  19938. CSG.prototype.union = function (csg) {
  19939. var a = new Node(this.clone().polygons);
  19940. var b = new Node(csg.clone().polygons);
  19941. a.clipTo(b);
  19942. b.clipTo(a);
  19943. b.invert();
  19944. b.clipTo(a);
  19945. b.invert();
  19946. a.build(b.allPolygons());
  19947. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  19948. };
  19949. CSG.prototype.unionInPlace = function (csg) {
  19950. var a = new Node(this.polygons);
  19951. var b = new Node(csg.polygons);
  19952. a.clipTo(b);
  19953. b.clipTo(a);
  19954. b.invert();
  19955. b.clipTo(a);
  19956. b.invert();
  19957. a.build(b.allPolygons());
  19958. this.polygons = a.allPolygons();
  19959. };
  19960. CSG.prototype.subtract = function (csg) {
  19961. var a = new Node(this.clone().polygons);
  19962. var b = new Node(csg.clone().polygons);
  19963. a.invert();
  19964. a.clipTo(b);
  19965. b.clipTo(a);
  19966. b.invert();
  19967. b.clipTo(a);
  19968. b.invert();
  19969. a.build(b.allPolygons());
  19970. a.invert();
  19971. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  19972. };
  19973. CSG.prototype.subtractInPlace = function (csg) {
  19974. var a = new Node(this.polygons);
  19975. var b = new Node(csg.polygons);
  19976. a.invert();
  19977. a.clipTo(b);
  19978. b.clipTo(a);
  19979. b.invert();
  19980. b.clipTo(a);
  19981. b.invert();
  19982. a.build(b.allPolygons());
  19983. a.invert();
  19984. this.polygons = a.allPolygons();
  19985. };
  19986. CSG.prototype.intersect = function (csg) {
  19987. var a = new Node(this.clone().polygons);
  19988. var b = new Node(csg.clone().polygons);
  19989. a.invert();
  19990. b.clipTo(a);
  19991. b.invert();
  19992. a.clipTo(b);
  19993. b.clipTo(a);
  19994. a.build(b.allPolygons());
  19995. a.invert();
  19996. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  19997. };
  19998. CSG.prototype.intersectInPlace = function (csg) {
  19999. var a = new Node(this.polygons);
  20000. var b = new Node(csg.polygons);
  20001. a.invert();
  20002. b.clipTo(a);
  20003. b.invert();
  20004. a.clipTo(b);
  20005. b.clipTo(a);
  20006. a.build(b.allPolygons());
  20007. a.invert();
  20008. this.polygons = a.allPolygons();
  20009. };
  20010. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  20011. // not modified.
  20012. CSG.prototype.inverse = function () {
  20013. var csg = this.clone();
  20014. csg.inverseInPlace();
  20015. return csg;
  20016. };
  20017. CSG.prototype.inverseInPlace = function () {
  20018. this.polygons.map(function (p) {
  20019. p.flip();
  20020. });
  20021. };
  20022. // This is used to keep meshes transformations so they can be restored
  20023. // when we build back a Babylon Mesh
  20024. // NB : All CSG operations are performed in world coordinates
  20025. CSG.prototype.copyTransformAttributes = function (csg) {
  20026. this.matrix = csg.matrix;
  20027. this.position = csg.position;
  20028. this.rotation = csg.rotation;
  20029. this.scaling = csg.scaling;
  20030. return this;
  20031. };
  20032. // Build Raw mesh from CSG
  20033. // Coordinates here are in world space
  20034. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  20035. var matrix = this.matrix.clone();
  20036. matrix.invert();
  20037. 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;
  20038. if (keepSubMeshes) {
  20039. // Sort Polygons, since subMeshes are indices range
  20040. polygons.sort(function (a, b) {
  20041. if (a.shared.meshId === b.shared.meshId) {
  20042. return a.shared.subMeshId - b.shared.subMeshId;
  20043. }
  20044. else {
  20045. return a.shared.meshId - b.shared.meshId;
  20046. }
  20047. });
  20048. }
  20049. for (var i = 0, il = polygons.length; i < il; i++) {
  20050. polygon = polygons[i];
  20051. // Building SubMeshes
  20052. if (!subMesh_dict[polygon.shared.meshId]) {
  20053. subMesh_dict[polygon.shared.meshId] = {};
  20054. }
  20055. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  20056. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  20057. indexStart: +Infinity,
  20058. indexEnd: -Infinity,
  20059. materialIndex: polygon.shared.materialIndex
  20060. };
  20061. }
  20062. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  20063. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  20064. polygonIndices[0] = 0;
  20065. polygonIndices[1] = j - 1;
  20066. polygonIndices[2] = j;
  20067. for (var k = 0; k < 3; k++) {
  20068. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  20069. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  20070. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  20071. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  20072. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  20073. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  20074. // Check if 2 points can be merged
  20075. 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)) {
  20076. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  20077. uvs.push(uv.x, uv.y);
  20078. normals.push(normal.x, normal.y, normal.z);
  20079. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  20080. }
  20081. indices.push(vertex_idx);
  20082. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  20083. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  20084. currentIndex++;
  20085. }
  20086. }
  20087. }
  20088. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  20089. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  20090. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  20091. mesh.setIndices(indices);
  20092. if (keepSubMeshes) {
  20093. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  20094. var materialIndexOffset = 0, materialMaxIndex;
  20095. mesh.subMeshes.length = 0;
  20096. for (var m in subMesh_dict) {
  20097. materialMaxIndex = -1;
  20098. for (var sm in subMesh_dict[m]) {
  20099. subMesh_obj = subMesh_dict[m][sm];
  20100. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  20101. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  20102. }
  20103. materialIndexOffset += ++materialMaxIndex;
  20104. }
  20105. }
  20106. return mesh;
  20107. };
  20108. // Build Mesh from CSG taking material and transforms into account
  20109. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  20110. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  20111. mesh.material = material;
  20112. mesh.position.copyFrom(this.position);
  20113. mesh.rotation.copyFrom(this.rotation);
  20114. mesh.scaling.copyFrom(this.scaling);
  20115. mesh.computeWorldMatrix(true);
  20116. return mesh;
  20117. };
  20118. return CSG;
  20119. })();
  20120. BABYLON.CSG = CSG;
  20121. })(BABYLON || (BABYLON = {}));
  20122. //# sourceMappingURL=babylon.csg.js.map
  20123. var BABYLON;
  20124. (function (BABYLON) {
  20125. var OculusDistortionCorrectionPostProcess = (function (_super) {
  20126. __extends(OculusDistortionCorrectionPostProcess, _super);
  20127. //ANY
  20128. function OculusDistortionCorrectionPostProcess(name, camera, isRightEye, cameraSettings) {
  20129. var _this = this;
  20130. _super.call(this, name, "oculusDistortionCorrection", [
  20131. 'LensCenter',
  20132. 'Scale',
  20133. 'ScaleIn',
  20134. 'HmdWarpParam'
  20135. ], null, cameraSettings.PostProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  20136. this._isRightEye = isRightEye;
  20137. this._distortionFactors = cameraSettings.DistortionK;
  20138. this._postProcessScaleFactor = cameraSettings.PostProcessScaleFactor;
  20139. this._lensCenterOffset = cameraSettings.LensCenterOffset;
  20140. this.onSizeChanged = function () {
  20141. _this.aspectRatio = _this.width * .5 / _this.height;
  20142. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  20143. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  20144. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  20145. };
  20146. this.onApply = function (effect) {
  20147. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  20148. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  20149. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  20150. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  20151. };
  20152. }
  20153. return OculusDistortionCorrectionPostProcess;
  20154. })(BABYLON.PostProcess);
  20155. BABYLON.OculusDistortionCorrectionPostProcess = OculusDistortionCorrectionPostProcess;
  20156. })(BABYLON || (BABYLON = {}));
  20157. //# sourceMappingURL=babylon.oculusDistortionCorrectionPostProcess.js.map// Mainly based on these 2 articles :
  20158. // 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
  20159. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  20160. var BABYLON;
  20161. (function (BABYLON) {
  20162. (function (JoystickAxis) {
  20163. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  20164. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  20165. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  20166. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  20167. var JoystickAxis = BABYLON.JoystickAxis;
  20168. var VirtualJoystick = (function () {
  20169. function VirtualJoystick(leftJoystick) {
  20170. var _this = this;
  20171. if (leftJoystick) {
  20172. this._leftJoystick = true;
  20173. }
  20174. else {
  20175. this._leftJoystick = false;
  20176. }
  20177. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  20178. VirtualJoystick._globalJoystickIndex++;
  20179. // By default left & right arrow keys are moving the X
  20180. // and up & down keys are moving the Y
  20181. this._axisTargetedByLeftAndRight = 0 /* X */;
  20182. this._axisTargetedByUpAndDown = 1 /* Y */;
  20183. this.reverseLeftRight = false;
  20184. this.reverseUpDown = false;
  20185. // collections of pointers
  20186. this._touches = new BABYLON.VirtualJoystick.Collection();
  20187. this.deltaPosition = BABYLON.Vector3.Zero();
  20188. this._joystickSensibility = 25;
  20189. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  20190. this._rotationSpeed = 25;
  20191. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  20192. this._rotateOnAxisRelativeToMesh = false;
  20193. // injecting a canvas element on top of the canvas 3D game
  20194. if (!VirtualJoystick.vjCanvas) {
  20195. window.addEventListener("resize", function () {
  20196. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  20197. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  20198. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  20199. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  20200. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  20201. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  20202. }, false);
  20203. VirtualJoystick.vjCanvas = document.createElement("canvas");
  20204. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  20205. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  20206. VirtualJoystick.vjCanvas.width = window.innerWidth;
  20207. VirtualJoystick.vjCanvas.height = window.innerHeight;
  20208. VirtualJoystick.vjCanvas.style.width = "100%";
  20209. VirtualJoystick.vjCanvas.style.height = "100%";
  20210. VirtualJoystick.vjCanvas.style.position = "absolute";
  20211. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  20212. VirtualJoystick.vjCanvas.style.top = "0px";
  20213. VirtualJoystick.vjCanvas.style.left = "0px";
  20214. VirtualJoystick.vjCanvas.style.zIndex = "5";
  20215. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  20216. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  20217. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  20218. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  20219. document.body.appendChild(VirtualJoystick.vjCanvas);
  20220. }
  20221. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  20222. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  20223. this.pressed = false;
  20224. // default joystick color
  20225. this._joystickColor = "cyan";
  20226. this._joystickPointerID = -1;
  20227. // current joystick position
  20228. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  20229. // origin joystick position
  20230. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  20231. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  20232. VirtualJoystick.vjCanvas.addEventListener('pointerdown', function (evt) {
  20233. _this._onPointerDown(evt);
  20234. }, false);
  20235. VirtualJoystick.vjCanvas.addEventListener('pointermove', function (evt) {
  20236. _this._onPointerMove(evt);
  20237. }, false);
  20238. VirtualJoystick.vjCanvas.addEventListener('pointerup', function (evt) {
  20239. _this._onPointerUp(evt);
  20240. }, false);
  20241. VirtualJoystick.vjCanvas.addEventListener('pointerout', function (evt) {
  20242. _this._onPointerUp(evt);
  20243. }, false);
  20244. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  20245. evt.preventDefault(); // Disables system menu
  20246. }, false);
  20247. requestAnimationFrame(function () {
  20248. _this._drawVirtualJoystick();
  20249. });
  20250. }
  20251. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  20252. this._joystickSensibility = newJoystickSensibility;
  20253. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  20254. };
  20255. VirtualJoystick.prototype._onPointerDown = function (e) {
  20256. var positionOnScreenCondition;
  20257. e.preventDefault();
  20258. if (this._leftJoystick === true) {
  20259. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  20260. }
  20261. else {
  20262. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  20263. }
  20264. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  20265. // First contact will be dedicated to the virtual joystick
  20266. this._joystickPointerID = e.pointerId;
  20267. this._joystickPointerStartPos.x = e.clientX;
  20268. this._joystickPointerStartPos.y = e.clientY;
  20269. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  20270. this._deltaJoystickVector.x = 0;
  20271. this._deltaJoystickVector.y = 0;
  20272. this.pressed = true;
  20273. this._touches.add(e.pointerId.toString(), e);
  20274. }
  20275. else {
  20276. // You can only trigger the action buttons with a joystick declared
  20277. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  20278. this._action();
  20279. this._touches.add(e.pointerId.toString(), e);
  20280. }
  20281. }
  20282. };
  20283. VirtualJoystick.prototype._onPointerMove = function (e) {
  20284. // If the current pointer is the one associated to the joystick (first touch contact)
  20285. if (this._joystickPointerID == e.pointerId) {
  20286. this._joystickPointerPos.x = e.clientX;
  20287. this._joystickPointerPos.y = e.clientY;
  20288. this._deltaJoystickVector = this._joystickPointerPos.clone();
  20289. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  20290. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  20291. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  20292. switch (this._axisTargetedByLeftAndRight) {
  20293. case 0 /* X */:
  20294. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  20295. break;
  20296. case 1 /* Y */:
  20297. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  20298. break;
  20299. case 2 /* Z */:
  20300. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  20301. break;
  20302. }
  20303. var directionUpDown = this.reverseUpDown ? 1 : -1;
  20304. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  20305. switch (this._axisTargetedByUpAndDown) {
  20306. case 0 /* X */:
  20307. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  20308. break;
  20309. case 1 /* Y */:
  20310. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  20311. break;
  20312. case 2 /* Z */:
  20313. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  20314. break;
  20315. }
  20316. }
  20317. else {
  20318. if (this._touches.item(e.pointerId.toString())) {
  20319. this._touches.item(e.pointerId.toString()).x = e.clientX;
  20320. this._touches.item(e.pointerId.toString()).y = e.clientY;
  20321. }
  20322. }
  20323. };
  20324. VirtualJoystick.prototype._onPointerUp = function (e) {
  20325. this._clearCanvas();
  20326. if (this._joystickPointerID == e.pointerId) {
  20327. this._joystickPointerID = -1;
  20328. this.pressed = false;
  20329. }
  20330. this._deltaJoystickVector.x = 0;
  20331. this._deltaJoystickVector.y = 0;
  20332. this._touches.remove(e.pointerId.toString());
  20333. };
  20334. /**
  20335. * Change the color of the virtual joystick
  20336. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  20337. */
  20338. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  20339. this._joystickColor = newColor;
  20340. };
  20341. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  20342. this._action = action;
  20343. };
  20344. // Define which axis you'd like to control for left & right
  20345. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  20346. switch (axis) {
  20347. case 0 /* X */:
  20348. case 1 /* Y */:
  20349. case 2 /* Z */:
  20350. this._axisTargetedByLeftAndRight = axis;
  20351. break;
  20352. default:
  20353. this._axisTargetedByLeftAndRight = 0 /* X */;
  20354. break;
  20355. }
  20356. };
  20357. // Define which axis you'd like to control for up & down
  20358. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  20359. switch (axis) {
  20360. case 0 /* X */:
  20361. case 1 /* Y */:
  20362. case 2 /* Z */:
  20363. this._axisTargetedByUpAndDown = axis;
  20364. break;
  20365. default:
  20366. this._axisTargetedByUpAndDown = 1 /* Y */;
  20367. break;
  20368. }
  20369. };
  20370. VirtualJoystick.prototype._clearCanvas = function () {
  20371. if (this._leftJoystick) {
  20372. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  20373. }
  20374. else {
  20375. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  20376. }
  20377. };
  20378. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  20379. var _this = this;
  20380. if (this.pressed) {
  20381. this._clearCanvas();
  20382. this._touches.forEach(function (touch) {
  20383. if (touch.pointerId === _this._joystickPointerID) {
  20384. VirtualJoystick.vjCanvasContext.beginPath();
  20385. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  20386. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  20387. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  20388. VirtualJoystick.vjCanvasContext.stroke();
  20389. VirtualJoystick.vjCanvasContext.beginPath();
  20390. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  20391. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  20392. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  20393. VirtualJoystick.vjCanvasContext.stroke();
  20394. VirtualJoystick.vjCanvasContext.beginPath();
  20395. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  20396. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  20397. VirtualJoystick.vjCanvasContext.stroke();
  20398. }
  20399. else {
  20400. VirtualJoystick.vjCanvasContext.beginPath();
  20401. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  20402. VirtualJoystick.vjCanvasContext.beginPath();
  20403. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  20404. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  20405. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  20406. VirtualJoystick.vjCanvasContext.stroke();
  20407. }
  20408. ;
  20409. });
  20410. }
  20411. requestAnimationFrame(function () {
  20412. _this._drawVirtualJoystick();
  20413. });
  20414. };
  20415. VirtualJoystick.prototype.releaseCanvas = function () {
  20416. if (VirtualJoystick.vjCanvas) {
  20417. document.body.removeChild(VirtualJoystick.vjCanvas);
  20418. VirtualJoystick.vjCanvas = null;
  20419. }
  20420. };
  20421. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  20422. VirtualJoystick._globalJoystickIndex = 0;
  20423. return VirtualJoystick;
  20424. })();
  20425. BABYLON.VirtualJoystick = VirtualJoystick;
  20426. })(BABYLON || (BABYLON = {}));
  20427. var BABYLON;
  20428. (function (BABYLON) {
  20429. var VirtualJoystick;
  20430. (function (VirtualJoystick) {
  20431. var Collection = (function () {
  20432. function Collection() {
  20433. this._count = 0;
  20434. this._collection = new Array();
  20435. }
  20436. Collection.prototype.Count = function () {
  20437. return this._count;
  20438. };
  20439. Collection.prototype.add = function (key, item) {
  20440. if (this._collection[key] != undefined) {
  20441. return undefined;
  20442. }
  20443. this._collection[key] = item;
  20444. return ++this._count;
  20445. };
  20446. Collection.prototype.remove = function (key) {
  20447. if (this._collection[key] == undefined) {
  20448. return undefined;
  20449. }
  20450. delete this._collection[key];
  20451. return --this._count;
  20452. };
  20453. Collection.prototype.item = function (key) {
  20454. return this._collection[key];
  20455. };
  20456. Collection.prototype.forEach = function (block) {
  20457. var key;
  20458. for (key in this._collection) {
  20459. if (this._collection.hasOwnProperty(key)) {
  20460. block(this._collection[key]);
  20461. }
  20462. }
  20463. };
  20464. return Collection;
  20465. })();
  20466. VirtualJoystick.Collection = Collection;
  20467. })(VirtualJoystick = BABYLON.VirtualJoystick || (BABYLON.VirtualJoystick = {}));
  20468. })(BABYLON || (BABYLON = {}));
  20469. //# sourceMappingURL=babylon.virtualJoystick.js.map
  20470. var BABYLON;
  20471. (function (BABYLON) {
  20472. var OculusRiftDevKit2013_Metric = {
  20473. HResolution: 1280,
  20474. VResolution: 800,
  20475. HScreenSize: 0.149759993,
  20476. VScreenSize: 0.0935999975,
  20477. VScreenCenter: 0.0467999987,
  20478. EyeToScreenDistance: 0.0410000011,
  20479. LensSeparationDistance: 0.0635000020,
  20480. InterpupillaryDistance: 0.0640000030,
  20481. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  20482. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  20483. PostProcessScaleFactor: 1.714605507808412,
  20484. LensCenterOffset: 0.151976421
  20485. };
  20486. var _OculusInnerCamera = (function (_super) {
  20487. __extends(_OculusInnerCamera, _super);
  20488. function _OculusInnerCamera(name, position, scene, isLeftEye) {
  20489. _super.call(this, name, position, scene);
  20490. this._workMatrix = new BABYLON.Matrix();
  20491. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  20492. // Constants
  20493. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  20494. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  20495. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  20496. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  20497. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  20498. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  20499. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  20500. // Postprocess
  20501. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  20502. }
  20503. _OculusInnerCamera.prototype.getProjectionMatrix = function () {
  20504. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  20505. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  20506. return this._projectionMatrix;
  20507. };
  20508. _OculusInnerCamera.prototype._getViewMatrix = function () {
  20509. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  20510. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  20511. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  20512. // Computing target and final matrix
  20513. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  20514. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  20515. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  20516. return this._viewMatrix;
  20517. };
  20518. return _OculusInnerCamera;
  20519. })(BABYLON.FreeCamera);
  20520. var OculusCamera = (function (_super) {
  20521. __extends(OculusCamera, _super);
  20522. function OculusCamera(name, position, scene) {
  20523. _super.call(this, name, position, scene);
  20524. this._leftCamera = new _OculusInnerCamera(name + "_left", position.clone(), scene, true);
  20525. this._rightCamera = new _OculusInnerCamera(name + "_right", position.clone(), scene, false);
  20526. this.subCameras.push(this._leftCamera);
  20527. this.subCameras.push(this._rightCamera);
  20528. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  20529. }
  20530. OculusCamera.prototype._update = function () {
  20531. this._leftCamera.position.copyFrom(this.position);
  20532. this._rightCamera.position.copyFrom(this.position);
  20533. this._updateCamera(this._leftCamera);
  20534. this._updateCamera(this._rightCamera);
  20535. _super.prototype._update.call(this);
  20536. };
  20537. OculusCamera.prototype._updateCamera = function (camera) {
  20538. camera.minZ = this.minZ;
  20539. camera.maxZ = this.maxZ;
  20540. camera.rotation.x = this.rotation.x;
  20541. camera.rotation.y = this.rotation.y;
  20542. camera.rotation.z = this.rotation.z;
  20543. };
  20544. // Oculus events
  20545. OculusCamera.prototype._onOrientationEvent = function (evt) {
  20546. var yaw = evt.alpha / 180 * Math.PI;
  20547. var pitch = evt.beta / 180 * Math.PI;
  20548. var roll = evt.gamma / 180 * Math.PI;
  20549. if (!this._offsetOrientation) {
  20550. this._offsetOrientation = {
  20551. yaw: yaw,
  20552. pitch: pitch,
  20553. roll: roll
  20554. };
  20555. return;
  20556. }
  20557. else {
  20558. this.rotation.y += yaw - this._offsetOrientation.yaw;
  20559. this.rotation.x += pitch - this._offsetOrientation.pitch;
  20560. this.rotation.z += this._offsetOrientation.roll - roll;
  20561. this._offsetOrientation.yaw = yaw;
  20562. this._offsetOrientation.pitch = pitch;
  20563. this._offsetOrientation.roll = roll;
  20564. }
  20565. };
  20566. OculusCamera.prototype.attachControl = function (element, noPreventDefault) {
  20567. _super.prototype.attachControl.call(this, element, noPreventDefault);
  20568. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  20569. };
  20570. OculusCamera.prototype.detachControl = function (element) {
  20571. _super.prototype.detachControl.call(this, element);
  20572. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  20573. };
  20574. return OculusCamera;
  20575. })(BABYLON.FreeCamera);
  20576. BABYLON.OculusCamera = OculusCamera;
  20577. })(BABYLON || (BABYLON = {}));
  20578. //# sourceMappingURL=babylon.oculusCamera.js.map
  20579. var BABYLON;
  20580. (function (BABYLON) {
  20581. var OculusRiftDevKit2013_Metric = {
  20582. HResolution: 1280,
  20583. VResolution: 800,
  20584. HScreenSize: 0.149759993,
  20585. VScreenSize: 0.0935999975,
  20586. VScreenCenter: 0.0467999987,
  20587. EyeToScreenDistance: 0.0410000011,
  20588. LensSeparationDistance: 0.0635000020,
  20589. InterpupillaryDistance: 0.0640000030,
  20590. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  20591. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  20592. PostProcessScaleFactor: 1.714605507808412,
  20593. LensCenterOffset: 0.151976421
  20594. };
  20595. var _OculusInnerGamepadCamera = (function (_super) {
  20596. __extends(_OculusInnerGamepadCamera, _super);
  20597. function _OculusInnerGamepadCamera(name, position, scene, isLeftEye) {
  20598. _super.call(this, name, position, scene);
  20599. this._workMatrix = new BABYLON.Matrix();
  20600. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  20601. // Constants
  20602. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  20603. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  20604. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  20605. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  20606. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  20607. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  20608. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  20609. // Postprocess
  20610. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  20611. }
  20612. _OculusInnerGamepadCamera.prototype.getProjectionMatrix = function () {
  20613. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  20614. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  20615. return this._projectionMatrix;
  20616. };
  20617. _OculusInnerGamepadCamera.prototype._getViewMatrix = function () {
  20618. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  20619. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  20620. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  20621. // Computing target and final matrix
  20622. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  20623. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  20624. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  20625. return this._viewMatrix;
  20626. };
  20627. return _OculusInnerGamepadCamera;
  20628. })(BABYLON.FreeCamera);
  20629. var OculusGamepadCamera = (function (_super) {
  20630. __extends(OculusGamepadCamera, _super);
  20631. function OculusGamepadCamera(name, position, scene) {
  20632. var _this = this;
  20633. _super.call(this, name, position, scene);
  20634. this.angularSensibility = 200;
  20635. this.moveSensibility = 75;
  20636. this._leftCamera = new _OculusInnerGamepadCamera(name + "_left", position.clone(), scene, true);
  20637. this._rightCamera = new _OculusInnerGamepadCamera(name + "_right", position.clone(), scene, false);
  20638. this.subCameras.push(this._leftCamera);
  20639. this.subCameras.push(this._rightCamera);
  20640. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  20641. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  20642. _this._onNewGameConnected(gamepad);
  20643. });
  20644. }
  20645. OculusGamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  20646. // Only the first gamepad can control the camera
  20647. if (gamepad.index === 0) {
  20648. this._gamepad = gamepad;
  20649. }
  20650. };
  20651. OculusGamepadCamera.prototype._update = function () {
  20652. this._leftCamera.position.copyFrom(this.position);
  20653. this._rightCamera.position.copyFrom(this.position);
  20654. this._updateCamera(this._leftCamera);
  20655. this._updateCamera(this._rightCamera);
  20656. _super.prototype._update.call(this);
  20657. };
  20658. OculusGamepadCamera.prototype._checkInputs = function () {
  20659. if (!this._gamepad) {
  20660. return;
  20661. }
  20662. var LSValues = this._gamepad.leftStick;
  20663. var normalizedLX = LSValues.x / this.moveSensibility;
  20664. var normalizedLY = LSValues.y / this.moveSensibility;
  20665. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  20666. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  20667. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  20668. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x, 0, -LSValues.y), cameraTransform);
  20669. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  20670. };
  20671. OculusGamepadCamera.prototype._updateCamera = function (camera) {
  20672. camera.minZ = this.minZ;
  20673. camera.maxZ = this.maxZ;
  20674. camera.rotation.x = this.rotation.x;
  20675. camera.rotation.y = this.rotation.y;
  20676. camera.rotation.z = this.rotation.z;
  20677. };
  20678. // Oculus events
  20679. OculusGamepadCamera.prototype._onOrientationEvent = function (evt) {
  20680. var yaw = evt.alpha / 180 * Math.PI;
  20681. var pitch = evt.beta / 180 * Math.PI;
  20682. var roll = evt.gamma / 180 * Math.PI;
  20683. if (!this._offsetOrientation) {
  20684. this._offsetOrientation = {
  20685. yaw: yaw,
  20686. pitch: pitch,
  20687. roll: roll
  20688. };
  20689. return;
  20690. }
  20691. else {
  20692. this.rotation.y += yaw - this._offsetOrientation.yaw;
  20693. this.rotation.x += pitch - this._offsetOrientation.pitch;
  20694. this.rotation.z += this._offsetOrientation.roll - roll;
  20695. this._offsetOrientation.yaw = yaw;
  20696. this._offsetOrientation.pitch = pitch;
  20697. this._offsetOrientation.roll = roll;
  20698. }
  20699. };
  20700. OculusGamepadCamera.prototype.attachControl = function (element, noPreventDefault) {
  20701. _super.prototype.attachControl.call(this, element, noPreventDefault);
  20702. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  20703. };
  20704. OculusGamepadCamera.prototype.detachControl = function (element) {
  20705. _super.prototype.detachControl.call(this, element);
  20706. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  20707. };
  20708. OculusGamepadCamera.prototype.dispose = function () {
  20709. this._gamepads.dispose();
  20710. _super.prototype.dispose.call(this);
  20711. };
  20712. return OculusGamepadCamera;
  20713. })(BABYLON.FreeCamera);
  20714. BABYLON.OculusGamepadCamera = OculusGamepadCamera;
  20715. })(BABYLON || (BABYLON = {}));
  20716. //# sourceMappingURL=babylon.oculusGamepadCamera.js.map
  20717. var BABYLON;
  20718. (function (BABYLON) {
  20719. // We're mainly based on the logic defined into the FreeCamera code
  20720. var VirtualJoysticksCamera = (function (_super) {
  20721. __extends(VirtualJoysticksCamera, _super);
  20722. function VirtualJoysticksCamera(name, position, scene) {
  20723. _super.call(this, name, position, scene);
  20724. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  20725. this._leftjoystick.setAxisForUpDown(2 /* Z */);
  20726. this._leftjoystick.setAxisForLeftRight(0 /* X */);
  20727. this._leftjoystick.setJoystickSensibility(0.15);
  20728. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  20729. this._rightjoystick.setAxisForUpDown(0 /* X */);
  20730. this._rightjoystick.setAxisForLeftRight(1 /* Y */);
  20731. this._rightjoystick.reverseUpDown = true;
  20732. this._rightjoystick.setJoystickSensibility(0.05);
  20733. this._rightjoystick.setJoystickColor("yellow");
  20734. }
  20735. VirtualJoysticksCamera.prototype._checkInputs = function () {
  20736. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  20737. var deltaTransform = BABYLON.Vector3.TransformCoordinates(this._leftjoystick.deltaPosition, cameraTransform);
  20738. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  20739. this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  20740. if (!this._leftjoystick.pressed) {
  20741. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  20742. }
  20743. if (!this._rightjoystick.pressed) {
  20744. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  20745. }
  20746. };
  20747. VirtualJoysticksCamera.prototype.dispose = function () {
  20748. this._leftjoystick.releaseCanvas();
  20749. _super.prototype.dispose.call(this);
  20750. };
  20751. return VirtualJoysticksCamera;
  20752. })(BABYLON.FreeCamera);
  20753. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  20754. })(BABYLON || (BABYLON = {}));
  20755. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  20756. var BABYLON;
  20757. (function (BABYLON) {
  20758. var ShaderMaterial = (function (_super) {
  20759. __extends(ShaderMaterial, _super);
  20760. function ShaderMaterial(name, scene, shaderPath, options) {
  20761. _super.call(this, name, scene);
  20762. this._textures = new Array();
  20763. this._floats = new Array();
  20764. this._floatsArrays = {};
  20765. this._colors3 = new Array();
  20766. this._colors4 = new Array();
  20767. this._vectors2 = new Array();
  20768. this._vectors3 = new Array();
  20769. this._matrices = new Array();
  20770. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  20771. this._shaderPath = shaderPath;
  20772. options.needAlphaBlending = options.needAlphaBlending || false;
  20773. options.needAlphaTesting = options.needAlphaTesting || false;
  20774. options.attributes = options.attributes || ["position", "normal", "uv"];
  20775. options.uniforms = options.uniforms || ["worldViewProjection"];
  20776. options.samplers = options.samplers || [];
  20777. this._options = options;
  20778. }
  20779. ShaderMaterial.prototype.needAlphaBlending = function () {
  20780. return this._options.needAlphaBlending;
  20781. };
  20782. ShaderMaterial.prototype.needAlphaTesting = function () {
  20783. return this._options.needAlphaTesting;
  20784. };
  20785. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  20786. if (this._options.uniforms.indexOf(uniformName) === -1) {
  20787. this._options.uniforms.push(uniformName);
  20788. }
  20789. };
  20790. ShaderMaterial.prototype.setTexture = function (name, texture) {
  20791. if (this._options.samplers.indexOf(name) === -1) {
  20792. this._options.samplers.push(name);
  20793. }
  20794. this._textures[name] = texture;
  20795. return this;
  20796. };
  20797. ShaderMaterial.prototype.setFloat = function (name, value) {
  20798. this._checkUniform(name);
  20799. this._floats[name] = value;
  20800. return this;
  20801. };
  20802. ShaderMaterial.prototype.setFloats = function (name, value) {
  20803. this._checkUniform(name);
  20804. this._floatsArrays[name] = value;
  20805. return this;
  20806. };
  20807. ShaderMaterial.prototype.setColor3 = function (name, value) {
  20808. this._checkUniform(name);
  20809. this._colors3[name] = value;
  20810. return this;
  20811. };
  20812. ShaderMaterial.prototype.setColor4 = function (name, value) {
  20813. this._checkUniform(name);
  20814. this._colors4[name] = value;
  20815. return this;
  20816. };
  20817. ShaderMaterial.prototype.setVector2 = function (name, value) {
  20818. this._checkUniform(name);
  20819. this._vectors2[name] = value;
  20820. return this;
  20821. };
  20822. ShaderMaterial.prototype.setVector3 = function (name, value) {
  20823. this._checkUniform(name);
  20824. this._vectors3[name] = value;
  20825. return this;
  20826. };
  20827. ShaderMaterial.prototype.setMatrix = function (name, value) {
  20828. this._checkUniform(name);
  20829. this._matrices[name] = value;
  20830. return this;
  20831. };
  20832. ShaderMaterial.prototype.isReady = function () {
  20833. var scene = this.getScene();
  20834. var engine = scene.getEngine();
  20835. if (!this.checkReadyOnEveryCall) {
  20836. if (this._renderId === scene.getRenderId()) {
  20837. return true;
  20838. }
  20839. }
  20840. var previousEffect = this._effect;
  20841. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, "", null, this.onCompiled, this.onError);
  20842. if (!this._effect.isReady()) {
  20843. return false;
  20844. }
  20845. if (previousEffect !== this._effect) {
  20846. scene.resetCachedMaterial();
  20847. }
  20848. this._renderId = scene.getRenderId();
  20849. return true;
  20850. };
  20851. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  20852. var scene = this.getScene();
  20853. if (this._options.uniforms.indexOf("world") !== -1) {
  20854. this._effect.setMatrix("world", world);
  20855. }
  20856. if (this._options.uniforms.indexOf("worldView") !== -1) {
  20857. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  20858. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  20859. }
  20860. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  20861. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  20862. }
  20863. };
  20864. ShaderMaterial.prototype.bind = function (world) {
  20865. // Std values
  20866. this.bindOnlyWorldMatrix(world);
  20867. if (this.getScene().getCachedMaterial() !== this) {
  20868. if (this._options.uniforms.indexOf("view") !== -1) {
  20869. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  20870. }
  20871. if (this._options.uniforms.indexOf("projection") !== -1) {
  20872. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  20873. }
  20874. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  20875. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  20876. }
  20877. for (var name in this._textures) {
  20878. this._effect.setTexture(name, this._textures[name]);
  20879. }
  20880. for (name in this._floats) {
  20881. this._effect.setFloat(name, this._floats[name]);
  20882. }
  20883. for (name in this._floatsArrays) {
  20884. this._effect.setArray(name, this._floatsArrays[name]);
  20885. }
  20886. for (name in this._colors3) {
  20887. this._effect.setColor3(name, this._colors3[name]);
  20888. }
  20889. for (name in this._colors4) {
  20890. var color = this._colors4[name];
  20891. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  20892. }
  20893. for (name in this._vectors2) {
  20894. this._effect.setVector2(name, this._vectors2[name]);
  20895. }
  20896. for (name in this._vectors3) {
  20897. this._effect.setVector3(name, this._vectors3[name]);
  20898. }
  20899. for (name in this._matrices) {
  20900. this._effect.setMatrix(name, this._matrices[name]);
  20901. }
  20902. }
  20903. _super.prototype.bind.call(this, world, null);
  20904. };
  20905. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  20906. for (var name in this._textures) {
  20907. this._textures[name].dispose();
  20908. }
  20909. this._textures = [];
  20910. _super.prototype.dispose.call(this, forceDisposeEffect);
  20911. };
  20912. return ShaderMaterial;
  20913. })(BABYLON.Material);
  20914. BABYLON.ShaderMaterial = ShaderMaterial;
  20915. })(BABYLON || (BABYLON = {}));
  20916. //# sourceMappingURL=babylon.shaderMaterial.js.mapvar BABYLON;
  20917. (function (BABYLON) {
  20918. var VertexData = (function () {
  20919. function VertexData() {
  20920. }
  20921. VertexData.prototype.set = function (data, kind) {
  20922. switch (kind) {
  20923. case BABYLON.VertexBuffer.PositionKind:
  20924. this.positions = data;
  20925. break;
  20926. case BABYLON.VertexBuffer.NormalKind:
  20927. this.normals = data;
  20928. break;
  20929. case BABYLON.VertexBuffer.UVKind:
  20930. this.uvs = data;
  20931. break;
  20932. case BABYLON.VertexBuffer.UV2Kind:
  20933. this.uv2s = data;
  20934. break;
  20935. case BABYLON.VertexBuffer.ColorKind:
  20936. this.colors = data;
  20937. break;
  20938. case BABYLON.VertexBuffer.MatricesIndicesKind:
  20939. this.matricesIndices = data;
  20940. break;
  20941. case BABYLON.VertexBuffer.MatricesWeightsKind:
  20942. this.matricesWeights = data;
  20943. break;
  20944. }
  20945. };
  20946. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  20947. this._applyTo(mesh, updatable);
  20948. };
  20949. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  20950. this._applyTo(geometry, updatable);
  20951. };
  20952. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  20953. this._update(mesh);
  20954. };
  20955. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  20956. this._update(geometry);
  20957. };
  20958. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  20959. if (this.positions) {
  20960. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  20961. }
  20962. if (this.normals) {
  20963. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  20964. }
  20965. if (this.uvs) {
  20966. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  20967. }
  20968. if (this.uv2s) {
  20969. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updatable);
  20970. }
  20971. if (this.colors) {
  20972. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  20973. }
  20974. if (this.matricesIndices) {
  20975. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  20976. }
  20977. if (this.matricesWeights) {
  20978. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  20979. }
  20980. if (this.indices) {
  20981. meshOrGeometry.setIndices(this.indices);
  20982. }
  20983. };
  20984. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  20985. if (this.positions) {
  20986. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  20987. }
  20988. if (this.normals) {
  20989. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  20990. }
  20991. if (this.uvs) {
  20992. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  20993. }
  20994. if (this.uv2s) {
  20995. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updateExtends, makeItUnique);
  20996. }
  20997. if (this.colors) {
  20998. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  20999. }
  21000. if (this.matricesIndices) {
  21001. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  21002. }
  21003. if (this.matricesWeights) {
  21004. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  21005. }
  21006. if (this.indices) {
  21007. meshOrGeometry.setIndices(this.indices);
  21008. }
  21009. };
  21010. VertexData.prototype.transform = function (matrix) {
  21011. var transformed = BABYLON.Vector3.Zero();
  21012. if (this.positions) {
  21013. var position = BABYLON.Vector3.Zero();
  21014. for (var index = 0; index < this.positions.length; index += 3) {
  21015. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  21016. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  21017. this.positions[index] = transformed.x;
  21018. this.positions[index + 1] = transformed.y;
  21019. this.positions[index + 2] = transformed.z;
  21020. }
  21021. }
  21022. if (this.normals) {
  21023. var normal = BABYLON.Vector3.Zero();
  21024. for (index = 0; index < this.normals.length; index += 3) {
  21025. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  21026. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  21027. this.normals[index] = transformed.x;
  21028. this.normals[index + 1] = transformed.y;
  21029. this.normals[index + 2] = transformed.z;
  21030. }
  21031. }
  21032. };
  21033. VertexData.prototype.merge = function (other) {
  21034. if (other.indices) {
  21035. if (!this.indices) {
  21036. this.indices = [];
  21037. }
  21038. var offset = this.positions ? this.positions.length / 3 : 0;
  21039. for (var index = 0; index < other.indices.length; index++) {
  21040. this.indices.push(other.indices[index] + offset);
  21041. }
  21042. }
  21043. if (other.positions) {
  21044. if (!this.positions) {
  21045. this.positions = [];
  21046. }
  21047. for (index = 0; index < other.positions.length; index++) {
  21048. this.positions.push(other.positions[index]);
  21049. }
  21050. }
  21051. if (other.normals) {
  21052. if (!this.normals) {
  21053. this.normals = [];
  21054. }
  21055. for (index = 0; index < other.normals.length; index++) {
  21056. this.normals.push(other.normals[index]);
  21057. }
  21058. }
  21059. if (other.uvs) {
  21060. if (!this.uvs) {
  21061. this.uvs = [];
  21062. }
  21063. for (index = 0; index < other.uvs.length; index++) {
  21064. this.uvs.push(other.uvs[index]);
  21065. }
  21066. }
  21067. if (other.uv2s) {
  21068. if (!this.uv2s) {
  21069. this.uv2s = [];
  21070. }
  21071. for (index = 0; index < other.uv2s.length; index++) {
  21072. this.uv2s.push(other.uv2s[index]);
  21073. }
  21074. }
  21075. if (other.matricesIndices) {
  21076. if (!this.matricesIndices) {
  21077. this.matricesIndices = [];
  21078. }
  21079. for (index = 0; index < other.matricesIndices.length; index++) {
  21080. this.matricesIndices.push(other.matricesIndices[index]);
  21081. }
  21082. }
  21083. if (other.matricesWeights) {
  21084. if (!this.matricesWeights) {
  21085. this.matricesWeights = [];
  21086. }
  21087. for (index = 0; index < other.matricesWeights.length; index++) {
  21088. this.matricesWeights.push(other.matricesWeights[index]);
  21089. }
  21090. }
  21091. if (other.colors) {
  21092. if (!this.colors) {
  21093. this.colors = [];
  21094. }
  21095. for (index = 0; index < other.colors.length; index++) {
  21096. this.colors.push(other.colors[index]);
  21097. }
  21098. }
  21099. };
  21100. // Statics
  21101. VertexData.ExtractFromMesh = function (mesh) {
  21102. return VertexData._ExtractFrom(mesh);
  21103. };
  21104. VertexData.ExtractFromGeometry = function (geometry) {
  21105. return VertexData._ExtractFrom(geometry);
  21106. };
  21107. VertexData._ExtractFrom = function (meshOrGeometry) {
  21108. var result = new VertexData();
  21109. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  21110. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21111. }
  21112. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21113. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21114. }
  21115. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  21116. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind);
  21117. }
  21118. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  21119. result.uv2s = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  21120. }
  21121. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  21122. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  21123. }
  21124. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  21125. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  21126. }
  21127. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  21128. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  21129. }
  21130. result.indices = meshOrGeometry.getIndices();
  21131. return result;
  21132. };
  21133. VertexData.CreateRibbon = function (pathArray, closeArray, closePath, offset, sideOrientation) {
  21134. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  21135. closeArray = closeArray || false;
  21136. closePath = closePath || false;
  21137. var defaultOffset = Math.floor(pathArray[0].length / 2);
  21138. offset = offset || defaultOffset;
  21139. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  21140. var positions = [];
  21141. var indices = [];
  21142. var normals = [];
  21143. var uvs = [];
  21144. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  21145. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  21146. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  21147. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  21148. var minlg; // minimal length among all paths from pathArray
  21149. var lg = []; // array of path lengths : nb of vertex per path
  21150. var idx = []; // array of path indexes : index of each path (first vertex) in positions array
  21151. var p; // path iterator
  21152. var i; // point iterator
  21153. var j; // point iterator
  21154. // if single path in pathArray
  21155. if (pathArray.length < 2) {
  21156. var ar1 = [];
  21157. var ar2 = [];
  21158. for (i = 0; i < pathArray[0].length - offset; i++) {
  21159. ar1.push(pathArray[0][i]);
  21160. ar2.push(pathArray[0][i + offset]);
  21161. }
  21162. pathArray = [ar1, ar2];
  21163. }
  21164. // positions and horizontal distances (u)
  21165. var idc = 0;
  21166. minlg = pathArray[0].length;
  21167. for (p = 0; p < pathArray.length; p++) {
  21168. uTotalDistance[p] = 0;
  21169. us[p] = [0];
  21170. var path = pathArray[p];
  21171. var l = path.length;
  21172. minlg = (minlg < l) ? minlg : l;
  21173. lg[p] = l;
  21174. idx[p] = idc;
  21175. j = 0;
  21176. while (j < l) {
  21177. positions.push(path[j].x, path[j].y, path[j].z);
  21178. if (j > 0) {
  21179. var vectlg = path[j].subtract(path[j - 1]).length();
  21180. var dist = vectlg + uTotalDistance[p];
  21181. us[p].push(dist);
  21182. uTotalDistance[p] = dist;
  21183. }
  21184. j++;
  21185. }
  21186. if (closePath) {
  21187. vectlg = path[0].subtract(path[j - 1]).length();
  21188. dist = vectlg + uTotalDistance[p];
  21189. uTotalDistance[p] = dist;
  21190. }
  21191. idc += l;
  21192. }
  21193. for (i = 0; i < minlg; i++) {
  21194. vTotalDistance[i] = 0;
  21195. vs[i] = [0];
  21196. var path1;
  21197. var path2;
  21198. for (p = 0; p < pathArray.length - 1; p++) {
  21199. path1 = pathArray[p];
  21200. path2 = pathArray[p + 1];
  21201. vectlg = path2[i].subtract(path1[i]).length();
  21202. dist = vectlg + vTotalDistance[i];
  21203. vs[i].push(dist);
  21204. vTotalDistance[i] = dist;
  21205. }
  21206. if (closeArray) {
  21207. path1 = pathArray[p];
  21208. path2 = pathArray[0];
  21209. vectlg = path2[i].subtract(path1[i]).length();
  21210. dist = vectlg + vTotalDistance[i];
  21211. vTotalDistance[i] = dist;
  21212. }
  21213. }
  21214. // uvs
  21215. var u;
  21216. var v;
  21217. for (p = 0; p < pathArray.length; p++) {
  21218. for (i = 0; i < minlg; i++) {
  21219. u = us[p][i] / uTotalDistance[p];
  21220. v = vs[i][p] / vTotalDistance[i];
  21221. uvs.push(u, v);
  21222. }
  21223. }
  21224. // indices
  21225. p = 0; // path index
  21226. var pi = 0; // positions array index
  21227. var l1 = lg[p] - 1; // path1 length
  21228. var l2 = lg[p + 1] - 1; // path2 length
  21229. var min = (l1 < l2) ? l1 : l2; // current path stop index
  21230. var shft = idx[1] - idx[0]; // shift
  21231. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate
  21232. var t1; // two consecutive triangles, so 4 points : point1
  21233. var t2; // point2
  21234. var t3; // point3
  21235. var t4; // point4
  21236. while (pi <= min && p < path1nb) {
  21237. // 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
  21238. t1 = pi;
  21239. t2 = pi + shft;
  21240. t3 = pi + 1;
  21241. t4 = pi + shft + 1;
  21242. indices.push(pi, pi + shft, pi + 1);
  21243. indices.push(pi + shft + 1, pi + 1, pi + shft);
  21244. pi += 1;
  21245. if (pi === min) {
  21246. if (closePath) {
  21247. indices.push(pi, pi + shft, idx[p]);
  21248. indices.push(idx[p] + shft, idx[p], pi + shft);
  21249. t3 = idx[p];
  21250. t4 = idx[p] + shft;
  21251. }
  21252. p++;
  21253. if (p === lg.length - 1) {
  21254. shft = idx[0] - idx[p];
  21255. l1 = lg[p] - 1;
  21256. l2 = lg[0] - 1;
  21257. }
  21258. else {
  21259. shft = idx[p + 1] - idx[p];
  21260. l1 = lg[p] - 1;
  21261. l2 = lg[p + 1] - 1;
  21262. }
  21263. pi = idx[p];
  21264. min = (l1 < l2) ? l1 + pi : l2 + pi;
  21265. }
  21266. }
  21267. // normals
  21268. VertexData.ComputeNormals(positions, indices, normals);
  21269. // sides
  21270. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  21271. // Result
  21272. var vertexData = new VertexData();
  21273. vertexData.indices = indices;
  21274. vertexData.positions = positions;
  21275. vertexData.normals = normals;
  21276. vertexData.uvs = uvs;
  21277. return vertexData;
  21278. };
  21279. VertexData.CreateBox = function (size, sideOrientation) {
  21280. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  21281. var normalsSource = [
  21282. new BABYLON.Vector3(0, 0, 1),
  21283. new BABYLON.Vector3(0, 0, -1),
  21284. new BABYLON.Vector3(1, 0, 0),
  21285. new BABYLON.Vector3(-1, 0, 0),
  21286. new BABYLON.Vector3(0, 1, 0),
  21287. new BABYLON.Vector3(0, -1, 0)
  21288. ];
  21289. var indices = [];
  21290. var positions = [];
  21291. var normals = [];
  21292. var uvs = [];
  21293. size = size || 1;
  21294. for (var index = 0; index < normalsSource.length; index++) {
  21295. var normal = normalsSource[index];
  21296. // Get two vectors perpendicular to the face normal and to each other.
  21297. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  21298. var side2 = BABYLON.Vector3.Cross(normal, side1);
  21299. // Six indices (two triangles) per face.
  21300. var verticesLength = positions.length / 3;
  21301. indices.push(verticesLength);
  21302. indices.push(verticesLength + 1);
  21303. indices.push(verticesLength + 2);
  21304. indices.push(verticesLength);
  21305. indices.push(verticesLength + 2);
  21306. indices.push(verticesLength + 3);
  21307. // Four vertices per face.
  21308. var vertex = normal.subtract(side1).subtract(side2).scale(size / 2);
  21309. positions.push(vertex.x, vertex.y, vertex.z);
  21310. normals.push(normal.x, normal.y, normal.z);
  21311. uvs.push(1.0, 1.0);
  21312. vertex = normal.subtract(side1).add(side2).scale(size / 2);
  21313. positions.push(vertex.x, vertex.y, vertex.z);
  21314. normals.push(normal.x, normal.y, normal.z);
  21315. uvs.push(0.0, 1.0);
  21316. vertex = normal.add(side1).add(side2).scale(size / 2);
  21317. positions.push(vertex.x, vertex.y, vertex.z);
  21318. normals.push(normal.x, normal.y, normal.z);
  21319. uvs.push(0.0, 0.0);
  21320. vertex = normal.add(side1).subtract(side2).scale(size / 2);
  21321. positions.push(vertex.x, vertex.y, vertex.z);
  21322. normals.push(normal.x, normal.y, normal.z);
  21323. uvs.push(1.0, 0.0);
  21324. }
  21325. // sides
  21326. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  21327. // Result
  21328. var vertexData = new VertexData();
  21329. vertexData.indices = indices;
  21330. vertexData.positions = positions;
  21331. vertexData.normals = normals;
  21332. vertexData.uvs = uvs;
  21333. return vertexData;
  21334. };
  21335. VertexData.CreateSphere = function (segments, diameter, sideOrientation) {
  21336. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  21337. segments = segments || 32;
  21338. diameter = diameter || 1;
  21339. var radius = diameter / 2;
  21340. var totalZRotationSteps = 2 + segments;
  21341. var totalYRotationSteps = 2 * totalZRotationSteps;
  21342. var indices = [];
  21343. var positions = [];
  21344. var normals = [];
  21345. var uvs = [];
  21346. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  21347. var normalizedZ = zRotationStep / totalZRotationSteps;
  21348. var angleZ = (normalizedZ * Math.PI);
  21349. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  21350. var normalizedY = yRotationStep / totalYRotationSteps;
  21351. var angleY = normalizedY * Math.PI * 2;
  21352. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  21353. var rotationY = BABYLON.Matrix.RotationY(angleY);
  21354. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  21355. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  21356. var vertex = complete.scale(radius);
  21357. var normal = BABYLON.Vector3.Normalize(vertex);
  21358. positions.push(vertex.x, vertex.y, vertex.z);
  21359. normals.push(normal.x, normal.y, normal.z);
  21360. uvs.push(normalizedZ, normalizedY);
  21361. }
  21362. if (zRotationStep > 0) {
  21363. var verticesCount = positions.length / 3;
  21364. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  21365. indices.push((firstIndex));
  21366. indices.push((firstIndex + 1));
  21367. indices.push(firstIndex + totalYRotationSteps + 1);
  21368. indices.push((firstIndex + totalYRotationSteps + 1));
  21369. indices.push((firstIndex + 1));
  21370. indices.push((firstIndex + totalYRotationSteps + 2));
  21371. }
  21372. }
  21373. }
  21374. // Sides
  21375. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  21376. // Result
  21377. var vertexData = new VertexData();
  21378. vertexData.indices = indices;
  21379. vertexData.positions = positions;
  21380. vertexData.normals = normals;
  21381. vertexData.uvs = uvs;
  21382. return vertexData;
  21383. };
  21384. VertexData.CreateCylinder = function (height, diameterTop, diameterBottom, tessellation, subdivisions, sideOrientation) {
  21385. if (subdivisions === void 0) { subdivisions = 1; }
  21386. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  21387. var radiusTop = diameterTop / 2;
  21388. var radiusBottom = diameterBottom / 2;
  21389. var indices = [];
  21390. var positions = [];
  21391. var normals = [];
  21392. var uvs = [];
  21393. height = height || 1;
  21394. diameterTop = diameterTop || 0.5;
  21395. diameterBottom = diameterBottom || 1;
  21396. tessellation = tessellation || 16;
  21397. subdivisions = subdivisions || 1;
  21398. subdivisions = (subdivisions < 1) ? 1 : subdivisions;
  21399. var getCircleVector = function (i) {
  21400. var angle = (i * 2.0 * Math.PI / tessellation);
  21401. var dx = Math.cos(angle);
  21402. var dz = Math.sin(angle);
  21403. return new BABYLON.Vector3(dx, 0, dz);
  21404. };
  21405. var createCylinderCap = function (isTop) {
  21406. var radius = isTop ? radiusTop : radiusBottom;
  21407. if (radius === 0) {
  21408. return;
  21409. }
  21410. var vbase = positions.length / 3;
  21411. var offset = new BABYLON.Vector3(0, height / 2, 0);
  21412. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  21413. if (!isTop) {
  21414. offset.scaleInPlace(-1);
  21415. textureScale.x = -textureScale.x;
  21416. }
  21417. for (var i = 0; i < tessellation; i++) {
  21418. var circleVector = getCircleVector(i);
  21419. var position = circleVector.scale(radius).add(offset);
  21420. var textureCoordinate = new BABYLON.Vector2(circleVector.x * textureScale.x + 0.5, circleVector.z * textureScale.y + 0.5);
  21421. positions.push(position.x, position.y, position.z);
  21422. uvs.push(textureCoordinate.x, textureCoordinate.y);
  21423. }
  21424. for (i = 0; i < tessellation - 2; i++) {
  21425. if (!isTop) {
  21426. indices.push(vbase);
  21427. indices.push(vbase + (i + 2) % tessellation);
  21428. indices.push(vbase + (i + 1) % tessellation);
  21429. }
  21430. else {
  21431. indices.push(vbase);
  21432. indices.push(vbase + (i + 1) % tessellation);
  21433. indices.push(vbase + (i + 2) % tessellation);
  21434. }
  21435. }
  21436. };
  21437. var base = new BABYLON.Vector3(0, -1, 0).scale(height / 2);
  21438. var offset = new BABYLON.Vector3(0, 1, 0).scale(height / subdivisions);
  21439. var stride = tessellation + 1;
  21440. for (var i = 0; i <= tessellation; i++) {
  21441. var circleVector = getCircleVector(i);
  21442. var textureCoordinate = new BABYLON.Vector2(i / tessellation, 0);
  21443. var position, radius = radiusBottom;
  21444. for (var s = 0; s <= subdivisions; s++) {
  21445. // Update variables
  21446. position = circleVector.scale(radius);
  21447. position.addInPlace(base.add(offset.scale(s)));
  21448. textureCoordinate.y += 1 / subdivisions;
  21449. radius += (radiusTop - radiusBottom) / subdivisions;
  21450. // Push in arrays
  21451. positions.push(position.x, position.y, position.z);
  21452. uvs.push(textureCoordinate.x, textureCoordinate.y);
  21453. }
  21454. }
  21455. subdivisions += 1;
  21456. for (s = 0; s < subdivisions - 1; s++) {
  21457. for (i = 0; i <= tessellation; i++) {
  21458. indices.push(i * subdivisions + s);
  21459. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  21460. indices.push(i * subdivisions + (s + 1));
  21461. indices.push(i * subdivisions + (s + 1));
  21462. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  21463. indices.push((i * subdivisions + (s + subdivisions + 1)) % (stride * subdivisions));
  21464. }
  21465. }
  21466. // Create flat triangle fan caps to seal the top and bottom.
  21467. createCylinderCap(true);
  21468. createCylinderCap(false);
  21469. // Normals
  21470. VertexData.ComputeNormals(positions, indices, normals);
  21471. // Sides
  21472. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  21473. // Result
  21474. var vertexData = new VertexData();
  21475. vertexData.indices = indices;
  21476. vertexData.positions = positions;
  21477. vertexData.normals = normals;
  21478. vertexData.uvs = uvs;
  21479. return vertexData;
  21480. };
  21481. VertexData.CreateTorus = function (diameter, thickness, tessellation, sideOrientation) {
  21482. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  21483. var indices = [];
  21484. var positions = [];
  21485. var normals = [];
  21486. var uvs = [];
  21487. diameter = diameter || 1;
  21488. thickness = thickness || 0.5;
  21489. tessellation = tessellation || 16;
  21490. var stride = tessellation + 1;
  21491. for (var i = 0; i <= tessellation; i++) {
  21492. var u = i / tessellation;
  21493. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  21494. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  21495. for (var j = 0; j <= tessellation; j++) {
  21496. var v = 1 - j / tessellation;
  21497. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  21498. var dx = Math.cos(innerAngle);
  21499. var dy = Math.sin(innerAngle);
  21500. // Create a vertex.
  21501. var normal = new BABYLON.Vector3(dx, dy, 0);
  21502. var position = normal.scale(thickness / 2);
  21503. var textureCoordinate = new BABYLON.Vector2(u, v);
  21504. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  21505. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  21506. positions.push(position.x, position.y, position.z);
  21507. normals.push(normal.x, normal.y, normal.z);
  21508. uvs.push(textureCoordinate.x, textureCoordinate.y);
  21509. // And create indices for two triangles.
  21510. var nextI = (i + 1) % stride;
  21511. var nextJ = (j + 1) % stride;
  21512. indices.push(i * stride + j);
  21513. indices.push(i * stride + nextJ);
  21514. indices.push(nextI * stride + j);
  21515. indices.push(i * stride + nextJ);
  21516. indices.push(nextI * stride + nextJ);
  21517. indices.push(nextI * stride + j);
  21518. }
  21519. }
  21520. // Sides
  21521. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  21522. // Result
  21523. var vertexData = new VertexData();
  21524. vertexData.indices = indices;
  21525. vertexData.positions = positions;
  21526. vertexData.normals = normals;
  21527. vertexData.uvs = uvs;
  21528. return vertexData;
  21529. };
  21530. VertexData.CreateLines = function (points) {
  21531. var indices = [];
  21532. var positions = [];
  21533. for (var index = 0; index < points.length; index++) {
  21534. positions.push(points[index].x, points[index].y, points[index].z);
  21535. if (index > 0) {
  21536. indices.push(index - 1);
  21537. indices.push(index);
  21538. }
  21539. }
  21540. // Result
  21541. var vertexData = new VertexData();
  21542. vertexData.indices = indices;
  21543. vertexData.positions = positions;
  21544. return vertexData;
  21545. };
  21546. VertexData.CreateGround = function (width, height, subdivisions) {
  21547. var indices = [];
  21548. var positions = [];
  21549. var normals = [];
  21550. var uvs = [];
  21551. var row, col;
  21552. width = width || 1;
  21553. height = height || 1;
  21554. subdivisions = subdivisions || 1;
  21555. for (row = 0; row <= subdivisions; row++) {
  21556. for (col = 0; col <= subdivisions; col++) {
  21557. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  21558. var normal = new BABYLON.Vector3(0, 1.0, 0);
  21559. positions.push(position.x, position.y, position.z);
  21560. normals.push(normal.x, normal.y, normal.z);
  21561. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  21562. }
  21563. }
  21564. for (row = 0; row < subdivisions; row++) {
  21565. for (col = 0; col < subdivisions; col++) {
  21566. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  21567. indices.push(col + 1 + row * (subdivisions + 1));
  21568. indices.push(col + row * (subdivisions + 1));
  21569. indices.push(col + (row + 1) * (subdivisions + 1));
  21570. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  21571. indices.push(col + row * (subdivisions + 1));
  21572. }
  21573. }
  21574. // Result
  21575. var vertexData = new VertexData();
  21576. vertexData.indices = indices;
  21577. vertexData.positions = positions;
  21578. vertexData.normals = normals;
  21579. vertexData.uvs = uvs;
  21580. return vertexData;
  21581. };
  21582. VertexData.CreateTiledGround = function (xmin, zmin, xmax, zmax, subdivisions, precision) {
  21583. if (subdivisions === void 0) { subdivisions = { w: 1, h: 1 }; }
  21584. if (precision === void 0) { precision = { w: 1, h: 1 }; }
  21585. var indices = [];
  21586. var positions = [];
  21587. var normals = [];
  21588. var uvs = [];
  21589. var row, col, tileRow, tileCol;
  21590. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  21591. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  21592. precision.w = (precision.w < 1) ? 1 : precision.w;
  21593. precision.h = (precision.h < 1) ? 1 : precision.h;
  21594. var tileSize = {
  21595. 'w': (xmax - xmin) / subdivisions.w,
  21596. 'h': (zmax - zmin) / subdivisions.h
  21597. };
  21598. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  21599. // Indices
  21600. var base = positions.length / 3;
  21601. var rowLength = precision.w + 1;
  21602. for (row = 0; row < precision.h; row++) {
  21603. for (col = 0; col < precision.w; col++) {
  21604. var square = [
  21605. base + col + row * rowLength,
  21606. base + (col + 1) + row * rowLength,
  21607. base + (col + 1) + (row + 1) * rowLength,
  21608. base + col + (row + 1) * rowLength
  21609. ];
  21610. indices.push(square[1]);
  21611. indices.push(square[2]);
  21612. indices.push(square[3]);
  21613. indices.push(square[0]);
  21614. indices.push(square[1]);
  21615. indices.push(square[3]);
  21616. }
  21617. }
  21618. // Position, normals and uvs
  21619. var position = BABYLON.Vector3.Zero();
  21620. var normal = new BABYLON.Vector3(0, 1.0, 0);
  21621. for (row = 0; row <= precision.h; row++) {
  21622. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  21623. for (col = 0; col <= precision.w; col++) {
  21624. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  21625. position.y = 0;
  21626. positions.push(position.x, position.y, position.z);
  21627. normals.push(normal.x, normal.y, normal.z);
  21628. uvs.push(col / precision.w, row / precision.h);
  21629. }
  21630. }
  21631. }
  21632. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  21633. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  21634. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  21635. }
  21636. }
  21637. // Result
  21638. var vertexData = new VertexData();
  21639. vertexData.indices = indices;
  21640. vertexData.positions = positions;
  21641. vertexData.normals = normals;
  21642. vertexData.uvs = uvs;
  21643. return vertexData;
  21644. };
  21645. VertexData.CreateGroundFromHeightMap = function (width, height, subdivisions, minHeight, maxHeight, buffer, bufferWidth, bufferHeight) {
  21646. var indices = [];
  21647. var positions = [];
  21648. var normals = [];
  21649. var uvs = [];
  21650. var row, col;
  21651. for (row = 0; row <= subdivisions; row++) {
  21652. for (col = 0; col <= subdivisions; col++) {
  21653. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  21654. // Compute height
  21655. var heightMapX = (((position.x + width / 2) / width) * (bufferWidth - 1)) | 0;
  21656. var heightMapY = ((1.0 - (position.z + height / 2) / height) * (bufferHeight - 1)) | 0;
  21657. var pos = (heightMapX + heightMapY * bufferWidth) * 4;
  21658. var r = buffer[pos] / 255.0;
  21659. var g = buffer[pos + 1] / 255.0;
  21660. var b = buffer[pos + 2] / 255.0;
  21661. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  21662. position.y = minHeight + (maxHeight - minHeight) * gradient;
  21663. // Add vertex
  21664. positions.push(position.x, position.y, position.z);
  21665. normals.push(0, 0, 0);
  21666. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  21667. }
  21668. }
  21669. for (row = 0; row < subdivisions; row++) {
  21670. for (col = 0; col < subdivisions; col++) {
  21671. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  21672. indices.push(col + 1 + row * (subdivisions + 1));
  21673. indices.push(col + row * (subdivisions + 1));
  21674. indices.push(col + (row + 1) * (subdivisions + 1));
  21675. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  21676. indices.push(col + row * (subdivisions + 1));
  21677. }
  21678. }
  21679. // Normals
  21680. VertexData.ComputeNormals(positions, indices, normals);
  21681. // Result
  21682. var vertexData = new VertexData();
  21683. vertexData.indices = indices;
  21684. vertexData.positions = positions;
  21685. vertexData.normals = normals;
  21686. vertexData.uvs = uvs;
  21687. return vertexData;
  21688. };
  21689. VertexData.CreatePlane = function (size, sideOrientation) {
  21690. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  21691. var indices = [];
  21692. var positions = [];
  21693. var normals = [];
  21694. var uvs = [];
  21695. size = size || 1;
  21696. // Vertices
  21697. var halfSize = size / 2.0;
  21698. positions.push(-halfSize, -halfSize, 0);
  21699. normals.push(0, 0, -1.0);
  21700. uvs.push(0.0, 0.0);
  21701. positions.push(halfSize, -halfSize, 0);
  21702. normals.push(0, 0, -1.0);
  21703. uvs.push(1.0, 0.0);
  21704. positions.push(halfSize, halfSize, 0);
  21705. normals.push(0, 0, -1.0);
  21706. uvs.push(1.0, 1.0);
  21707. positions.push(-halfSize, halfSize, 0);
  21708. normals.push(0, 0, -1.0);
  21709. uvs.push(0.0, 1.0);
  21710. // Indices
  21711. indices.push(0);
  21712. indices.push(1);
  21713. indices.push(2);
  21714. indices.push(0);
  21715. indices.push(2);
  21716. indices.push(3);
  21717. // Sides
  21718. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  21719. // Result
  21720. var vertexData = new VertexData();
  21721. vertexData.indices = indices;
  21722. vertexData.positions = positions;
  21723. vertexData.normals = normals;
  21724. vertexData.uvs = uvs;
  21725. return vertexData;
  21726. };
  21727. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  21728. VertexData.CreateTorusKnot = function (radius, tube, radialSegments, tubularSegments, p, q, sideOrientation) {
  21729. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  21730. var indices = [];
  21731. var positions = [];
  21732. var normals = [];
  21733. var uvs = [];
  21734. radius = radius || 2;
  21735. tube = tube || 0.5;
  21736. radialSegments = radialSegments || 32;
  21737. tubularSegments = tubularSegments || 32;
  21738. p = p || 2;
  21739. q = q || 3;
  21740. // Helper
  21741. var getPos = function (angle) {
  21742. var cu = Math.cos(angle);
  21743. var su = Math.sin(angle);
  21744. var quOverP = q / p * angle;
  21745. var cs = Math.cos(quOverP);
  21746. var tx = radius * (2 + cs) * 0.5 * cu;
  21747. var ty = radius * (2 + cs) * su * 0.5;
  21748. var tz = radius * Math.sin(quOverP) * 0.5;
  21749. return new BABYLON.Vector3(tx, ty, tz);
  21750. };
  21751. for (var i = 0; i <= radialSegments; i++) {
  21752. var modI = i % radialSegments;
  21753. var u = modI / radialSegments * 2 * p * Math.PI;
  21754. var p1 = getPos(u);
  21755. var p2 = getPos(u + 0.01);
  21756. var tang = p2.subtract(p1);
  21757. var n = p2.add(p1);
  21758. var bitan = BABYLON.Vector3.Cross(tang, n);
  21759. n = BABYLON.Vector3.Cross(bitan, tang);
  21760. bitan.normalize();
  21761. n.normalize();
  21762. for (var j = 0; j < tubularSegments; j++) {
  21763. var modJ = j % tubularSegments;
  21764. var v = modJ / tubularSegments * 2 * Math.PI;
  21765. var cx = -tube * Math.cos(v);
  21766. var cy = tube * Math.sin(v);
  21767. positions.push(p1.x + cx * n.x + cy * bitan.x);
  21768. positions.push(p1.y + cx * n.y + cy * bitan.y);
  21769. positions.push(p1.z + cx * n.z + cy * bitan.z);
  21770. uvs.push(i / radialSegments);
  21771. uvs.push(j / tubularSegments);
  21772. }
  21773. }
  21774. for (i = 0; i < radialSegments; i++) {
  21775. for (j = 0; j < tubularSegments; j++) {
  21776. var jNext = (j + 1) % tubularSegments;
  21777. var a = i * tubularSegments + j;
  21778. var b = (i + 1) * tubularSegments + j;
  21779. var c = (i + 1) * tubularSegments + jNext;
  21780. var d = i * tubularSegments + jNext;
  21781. indices.push(d);
  21782. indices.push(b);
  21783. indices.push(a);
  21784. indices.push(d);
  21785. indices.push(c);
  21786. indices.push(b);
  21787. }
  21788. }
  21789. // Normals
  21790. VertexData.ComputeNormals(positions, indices, normals);
  21791. // Sides
  21792. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  21793. // Result
  21794. var vertexData = new VertexData();
  21795. vertexData.indices = indices;
  21796. vertexData.positions = positions;
  21797. vertexData.normals = normals;
  21798. vertexData.uvs = uvs;
  21799. return vertexData;
  21800. };
  21801. // Tools
  21802. VertexData.ComputeNormals = function (positions, indices, normals) {
  21803. var positionVectors = [];
  21804. var facesOfVertices = [];
  21805. var index;
  21806. for (index = 0; index < positions.length; index += 3) {
  21807. var vector3 = new BABYLON.Vector3(positions[index], positions[index + 1], positions[index + 2]);
  21808. positionVectors.push(vector3);
  21809. facesOfVertices.push([]);
  21810. }
  21811. // Compute normals
  21812. var facesNormals = [];
  21813. for (index = 0; index < indices.length / 3; index++) {
  21814. var i1 = indices[index * 3];
  21815. var i2 = indices[index * 3 + 1];
  21816. var i3 = indices[index * 3 + 2];
  21817. var p1 = positionVectors[i1];
  21818. var p2 = positionVectors[i2];
  21819. var p3 = positionVectors[i3];
  21820. var p1p2 = p1.subtract(p2);
  21821. var p3p2 = p3.subtract(p2);
  21822. facesNormals[index] = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  21823. facesOfVertices[i1].push(index);
  21824. facesOfVertices[i2].push(index);
  21825. facesOfVertices[i3].push(index);
  21826. }
  21827. for (index = 0; index < positionVectors.length; index++) {
  21828. var faces = facesOfVertices[index];
  21829. var normal = BABYLON.Vector3.Zero();
  21830. for (var faceIndex = 0; faceIndex < faces.length; faceIndex++) {
  21831. normal.addInPlace(facesNormals[faces[faceIndex]]);
  21832. }
  21833. normal = BABYLON.Vector3.Normalize(normal.scale(1.0 / faces.length));
  21834. normals[index * 3] = normal.x;
  21835. normals[index * 3 + 1] = normal.y;
  21836. normals[index * 3 + 2] = normal.z;
  21837. }
  21838. };
  21839. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  21840. var li = indices.length;
  21841. var ln = normals.length;
  21842. var i;
  21843. var n;
  21844. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  21845. switch (sideOrientation) {
  21846. case BABYLON.Mesh.FRONTSIDE:
  21847. break;
  21848. case BABYLON.Mesh.BACKSIDE:
  21849. var tmp;
  21850. for (i = 0; i < li; i += 3) {
  21851. tmp = indices[i];
  21852. indices[i] = indices[i + 2];
  21853. indices[i + 2] = tmp;
  21854. }
  21855. for (n = 0; n < ln; n++) {
  21856. normals[n] = -normals[n];
  21857. }
  21858. break;
  21859. case BABYLON.Mesh.DOUBLESIDE:
  21860. // positions
  21861. var lp = positions.length;
  21862. var l = lp / 3;
  21863. for (var p = 0; p < lp; p++) {
  21864. positions[lp + p] = positions[p];
  21865. }
  21866. for (i = 0; i < li; i += 3) {
  21867. indices[i + li] = indices[i + 2] + l;
  21868. indices[i + 1 + li] = indices[i + 1] + l;
  21869. indices[i + 2 + li] = indices[i] + l;
  21870. }
  21871. for (n = 0; n < ln; n++) {
  21872. normals[ln + n] = -normals[n];
  21873. }
  21874. // uvs
  21875. var lu = uvs.length;
  21876. for (var u = 0; u < lu; u++) {
  21877. uvs[u + lu] = uvs[u];
  21878. }
  21879. break;
  21880. }
  21881. };
  21882. return VertexData;
  21883. })();
  21884. BABYLON.VertexData = VertexData;
  21885. })(BABYLON || (BABYLON = {}));
  21886. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  21887. var BABYLON;
  21888. (function (BABYLON) {
  21889. var buildCamera = function (that, name) {
  21890. that._leftCamera.isIntermediate = true;
  21891. that.subCameras.push(that._leftCamera);
  21892. that.subCameras.push(that._rightCamera);
  21893. that._leftTexture = new BABYLON.PassPostProcess(name + "_leftTexture", 1.0, that._leftCamera);
  21894. that._anaglyphPostProcess = new BABYLON.AnaglyphPostProcess(name + "_anaglyph", 1.0, that._rightCamera);
  21895. that._anaglyphPostProcess.onApply = function (effect) {
  21896. effect.setTextureFromPostProcess("leftSampler", that._leftTexture);
  21897. };
  21898. that._update();
  21899. };
  21900. var AnaglyphArcRotateCamera = (function (_super) {
  21901. __extends(AnaglyphArcRotateCamera, _super);
  21902. // ANY
  21903. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, eyeSpace, scene) {
  21904. _super.call(this, name, alpha, beta, radius, target, scene);
  21905. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  21906. this._leftCamera = new BABYLON.ArcRotateCamera(name + "_left", alpha - this._eyeSpace, beta, radius, target, scene);
  21907. this._rightCamera = new BABYLON.ArcRotateCamera(name + "_right", alpha + this._eyeSpace, beta, radius, target, scene);
  21908. buildCamera(this, name);
  21909. }
  21910. AnaglyphArcRotateCamera.prototype._update = function () {
  21911. this._updateCamera(this._leftCamera);
  21912. this._updateCamera(this._rightCamera);
  21913. this._leftCamera.alpha = this.alpha - this._eyeSpace;
  21914. this._rightCamera.alpha = this.alpha + this._eyeSpace;
  21915. _super.prototype._update.call(this);
  21916. };
  21917. AnaglyphArcRotateCamera.prototype._updateCamera = function (camera) {
  21918. camera.beta = this.beta;
  21919. camera.radius = this.radius;
  21920. camera.minZ = this.minZ;
  21921. camera.maxZ = this.maxZ;
  21922. camera.fov = this.fov;
  21923. camera.target = this.target;
  21924. };
  21925. return AnaglyphArcRotateCamera;
  21926. })(BABYLON.ArcRotateCamera);
  21927. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  21928. var AnaglyphFreeCamera = (function (_super) {
  21929. __extends(AnaglyphFreeCamera, _super);
  21930. function AnaglyphFreeCamera(name, position, eyeSpace, scene) {
  21931. _super.call(this, name, position, scene);
  21932. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  21933. this._transformMatrix = new BABYLON.Matrix();
  21934. this._leftCamera = new BABYLON.FreeCamera(name + "_left", position.clone(), scene);
  21935. this._rightCamera = new BABYLON.FreeCamera(name + "_right", position.clone(), scene);
  21936. buildCamera(this, name);
  21937. }
  21938. AnaglyphFreeCamera.prototype._getSubCameraPosition = function (eyeSpace, result) {
  21939. var target = this.getTarget();
  21940. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(eyeSpace), this._transformMatrix);
  21941. this._transformMatrix = this._transformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  21942. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._transformMatrix, result);
  21943. };
  21944. AnaglyphFreeCamera.prototype._update = function () {
  21945. this._getSubCameraPosition(-this._eyeSpace, this._leftCamera.position);
  21946. this._getSubCameraPosition(this._eyeSpace, this._rightCamera.position);
  21947. this._updateCamera(this._leftCamera);
  21948. this._updateCamera(this._rightCamera);
  21949. _super.prototype._update.call(this);
  21950. };
  21951. AnaglyphFreeCamera.prototype._updateCamera = function (camera) {
  21952. camera.minZ = this.minZ;
  21953. camera.maxZ = this.maxZ;
  21954. camera.fov = this.fov;
  21955. camera.viewport = this.viewport;
  21956. camera.setTarget(this.getTarget());
  21957. };
  21958. return AnaglyphFreeCamera;
  21959. })(BABYLON.FreeCamera);
  21960. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  21961. })(BABYLON || (BABYLON = {}));
  21962. //# sourceMappingURL=babylon.anaglyphCamera.js.map
  21963. var BABYLON;
  21964. (function (BABYLON) {
  21965. var AnaglyphPostProcess = (function (_super) {
  21966. __extends(AnaglyphPostProcess, _super);
  21967. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  21968. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  21969. }
  21970. return AnaglyphPostProcess;
  21971. })(BABYLON.PostProcess);
  21972. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  21973. })(BABYLON || (BABYLON = {}));
  21974. //# sourceMappingURL=babylon.anaglyphPostProcess.js.mapvar BABYLON;
  21975. (function (BABYLON) {
  21976. var Tags = (function () {
  21977. function Tags() {
  21978. }
  21979. Tags.EnableFor = function (obj) {
  21980. obj._tags = obj._tags || {};
  21981. obj.hasTags = function () {
  21982. return Tags.HasTags(obj);
  21983. };
  21984. obj.addTags = function (tagsString) {
  21985. return Tags.AddTagsTo(obj, tagsString);
  21986. };
  21987. obj.removeTags = function (tagsString) {
  21988. return Tags.RemoveTagsFrom(obj, tagsString);
  21989. };
  21990. obj.matchesTagsQuery = function (tagsQuery) {
  21991. return Tags.MatchesQuery(obj, tagsQuery);
  21992. };
  21993. };
  21994. Tags.DisableFor = function (obj) {
  21995. delete obj._tags;
  21996. delete obj.hasTags;
  21997. delete obj.addTags;
  21998. delete obj.removeTags;
  21999. delete obj.matchesTagsQuery;
  22000. };
  22001. Tags.HasTags = function (obj) {
  22002. if (!obj._tags) {
  22003. return false;
  22004. }
  22005. return !BABYLON.Tools.IsEmpty(obj._tags);
  22006. };
  22007. Tags.GetTags = function (obj) {
  22008. if (!obj._tags) {
  22009. return null;
  22010. }
  22011. return obj._tags;
  22012. };
  22013. // the tags 'true' and 'false' are reserved and cannot be used as tags
  22014. // a tag cannot start with '||', '&&', and '!'
  22015. // it cannot contain whitespaces
  22016. Tags.AddTagsTo = function (obj, tagsString) {
  22017. if (!tagsString) {
  22018. return;
  22019. }
  22020. var tags = tagsString.split(" ");
  22021. for (var t in tags) {
  22022. Tags._AddTagTo(obj, tags[t]);
  22023. }
  22024. };
  22025. Tags._AddTagTo = function (obj, tag) {
  22026. tag = tag.trim();
  22027. if (tag === "" || tag === "true" || tag === "false") {
  22028. return;
  22029. }
  22030. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  22031. return;
  22032. }
  22033. Tags.EnableFor(obj);
  22034. obj._tags[tag] = true;
  22035. };
  22036. Tags.RemoveTagsFrom = function (obj, tagsString) {
  22037. if (!Tags.HasTags(obj)) {
  22038. return;
  22039. }
  22040. var tags = tagsString.split(" ");
  22041. for (var t in tags) {
  22042. Tags._RemoveTagFrom(obj, tags[t]);
  22043. }
  22044. };
  22045. Tags._RemoveTagFrom = function (obj, tag) {
  22046. delete obj._tags[tag];
  22047. };
  22048. Tags.MatchesQuery = function (obj, tagsQuery) {
  22049. if (tagsQuery === undefined) {
  22050. return true;
  22051. }
  22052. if (tagsQuery === "") {
  22053. return Tags.HasTags(obj);
  22054. }
  22055. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  22056. };
  22057. return Tags;
  22058. })();
  22059. BABYLON.Tags = Tags;
  22060. })(BABYLON || (BABYLON = {}));
  22061. //# sourceMappingURL=babylon.tags.js.mapvar BABYLON;
  22062. (function (BABYLON) {
  22063. var Internals;
  22064. (function (Internals) {
  22065. var AndOrNotEvaluator = (function () {
  22066. function AndOrNotEvaluator() {
  22067. }
  22068. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  22069. if (!query.match(/\([^\(\)]*\)/g)) {
  22070. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  22071. }
  22072. else {
  22073. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  22074. // remove parenthesis
  22075. r = r.slice(1, r.length - 1);
  22076. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  22077. });
  22078. }
  22079. if (query === "true") {
  22080. return true;
  22081. }
  22082. if (query === "false") {
  22083. return false;
  22084. }
  22085. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  22086. };
  22087. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  22088. evaluateCallback = evaluateCallback || (function (r) {
  22089. return r === "true" ? true : false;
  22090. });
  22091. var result;
  22092. var or = parenthesisContent.split("||");
  22093. for (var i in or) {
  22094. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  22095. var and = ori.split("&&");
  22096. if (and.length > 1) {
  22097. for (var j = 0; j < and.length; ++j) {
  22098. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  22099. if (andj !== "true" && andj !== "false") {
  22100. if (andj[0] === "!") {
  22101. result = !evaluateCallback(andj.substring(1));
  22102. }
  22103. else {
  22104. result = evaluateCallback(andj);
  22105. }
  22106. }
  22107. else {
  22108. result = andj === "true" ? true : false;
  22109. }
  22110. if (!result) {
  22111. ori = "false";
  22112. break;
  22113. }
  22114. }
  22115. }
  22116. if (result || ori === "true") {
  22117. result = true;
  22118. break;
  22119. }
  22120. // result equals false (or undefined)
  22121. if (ori !== "true" && ori !== "false") {
  22122. if (ori[0] === "!") {
  22123. result = !evaluateCallback(ori.substring(1));
  22124. }
  22125. else {
  22126. result = evaluateCallback(ori);
  22127. }
  22128. }
  22129. else {
  22130. result = ori === "true" ? true : false;
  22131. }
  22132. }
  22133. // the whole parenthesis scope is replaced by 'true' or 'false'
  22134. return result ? "true" : "false";
  22135. };
  22136. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  22137. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  22138. // remove whitespaces
  22139. r = r.replace(/[\s]/g, function () { return ""; });
  22140. return r.length % 2 ? "!" : "";
  22141. });
  22142. booleanString = booleanString.trim();
  22143. if (booleanString === "!true") {
  22144. booleanString = "false";
  22145. }
  22146. else if (booleanString === "!false") {
  22147. booleanString = "true";
  22148. }
  22149. return booleanString;
  22150. };
  22151. return AndOrNotEvaluator;
  22152. })();
  22153. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  22154. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  22155. })(BABYLON || (BABYLON = {}));
  22156. //# sourceMappingURL=babylon.andOrNotEvaluator.js.mapvar BABYLON;
  22157. (function (BABYLON) {
  22158. var PostProcessRenderPass = (function () {
  22159. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  22160. this._enabled = true;
  22161. this._refCount = 0;
  22162. this._name = name;
  22163. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  22164. this.setRenderList(renderList);
  22165. this._renderTexture.onBeforeRender = beforeRender;
  22166. this._renderTexture.onAfterRender = afterRender;
  22167. this._scene = scene;
  22168. this._renderList = renderList;
  22169. }
  22170. // private
  22171. PostProcessRenderPass.prototype._incRefCount = function () {
  22172. if (this._refCount === 0) {
  22173. this._scene.customRenderTargets.push(this._renderTexture);
  22174. }
  22175. return ++this._refCount;
  22176. };
  22177. PostProcessRenderPass.prototype._decRefCount = function () {
  22178. this._refCount--;
  22179. if (this._refCount <= 0) {
  22180. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  22181. }
  22182. return this._refCount;
  22183. };
  22184. PostProcessRenderPass.prototype._update = function () {
  22185. this.setRenderList(this._renderList);
  22186. };
  22187. // public
  22188. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  22189. this._renderTexture.renderList = renderList;
  22190. };
  22191. PostProcessRenderPass.prototype.getRenderTexture = function () {
  22192. return this._renderTexture;
  22193. };
  22194. return PostProcessRenderPass;
  22195. })();
  22196. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  22197. })(BABYLON || (BABYLON = {}));
  22198. //# sourceMappingURL=babylon.postProcessRenderPass.js.mapvar BABYLON;
  22199. (function (BABYLON) {
  22200. var PostProcessRenderEffect = (function () {
  22201. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  22202. this._engine = engine;
  22203. this._name = name;
  22204. this._singleInstance = singleInstance || true;
  22205. this._getPostProcess = getPostProcess;
  22206. this._cameras = [];
  22207. this._indicesForCamera = [];
  22208. this._postProcesses = {};
  22209. this._renderPasses = {};
  22210. this._renderEffectAsPasses = {};
  22211. }
  22212. PostProcessRenderEffect.prototype._update = function () {
  22213. for (var renderPassName in this._renderPasses) {
  22214. this._renderPasses[renderPassName]._update();
  22215. }
  22216. };
  22217. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  22218. this._renderPasses[renderPass._name] = renderPass;
  22219. this._linkParameters();
  22220. };
  22221. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  22222. delete this._renderPasses[renderPass._name];
  22223. this._linkParameters();
  22224. };
  22225. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  22226. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  22227. this._linkParameters();
  22228. };
  22229. PostProcessRenderEffect.prototype.getPass = function (passName) {
  22230. for (var renderPassName in this._renderPasses) {
  22231. if (renderPassName === passName) {
  22232. return this._renderPasses[passName];
  22233. }
  22234. }
  22235. };
  22236. PostProcessRenderEffect.prototype.emptyPasses = function () {
  22237. this._renderPasses = {};
  22238. this._linkParameters();
  22239. };
  22240. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  22241. var cameraKey;
  22242. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  22243. for (var i = 0; i < _cam.length; i++) {
  22244. var camera = _cam[i];
  22245. var cameraName = camera.name;
  22246. if (this._singleInstance) {
  22247. cameraKey = 0;
  22248. }
  22249. else {
  22250. cameraKey = cameraName;
  22251. }
  22252. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  22253. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  22254. if (!this._indicesForCamera[cameraName]) {
  22255. this._indicesForCamera[cameraName] = [];
  22256. }
  22257. this._indicesForCamera[cameraName].push(index);
  22258. if (this._cameras.indexOf(camera) === -1) {
  22259. this._cameras[cameraName] = camera;
  22260. }
  22261. for (var passName in this._renderPasses) {
  22262. this._renderPasses[passName]._incRefCount();
  22263. }
  22264. }
  22265. this._linkParameters();
  22266. };
  22267. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  22268. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  22269. for (var i = 0; i < _cam.length; i++) {
  22270. var camera = _cam[i];
  22271. var cameraName = camera.name;
  22272. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  22273. var index = this._cameras.indexOf(cameraName);
  22274. this._indicesForCamera.splice(index, 1);
  22275. this._cameras.splice(index, 1);
  22276. for (var passName in this._renderPasses) {
  22277. this._renderPasses[passName]._decRefCount();
  22278. }
  22279. }
  22280. };
  22281. PostProcessRenderEffect.prototype._enable = function (cameras) {
  22282. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  22283. for (var i = 0; i < _cam.length; i++) {
  22284. var camera = _cam[i];
  22285. var cameraName = camera.name;
  22286. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  22287. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  22288. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  22289. }
  22290. }
  22291. for (var passName in this._renderPasses) {
  22292. this._renderPasses[passName]._incRefCount();
  22293. }
  22294. }
  22295. };
  22296. PostProcessRenderEffect.prototype._disable = function (cameras) {
  22297. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  22298. for (var i = 0; i < _cam.length; i++) {
  22299. var camera = _cam[i];
  22300. var cameraName = camera.Name;
  22301. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  22302. for (var passName in this._renderPasses) {
  22303. this._renderPasses[passName]._decRefCount();
  22304. }
  22305. }
  22306. };
  22307. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  22308. if (this._singleInstance) {
  22309. return this._postProcesses[0];
  22310. }
  22311. else {
  22312. return this._postProcesses[camera.name];
  22313. }
  22314. };
  22315. PostProcessRenderEffect.prototype._linkParameters = function () {
  22316. var _this = this;
  22317. for (var index in this._postProcesses) {
  22318. if (this.applyParameters) {
  22319. this.applyParameters(this._postProcesses[index]);
  22320. }
  22321. this._postProcesses[index].onBeforeRender = function (effect) {
  22322. _this._linkTextures(effect);
  22323. };
  22324. }
  22325. };
  22326. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  22327. for (var renderPassName in this._renderPasses) {
  22328. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  22329. }
  22330. for (var renderEffectName in this._renderEffectAsPasses) {
  22331. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  22332. }
  22333. };
  22334. return PostProcessRenderEffect;
  22335. })();
  22336. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  22337. })(BABYLON || (BABYLON = {}));
  22338. //# sourceMappingURL=babylon.postProcessRenderEffect.js.mapvar BABYLON;
  22339. (function (BABYLON) {
  22340. var PostProcessRenderPipeline = (function () {
  22341. function PostProcessRenderPipeline(engine, name) {
  22342. this._engine = engine;
  22343. this._name = name;
  22344. this._renderEffects = {};
  22345. this._renderEffectsForIsolatedPass = {};
  22346. this._cameras = [];
  22347. }
  22348. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  22349. this._renderEffects[renderEffect._name] = renderEffect;
  22350. };
  22351. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  22352. var renderEffects = this._renderEffects[renderEffectName];
  22353. if (!renderEffects) {
  22354. return;
  22355. }
  22356. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  22357. };
  22358. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  22359. var renderEffects = this._renderEffects[renderEffectName];
  22360. if (!renderEffects) {
  22361. return;
  22362. }
  22363. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  22364. };
  22365. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  22366. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  22367. var indicesToDelete = [];
  22368. for (var i = 0; i < _cam.length; i++) {
  22369. var camera = _cam[i];
  22370. var cameraName = camera.name;
  22371. if (this._cameras.indexOf(camera) === -1) {
  22372. this._cameras[cameraName] = camera;
  22373. }
  22374. else if (unique) {
  22375. indicesToDelete.push(i);
  22376. }
  22377. }
  22378. for (var i = 0; i < indicesToDelete.length; i++) {
  22379. cameras.splice(indicesToDelete[i], 1);
  22380. }
  22381. for (var renderEffectName in this._renderEffects) {
  22382. this._renderEffects[renderEffectName]._attachCameras(_cam);
  22383. }
  22384. };
  22385. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  22386. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  22387. for (var renderEffectName in this._renderEffects) {
  22388. this._renderEffects[renderEffectName]._detachCameras(_cam);
  22389. }
  22390. for (var i = 0; i < _cam.length; i++) {
  22391. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  22392. }
  22393. };
  22394. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  22395. var _this = this;
  22396. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  22397. var pass = null;
  22398. for (var renderEffectName in this._renderEffects) {
  22399. pass = this._renderEffects[renderEffectName].getPass(passName);
  22400. if (pass != null) {
  22401. break;
  22402. }
  22403. }
  22404. if (pass === null) {
  22405. return;
  22406. }
  22407. for (var renderEffectName in this._renderEffects) {
  22408. this._renderEffects[renderEffectName]._disable(_cam);
  22409. }
  22410. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  22411. for (var i = 0; i < _cam.length; i++) {
  22412. var camera = _cam[i];
  22413. var cameraName = camera.name;
  22414. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () {
  22415. return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true);
  22416. });
  22417. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  22418. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  22419. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  22420. }
  22421. };
  22422. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  22423. var _this = this;
  22424. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  22425. for (var i = 0; i < _cam.length; i++) {
  22426. var camera = _cam[i];
  22427. var cameraName = camera.name;
  22428. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () {
  22429. return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true);
  22430. });
  22431. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  22432. }
  22433. for (var renderEffectName in this._renderEffects) {
  22434. this._renderEffects[renderEffectName]._enable(_cam);
  22435. }
  22436. };
  22437. PostProcessRenderPipeline.prototype._update = function () {
  22438. for (var renderEffectName in this._renderEffects) {
  22439. this._renderEffects[renderEffectName]._update();
  22440. }
  22441. for (var i = 0; i < this._cameras.length; i++) {
  22442. var cameraName = this._cameras[i].name;
  22443. if (this._renderEffectsForIsolatedPass[cameraName]) {
  22444. this._renderEffectsForIsolatedPass[cameraName]._update();
  22445. }
  22446. }
  22447. };
  22448. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  22449. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  22450. return PostProcessRenderPipeline;
  22451. })();
  22452. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  22453. })(BABYLON || (BABYLON = {}));
  22454. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.mapvar BABYLON;
  22455. (function (BABYLON) {
  22456. var PostProcessRenderPipelineManager = (function () {
  22457. function PostProcessRenderPipelineManager() {
  22458. this._renderPipelines = {};
  22459. }
  22460. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  22461. this._renderPipelines[renderPipeline._name] = renderPipeline;
  22462. };
  22463. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  22464. var renderPipeline = this._renderPipelines[renderPipelineName];
  22465. if (!renderPipeline) {
  22466. return;
  22467. }
  22468. renderPipeline._attachCameras(cameras, unique);
  22469. };
  22470. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  22471. var renderPipeline = this._renderPipelines[renderPipelineName];
  22472. if (!renderPipeline) {
  22473. return;
  22474. }
  22475. renderPipeline._detachCameras(cameras);
  22476. };
  22477. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  22478. var renderPipeline = this._renderPipelines[renderPipelineName];
  22479. if (!renderPipeline) {
  22480. return;
  22481. }
  22482. renderPipeline._enableEffect(renderEffectName, cameras);
  22483. };
  22484. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  22485. var renderPipeline = this._renderPipelines[renderPipelineName];
  22486. if (!renderPipeline) {
  22487. return;
  22488. }
  22489. renderPipeline._disableEffect(renderEffectName, cameras);
  22490. };
  22491. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  22492. var renderPipeline = this._renderPipelines[renderPipelineName];
  22493. if (!renderPipeline) {
  22494. return;
  22495. }
  22496. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  22497. };
  22498. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  22499. var renderPipeline = this._renderPipelines[renderPipelineName];
  22500. if (!renderPipeline) {
  22501. return;
  22502. }
  22503. renderPipeline._disableDisplayOnlyPass(cameras);
  22504. };
  22505. PostProcessRenderPipelineManager.prototype.update = function () {
  22506. for (var renderPipelineName in this._renderPipelines) {
  22507. this._renderPipelines[renderPipelineName]._update();
  22508. }
  22509. };
  22510. return PostProcessRenderPipelineManager;
  22511. })();
  22512. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  22513. })(BABYLON || (BABYLON = {}));
  22514. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  22515. var BABYLON;
  22516. (function (BABYLON) {
  22517. var DisplayPassPostProcess = (function (_super) {
  22518. __extends(DisplayPassPostProcess, _super);
  22519. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  22520. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  22521. }
  22522. return DisplayPassPostProcess;
  22523. })(BABYLON.PostProcess);
  22524. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  22525. })(BABYLON || (BABYLON = {}));
  22526. //# sourceMappingURL=babylon.displayPassPostProcess.js.mapvar BABYLON;
  22527. (function (BABYLON) {
  22528. var BoundingBoxRenderer = (function () {
  22529. function BoundingBoxRenderer(scene) {
  22530. this.frontColor = new BABYLON.Color3(1, 1, 1);
  22531. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  22532. this.showBackLines = true;
  22533. this.renderList = new BABYLON.SmartArray(32);
  22534. this._scene = scene;
  22535. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  22536. attributes: ["position"],
  22537. uniforms: ["worldViewProjection", "color"]
  22538. });
  22539. var engine = this._scene.getEngine();
  22540. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  22541. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  22542. 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]);
  22543. }
  22544. BoundingBoxRenderer.prototype.reset = function () {
  22545. this.renderList.reset();
  22546. };
  22547. BoundingBoxRenderer.prototype.render = function () {
  22548. if (this.renderList.length === 0 || !this._colorShader.isReady()) {
  22549. return;
  22550. }
  22551. var engine = this._scene.getEngine();
  22552. engine.setDepthWrite(false);
  22553. this._colorShader._preBind();
  22554. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  22555. var boundingBox = this.renderList.data[boundingBoxIndex];
  22556. var min = boundingBox.minimum;
  22557. var max = boundingBox.maximum;
  22558. var diff = max.subtract(min);
  22559. var median = min.add(diff.scale(0.5));
  22560. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z).multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z)).multiply(boundingBox.getWorldMatrix());
  22561. // VBOs
  22562. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  22563. if (this.showBackLines) {
  22564. // Back
  22565. engine.setDepthFunctionToGreaterOrEqual();
  22566. this._scene.resetCachedMaterial();
  22567. this._colorShader.setColor4("color", this.backColor.toColor4());
  22568. this._colorShader.bind(worldMatrix);
  22569. // Draw order
  22570. engine.draw(false, 0, 24);
  22571. }
  22572. // Front
  22573. engine.setDepthFunctionToLess();
  22574. this._scene.resetCachedMaterial();
  22575. this._colorShader.setColor4("color", this.frontColor.toColor4());
  22576. this._colorShader.bind(worldMatrix);
  22577. // Draw order
  22578. engine.draw(false, 0, 24);
  22579. }
  22580. this._colorShader.unbind();
  22581. engine.setDepthFunctionToLessOrEqual();
  22582. engine.setDepthWrite(true);
  22583. };
  22584. BoundingBoxRenderer.prototype.dispose = function () {
  22585. this._colorShader.dispose();
  22586. this._vb.dispose();
  22587. this._scene.getEngine()._releaseBuffer(this._ib);
  22588. };
  22589. return BoundingBoxRenderer;
  22590. })();
  22591. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  22592. })(BABYLON || (BABYLON = {}));
  22593. //# sourceMappingURL=babylon.boundingBoxRenderer.js.mapvar BABYLON;
  22594. (function (BABYLON) {
  22595. var Internals;
  22596. (function (Internals) {
  22597. /*
  22598. * Based on jsTGALoader - Javascript loader for TGA file
  22599. * By Vincent Thibault
  22600. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  22601. */
  22602. var TGATools = (function () {
  22603. function TGATools() {
  22604. }
  22605. TGATools.GetTGAHeader = function (data) {
  22606. var offset = 0;
  22607. var header = {
  22608. id_length: data[offset++],
  22609. colormap_type: data[offset++],
  22610. image_type: data[offset++],
  22611. colormap_index: data[offset++] | data[offset++] << 8,
  22612. colormap_length: data[offset++] | data[offset++] << 8,
  22613. colormap_size: data[offset++],
  22614. origin: [
  22615. data[offset++] | data[offset++] << 8,
  22616. data[offset++] | data[offset++] << 8
  22617. ],
  22618. width: data[offset++] | data[offset++] << 8,
  22619. height: data[offset++] | data[offset++] << 8,
  22620. pixel_size: data[offset++],
  22621. flags: data[offset++]
  22622. };
  22623. return header;
  22624. };
  22625. TGATools.UploadContent = function (gl, data) {
  22626. // Not enough data to contain header ?
  22627. if (data.length < 19) {
  22628. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  22629. return;
  22630. }
  22631. // Read Header
  22632. var offset = 18;
  22633. var header = TGATools.GetTGAHeader(data);
  22634. // Assume it's a valid Targa file.
  22635. if (header.id_length + offset > data.length) {
  22636. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  22637. return;
  22638. }
  22639. // Skip not needed data
  22640. offset += header.id_length;
  22641. var use_rle = false;
  22642. var use_pal = false;
  22643. var use_rgb = false;
  22644. var use_grey = false;
  22645. switch (header.image_type) {
  22646. case TGATools._TYPE_RLE_INDEXED:
  22647. use_rle = true;
  22648. case TGATools._TYPE_INDEXED:
  22649. use_pal = true;
  22650. break;
  22651. case TGATools._TYPE_RLE_RGB:
  22652. use_rle = true;
  22653. case TGATools._TYPE_RGB:
  22654. use_rgb = true;
  22655. break;
  22656. case TGATools._TYPE_RLE_GREY:
  22657. use_rle = true;
  22658. case TGATools._TYPE_GREY:
  22659. use_grey = true;
  22660. break;
  22661. }
  22662. var pixel_data;
  22663. var numAlphaBits = header.flags & 0xf;
  22664. var pixel_size = header.pixel_size >> 3;
  22665. var pixel_total = header.width * header.height * pixel_size;
  22666. // Read palettes
  22667. var palettes;
  22668. if (use_pal) {
  22669. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  22670. }
  22671. // Read LRE
  22672. if (use_rle) {
  22673. pixel_data = new Uint8Array(pixel_total);
  22674. var c, count, i;
  22675. var localOffset = 0;
  22676. var pixels = new Uint8Array(pixel_size);
  22677. while (offset < pixel_total && localOffset < pixel_total) {
  22678. c = data[offset++];
  22679. count = (c & 0x7f) + 1;
  22680. // RLE pixels
  22681. if (c & 0x80) {
  22682. for (i = 0; i < pixel_size; ++i) {
  22683. pixels[i] = data[offset++];
  22684. }
  22685. for (i = 0; i < count; ++i) {
  22686. pixel_data.set(pixels, localOffset + i * pixel_size);
  22687. }
  22688. localOffset += pixel_size * count;
  22689. }
  22690. else {
  22691. count *= pixel_size;
  22692. for (i = 0; i < count; ++i) {
  22693. pixel_data[localOffset + i] = data[offset++];
  22694. }
  22695. localOffset += count;
  22696. }
  22697. }
  22698. }
  22699. else {
  22700. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  22701. }
  22702. // Load to texture
  22703. var x_start, y_start, x_step, y_step, y_end, x_end;
  22704. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  22705. default:
  22706. case TGATools._ORIGIN_UL:
  22707. x_start = 0;
  22708. x_step = 1;
  22709. x_end = header.width;
  22710. y_start = 0;
  22711. y_step = 1;
  22712. y_end = header.height;
  22713. break;
  22714. case TGATools._ORIGIN_BL:
  22715. x_start = 0;
  22716. x_step = 1;
  22717. x_end = header.width;
  22718. y_start = header.height - 1;
  22719. y_step = -1;
  22720. y_end = -1;
  22721. break;
  22722. case TGATools._ORIGIN_UR:
  22723. x_start = header.width - 1;
  22724. x_step = -1;
  22725. x_end = -1;
  22726. y_start = 0;
  22727. y_step = 1;
  22728. y_end = header.height;
  22729. break;
  22730. case TGATools._ORIGIN_BR:
  22731. x_start = header.width - 1;
  22732. x_step = -1;
  22733. x_end = -1;
  22734. y_start = header.height - 1;
  22735. y_step = -1;
  22736. y_end = -1;
  22737. break;
  22738. }
  22739. // Load the specify method
  22740. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  22741. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  22742. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  22743. };
  22744. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  22745. var image = pixel_data, colormap = palettes;
  22746. var width = header.width, height = header.height;
  22747. var color, i = 0, x, y;
  22748. var imageData = new Uint8Array(width * height * 4);
  22749. for (y = y_start; y !== y_end; y += y_step) {
  22750. for (x = x_start; x !== x_end; x += x_step, i++) {
  22751. color = image[i];
  22752. imageData[(x + width * y) * 4 + 3] = 255;
  22753. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  22754. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  22755. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  22756. }
  22757. }
  22758. return imageData;
  22759. };
  22760. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  22761. var image = pixel_data;
  22762. var width = header.width, height = header.height;
  22763. var color, i = 0, x, y;
  22764. var imageData = new Uint8Array(width * height * 4);
  22765. for (y = y_start; y !== y_end; y += y_step) {
  22766. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  22767. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  22768. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  22769. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  22770. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  22771. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  22772. }
  22773. }
  22774. return imageData;
  22775. };
  22776. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  22777. var image = pixel_data;
  22778. var width = header.width, height = header.height;
  22779. var i = 0, x, y;
  22780. var imageData = new Uint8Array(width * height * 4);
  22781. for (y = y_start; y !== y_end; y += y_step) {
  22782. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  22783. imageData[(x + width * y) * 4 + 3] = 255;
  22784. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  22785. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  22786. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  22787. }
  22788. }
  22789. return imageData;
  22790. };
  22791. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  22792. var image = pixel_data;
  22793. var width = header.width, height = header.height;
  22794. var i = 0, x, y;
  22795. var imageData = new Uint8Array(width * height * 4);
  22796. for (y = y_start; y !== y_end; y += y_step) {
  22797. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  22798. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  22799. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  22800. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  22801. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  22802. }
  22803. }
  22804. return imageData;
  22805. };
  22806. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  22807. var image = pixel_data;
  22808. var width = header.width, height = header.height;
  22809. var color, i = 0, x, y;
  22810. var imageData = new Uint8Array(width * height * 4);
  22811. for (y = y_start; y !== y_end; y += y_step) {
  22812. for (x = x_start; x !== x_end; x += x_step, i++) {
  22813. color = image[i];
  22814. imageData[(x + width * y) * 4 + 0] = color;
  22815. imageData[(x + width * y) * 4 + 1] = color;
  22816. imageData[(x + width * y) * 4 + 2] = color;
  22817. imageData[(x + width * y) * 4 + 3] = 255;
  22818. }
  22819. }
  22820. return imageData;
  22821. };
  22822. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  22823. var image = pixel_data;
  22824. var width = header.width, height = header.height;
  22825. var i = 0, x, y;
  22826. var imageData = new Uint8Array(width * height * 4);
  22827. for (y = y_start; y !== y_end; y += y_step) {
  22828. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  22829. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  22830. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  22831. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  22832. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  22833. }
  22834. }
  22835. return imageData;
  22836. };
  22837. TGATools._TYPE_NO_DATA = 0;
  22838. TGATools._TYPE_INDEXED = 1;
  22839. TGATools._TYPE_RGB = 2;
  22840. TGATools._TYPE_GREY = 3;
  22841. TGATools._TYPE_RLE_INDEXED = 9;
  22842. TGATools._TYPE_RLE_RGB = 10;
  22843. TGATools._TYPE_RLE_GREY = 11;
  22844. TGATools._ORIGIN_MASK = 0x30;
  22845. TGATools._ORIGIN_SHIFT = 0x04;
  22846. TGATools._ORIGIN_BL = 0x00;
  22847. TGATools._ORIGIN_BR = 0x01;
  22848. TGATools._ORIGIN_UL = 0x02;
  22849. TGATools._ORIGIN_UR = 0x03;
  22850. return TGATools;
  22851. })();
  22852. Internals.TGATools = TGATools;
  22853. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  22854. })(BABYLON || (BABYLON = {}));
  22855. //# sourceMappingURL=babylon.tools.tga.js.mapvar BABYLON;
  22856. (function (BABYLON) {
  22857. var Internals;
  22858. (function (Internals) {
  22859. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  22860. // All values and structures referenced from:
  22861. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  22862. var DDS_MAGIC = 0x20534444;
  22863. 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;
  22864. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  22865. 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;
  22866. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  22867. function FourCCToInt32(value) {
  22868. return value.charCodeAt(0) + (value.charCodeAt(1) << 8) + (value.charCodeAt(2) << 16) + (value.charCodeAt(3) << 24);
  22869. }
  22870. function Int32ToFourCC(value) {
  22871. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  22872. }
  22873. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  22874. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  22875. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  22876. var headerLengthInt = 31; // The header length in 32 bit ints
  22877. // Offsets into the header array
  22878. var off_magic = 0;
  22879. var off_size = 1;
  22880. var off_flags = 2;
  22881. var off_height = 3;
  22882. var off_width = 4;
  22883. var off_mipmapCount = 7;
  22884. var off_pfFlags = 20;
  22885. var off_pfFourCC = 21;
  22886. var off_RGBbpp = 22;
  22887. var off_RMask = 23;
  22888. var off_GMask = 24;
  22889. var off_BMask = 25;
  22890. var off_AMask = 26;
  22891. var off_caps1 = 27;
  22892. var off_caps2 = 28;
  22893. ;
  22894. var DDSTools = (function () {
  22895. function DDSTools() {
  22896. }
  22897. DDSTools.GetDDSInfo = function (arrayBuffer) {
  22898. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  22899. var mipmapCount = 1;
  22900. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  22901. mipmapCount = Math.max(1, header[off_mipmapCount]);
  22902. }
  22903. return {
  22904. width: header[off_width],
  22905. height: header[off_height],
  22906. mipmapCount: mipmapCount,
  22907. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  22908. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  22909. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  22910. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  22911. };
  22912. };
  22913. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  22914. var byteArray = new Uint8Array(dataLength);
  22915. var srcData = new Uint8Array(arrayBuffer);
  22916. var index = 0;
  22917. for (var y = height - 1; y >= 0; y--) {
  22918. for (var x = 0; x < width; x++) {
  22919. var srcPos = dataOffset + (x + y * width) * 4;
  22920. byteArray[index + 2] = srcData[srcPos];
  22921. byteArray[index + 1] = srcData[srcPos + 1];
  22922. byteArray[index] = srcData[srcPos + 2];
  22923. byteArray[index + 3] = srcData[srcPos + 3];
  22924. index += 4;
  22925. }
  22926. }
  22927. return byteArray;
  22928. };
  22929. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  22930. var byteArray = new Uint8Array(dataLength);
  22931. var srcData = new Uint8Array(arrayBuffer);
  22932. var index = 0;
  22933. for (var y = height - 1; y >= 0; y--) {
  22934. for (var x = 0; x < width; x++) {
  22935. var srcPos = dataOffset + (x + y * width) * 3;
  22936. byteArray[index + 2] = srcData[srcPos];
  22937. byteArray[index + 1] = srcData[srcPos + 1];
  22938. byteArray[index] = srcData[srcPos + 2];
  22939. index += 3;
  22940. }
  22941. }
  22942. return byteArray;
  22943. };
  22944. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  22945. var byteArray = new Uint8Array(dataLength);
  22946. var srcData = new Uint8Array(arrayBuffer);
  22947. var index = 0;
  22948. for (var y = height - 1; y >= 0; y--) {
  22949. for (var x = 0; x < width; x++) {
  22950. var srcPos = dataOffset + (x + y * width);
  22951. byteArray[index] = srcData[srcPos];
  22952. index++;
  22953. }
  22954. }
  22955. return byteArray;
  22956. };
  22957. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  22958. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  22959. if (header[off_magic] != DDS_MAGIC) {
  22960. BABYLON.Tools.Error("Invalid magic number in DDS header");
  22961. return;
  22962. }
  22963. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  22964. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  22965. return;
  22966. }
  22967. if (info.isFourCC) {
  22968. fourCC = header[off_pfFourCC];
  22969. switch (fourCC) {
  22970. case FOURCC_DXT1:
  22971. blockBytes = 8;
  22972. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  22973. break;
  22974. case FOURCC_DXT3:
  22975. blockBytes = 16;
  22976. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  22977. break;
  22978. case FOURCC_DXT5:
  22979. blockBytes = 16;
  22980. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  22981. break;
  22982. default:
  22983. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  22984. return;
  22985. }
  22986. }
  22987. mipmapCount = 1;
  22988. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  22989. mipmapCount = Math.max(1, header[off_mipmapCount]);
  22990. }
  22991. var bpp = header[off_RGBbpp];
  22992. for (var face = 0; face < faces; face++) {
  22993. var sampler = faces == 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  22994. width = header[off_width];
  22995. height = header[off_height];
  22996. dataOffset = header[off_size] + 4;
  22997. for (i = 0; i < mipmapCount; ++i) {
  22998. if (info.isRGB) {
  22999. if (bpp == 24) {
  23000. dataLength = width * height * 3;
  23001. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  23002. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  23003. }
  23004. else {
  23005. dataLength = width * height * 4;
  23006. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  23007. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  23008. }
  23009. }
  23010. else if (info.isLuminance) {
  23011. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  23012. var unpaddedRowSize = width;
  23013. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  23014. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  23015. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  23016. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  23017. }
  23018. else {
  23019. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  23020. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  23021. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  23022. }
  23023. dataOffset += dataLength;
  23024. width *= 0.5;
  23025. height *= 0.5;
  23026. width = Math.max(1.0, width);
  23027. height = Math.max(1.0, height);
  23028. }
  23029. }
  23030. };
  23031. return DDSTools;
  23032. })();
  23033. Internals.DDSTools = DDSTools;
  23034. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  23035. })(BABYLON || (BABYLON = {}));
  23036. //# sourceMappingURL=babylon.tools.dds.js.mapvar BABYLON;
  23037. (function (BABYLON) {
  23038. var SmartArray = (function () {
  23039. function SmartArray(capacity) {
  23040. this.length = 0;
  23041. this._duplicateId = 0;
  23042. this.data = new Array(capacity);
  23043. this._id = SmartArray._GlobalId++;
  23044. }
  23045. SmartArray.prototype.push = function (value) {
  23046. this.data[this.length++] = value;
  23047. if (this.length > this.data.length) {
  23048. this.data.length *= 2;
  23049. }
  23050. if (!value.__smartArrayFlags) {
  23051. value.__smartArrayFlags = {};
  23052. }
  23053. value.__smartArrayFlags[this._id] = this._duplicateId;
  23054. };
  23055. SmartArray.prototype.pushNoDuplicate = function (value) {
  23056. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  23057. return;
  23058. }
  23059. this.push(value);
  23060. };
  23061. SmartArray.prototype.sort = function (compareFn) {
  23062. this.data.sort(compareFn);
  23063. };
  23064. SmartArray.prototype.reset = function () {
  23065. this.length = 0;
  23066. this._duplicateId++;
  23067. };
  23068. SmartArray.prototype.concat = function (array) {
  23069. if (array.length === 0) {
  23070. return;
  23071. }
  23072. if (this.length + array.length > this.data.length) {
  23073. this.data.length = (this.length + array.length) * 2;
  23074. }
  23075. for (var index = 0; index < array.length; index++) {
  23076. this.data[this.length++] = (array.data || array)[index];
  23077. }
  23078. };
  23079. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  23080. if (array.length === 0) {
  23081. return;
  23082. }
  23083. if (this.length + array.length > this.data.length) {
  23084. this.data.length = (this.length + array.length) * 2;
  23085. }
  23086. for (var index = 0; index < array.length; index++) {
  23087. var item = (array.data || array)[index];
  23088. this.pushNoDuplicate(item);
  23089. }
  23090. };
  23091. SmartArray.prototype.indexOf = function (value) {
  23092. var position = this.data.indexOf(value);
  23093. if (position >= this.length) {
  23094. return -1;
  23095. }
  23096. return position;
  23097. };
  23098. // Statics
  23099. SmartArray._GlobalId = 0;
  23100. return SmartArray;
  23101. })();
  23102. BABYLON.SmartArray = SmartArray;
  23103. })(BABYLON || (BABYLON = {}));
  23104. //# sourceMappingURL=babylon.smartArray.js.mapvar BABYLON;
  23105. (function (BABYLON) {
  23106. var CannonJSPlugin = (function () {
  23107. function CannonJSPlugin() {
  23108. this._registeredMeshes = [];
  23109. this._physicsMaterials = [];
  23110. this.updateBodyPosition = function (mesh) {
  23111. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23112. var registeredMesh = this._registeredMeshes[index];
  23113. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  23114. var body = registeredMesh.body;
  23115. var center = mesh.getBoundingInfo().boundingBox.center;
  23116. body.position.set(center.x, center.z, center.y);
  23117. body.quaternion.x = mesh.rotationQuaternion.x;
  23118. body.quaternion.z = mesh.rotationQuaternion.y;
  23119. body.quaternion.y = mesh.rotationQuaternion.z;
  23120. body.quaternion.w = -mesh.rotationQuaternion.w;
  23121. return;
  23122. }
  23123. }
  23124. };
  23125. }
  23126. CannonJSPlugin.prototype.initialize = function (iterations) {
  23127. if (iterations === void 0) { iterations = 10; }
  23128. this._world = new CANNON.World();
  23129. this._world.broadphase = new CANNON.NaiveBroadphase();
  23130. this._world.solver.iterations = iterations;
  23131. };
  23132. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  23133. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  23134. };
  23135. CannonJSPlugin.prototype.runOneStep = function (delta) {
  23136. this._world.step(delta);
  23137. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23138. var registeredMesh = this._registeredMeshes[index];
  23139. if (registeredMesh.isChild) {
  23140. continue;
  23141. }
  23142. // Body position
  23143. var bodyX = registeredMesh.body.position.x, bodyY = registeredMesh.body.position.y, bodyZ = registeredMesh.body.position.z;
  23144. var deltaPos = registeredMesh.delta;
  23145. if (deltaPos) {
  23146. registeredMesh.mesh.position.x = bodyX + deltaPos.x;
  23147. registeredMesh.mesh.position.y = bodyZ + deltaPos.y;
  23148. registeredMesh.mesh.position.z = bodyY + deltaPos.z;
  23149. }
  23150. else {
  23151. registeredMesh.mesh.position.x = bodyX;
  23152. registeredMesh.mesh.position.y = bodyZ;
  23153. registeredMesh.mesh.position.z = bodyY;
  23154. }
  23155. if (!registeredMesh.mesh.rotationQuaternion) {
  23156. registeredMesh.mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  23157. }
  23158. registeredMesh.mesh.rotationQuaternion.x = registeredMesh.body.quaternion.x;
  23159. registeredMesh.mesh.rotationQuaternion.y = registeredMesh.body.quaternion.z;
  23160. registeredMesh.mesh.rotationQuaternion.z = registeredMesh.body.quaternion.y;
  23161. registeredMesh.mesh.rotationQuaternion.w = -registeredMesh.body.quaternion.w;
  23162. }
  23163. };
  23164. CannonJSPlugin.prototype.setGravity = function (gravity) {
  23165. this._world.gravity.set(gravity.x, gravity.z, gravity.y);
  23166. };
  23167. CannonJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  23168. this.unregisterMesh(mesh);
  23169. mesh.computeWorldMatrix(true);
  23170. switch (impostor) {
  23171. case BABYLON.PhysicsEngine.SphereImpostor:
  23172. var bbox = mesh.getBoundingInfo().boundingBox;
  23173. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  23174. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  23175. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  23176. return this._createSphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2, mesh, options);
  23177. case BABYLON.PhysicsEngine.BoxImpostor:
  23178. bbox = mesh.getBoundingInfo().boundingBox;
  23179. var min = bbox.minimumWorld;
  23180. var max = bbox.maximumWorld;
  23181. var box = max.subtract(min).scale(0.5);
  23182. return this._createBox(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z), mesh, options);
  23183. case BABYLON.PhysicsEngine.PlaneImpostor:
  23184. return this._createPlane(mesh, options);
  23185. case BABYLON.PhysicsEngine.MeshImpostor:
  23186. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23187. var rawFaces = mesh.getIndices();
  23188. return this._createConvexPolyhedron(rawVerts, rawFaces, mesh, options);
  23189. }
  23190. return null;
  23191. };
  23192. CannonJSPlugin.prototype._createSphere = function (radius, mesh, options) {
  23193. var shape = new CANNON.Sphere(radius);
  23194. if (!options) {
  23195. return shape;
  23196. }
  23197. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  23198. };
  23199. CannonJSPlugin.prototype._createBox = function (x, y, z, mesh, options) {
  23200. var shape = new CANNON.Box(new CANNON.Vec3(x, z, y));
  23201. if (!options) {
  23202. return shape;
  23203. }
  23204. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  23205. };
  23206. CannonJSPlugin.prototype._createPlane = function (mesh, options) {
  23207. var shape = new CANNON.Plane();
  23208. if (!options) {
  23209. return shape;
  23210. }
  23211. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  23212. };
  23213. CannonJSPlugin.prototype._createConvexPolyhedron = function (rawVerts, rawFaces, mesh, options) {
  23214. var verts = [], faces = [];
  23215. mesh.computeWorldMatrix(true);
  23216. for (var i = 0; i < rawVerts.length; i += 3) {
  23217. var transformed = BABYLON.Vector3.Zero();
  23218. BABYLON.Vector3.TransformNormalFromFloatsToRef(rawVerts[i], rawVerts[i + 1], rawVerts[i + 2], mesh.getWorldMatrix(), transformed);
  23219. verts.push(new CANNON.Vec3(transformed.x, transformed.z, transformed.y));
  23220. }
  23221. for (var j = 0; j < rawFaces.length; j += 3) {
  23222. faces.push([rawFaces[j], rawFaces[j + 2], rawFaces[j + 1]]);
  23223. }
  23224. var shape = new CANNON.ConvexPolyhedron(verts, faces);
  23225. if (!options) {
  23226. return shape;
  23227. }
  23228. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  23229. };
  23230. CannonJSPlugin.prototype._addMaterial = function (friction, restitution) {
  23231. var index;
  23232. var mat;
  23233. for (index = 0; index < this._physicsMaterials.length; index++) {
  23234. mat = this._physicsMaterials[index];
  23235. if (mat.friction === friction && mat.restitution === restitution) {
  23236. return mat;
  23237. }
  23238. }
  23239. var currentMat = new CANNON.Material();
  23240. currentMat.friction = friction;
  23241. currentMat.restitution = restitution;
  23242. this._physicsMaterials.push(currentMat);
  23243. for (index = 0; index < this._physicsMaterials.length; index++) {
  23244. mat = this._physicsMaterials[index];
  23245. var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, mat.friction * currentMat.friction, mat.restitution * currentMat.restitution);
  23246. contactMaterial.contactEquationStiffness = 1e10;
  23247. contactMaterial.contactEquationRegularizationTime = 10;
  23248. this._world.addContactMaterial(contactMaterial);
  23249. }
  23250. return currentMat;
  23251. };
  23252. CannonJSPlugin.prototype._createRigidBodyFromShape = function (shape, mesh, mass, friction, restitution) {
  23253. var initialRotation = null;
  23254. if (mesh.rotationQuaternion) {
  23255. initialRotation = mesh.rotationQuaternion.clone();
  23256. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  23257. }
  23258. // The delta between the mesh position and the mesh bounding box center
  23259. var bbox = mesh.getBoundingInfo().boundingBox;
  23260. var deltaPosition = mesh.position.subtract(bbox.center);
  23261. var material = this._addMaterial(friction, restitution);
  23262. var body = new CANNON.RigidBody(mass, shape, material);
  23263. if (initialRotation) {
  23264. body.quaternion.x = initialRotation.x;
  23265. body.quaternion.z = initialRotation.y;
  23266. body.quaternion.y = initialRotation.z;
  23267. body.quaternion.w = -initialRotation.w;
  23268. }
  23269. body.position.set(bbox.center.x, bbox.center.z, bbox.center.y);
  23270. this._world.add(body);
  23271. this._registeredMeshes.push({ mesh: mesh, body: body, material: material, delta: deltaPosition });
  23272. return body;
  23273. };
  23274. CannonJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  23275. var compoundShape = new CANNON.Compound();
  23276. for (var index = 0; index < parts.length; index++) {
  23277. var mesh = parts[index].mesh;
  23278. var shape = this.registerMesh(mesh, parts[index].impostor);
  23279. if (index == 0) {
  23280. compoundShape.addChild(shape, new CANNON.Vec3(0, 0, 0));
  23281. }
  23282. else {
  23283. compoundShape.addChild(shape, new CANNON.Vec3(mesh.position.x, mesh.position.z, mesh.position.y));
  23284. }
  23285. }
  23286. var initialMesh = parts[0].mesh;
  23287. var body = this._createRigidBodyFromShape(compoundShape, initialMesh, options.mass, options.friction, options.restitution);
  23288. body.parts = parts;
  23289. return body;
  23290. };
  23291. CannonJSPlugin.prototype._unbindBody = function (body) {
  23292. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23293. var registeredMesh = this._registeredMeshes[index];
  23294. if (registeredMesh.body === body) {
  23295. registeredMesh.body = null;
  23296. registeredMesh.delta = 0;
  23297. }
  23298. }
  23299. };
  23300. CannonJSPlugin.prototype.unregisterMesh = function (mesh) {
  23301. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23302. var registeredMesh = this._registeredMeshes[index];
  23303. if (registeredMesh.mesh === mesh) {
  23304. // Remove body
  23305. if (registeredMesh.body) {
  23306. this._world.remove(registeredMesh.body);
  23307. this._unbindBody(registeredMesh.body);
  23308. }
  23309. this._registeredMeshes.splice(index, 1);
  23310. return;
  23311. }
  23312. }
  23313. };
  23314. CannonJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  23315. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.z, contactPoint.y);
  23316. var impulse = new CANNON.Vec3(force.x, force.z, force.y);
  23317. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23318. var registeredMesh = this._registeredMeshes[index];
  23319. if (registeredMesh.mesh === mesh) {
  23320. registeredMesh.body.applyImpulse(impulse, worldPoint);
  23321. return;
  23322. }
  23323. }
  23324. };
  23325. CannonJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2) {
  23326. var body1 = null, body2 = null;
  23327. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23328. var registeredMesh = this._registeredMeshes[index];
  23329. if (registeredMesh.mesh === mesh1) {
  23330. body1 = registeredMesh.body;
  23331. }
  23332. else if (registeredMesh.mesh === mesh2) {
  23333. body2 = registeredMesh.body;
  23334. }
  23335. }
  23336. if (!body1 || !body2) {
  23337. return false;
  23338. }
  23339. 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));
  23340. this._world.addConstraint(constraint);
  23341. return true;
  23342. };
  23343. CannonJSPlugin.prototype.dispose = function () {
  23344. while (this._registeredMeshes.length) {
  23345. this.unregisterMesh(this._registeredMeshes[0].mesh);
  23346. }
  23347. };
  23348. CannonJSPlugin.prototype.isSupported = function () {
  23349. return window.CANNON !== undefined;
  23350. };
  23351. return CannonJSPlugin;
  23352. })();
  23353. BABYLON.CannonJSPlugin = CannonJSPlugin;
  23354. })(BABYLON || (BABYLON = {}));
  23355. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  23356. var BABYLON;
  23357. (function (BABYLON) {
  23358. var Condition = (function () {
  23359. function Condition(actionManager) {
  23360. this._actionManager = actionManager;
  23361. }
  23362. Condition.prototype.isValid = function () {
  23363. return true;
  23364. };
  23365. Condition.prototype._getProperty = function (propertyPath) {
  23366. return this._actionManager._getProperty(propertyPath);
  23367. };
  23368. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  23369. return this._actionManager._getEffectiveTarget(target, propertyPath);
  23370. };
  23371. return Condition;
  23372. })();
  23373. BABYLON.Condition = Condition;
  23374. var ValueCondition = (function (_super) {
  23375. __extends(ValueCondition, _super);
  23376. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  23377. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  23378. _super.call(this, actionManager);
  23379. this.propertyPath = propertyPath;
  23380. this.value = value;
  23381. this.operator = operator;
  23382. this._target = this._getEffectiveTarget(target, this.propertyPath);
  23383. this._property = this._getProperty(this.propertyPath);
  23384. }
  23385. Object.defineProperty(ValueCondition, "IsEqual", {
  23386. get: function () {
  23387. return ValueCondition._IsEqual;
  23388. },
  23389. enumerable: true,
  23390. configurable: true
  23391. });
  23392. Object.defineProperty(ValueCondition, "IsDifferent", {
  23393. get: function () {
  23394. return ValueCondition._IsDifferent;
  23395. },
  23396. enumerable: true,
  23397. configurable: true
  23398. });
  23399. Object.defineProperty(ValueCondition, "IsGreater", {
  23400. get: function () {
  23401. return ValueCondition._IsGreater;
  23402. },
  23403. enumerable: true,
  23404. configurable: true
  23405. });
  23406. Object.defineProperty(ValueCondition, "IsLesser", {
  23407. get: function () {
  23408. return ValueCondition._IsLesser;
  23409. },
  23410. enumerable: true,
  23411. configurable: true
  23412. });
  23413. // Methods
  23414. ValueCondition.prototype.isValid = function () {
  23415. switch (this.operator) {
  23416. case ValueCondition.IsGreater:
  23417. return this._target[this._property] > this.value;
  23418. case ValueCondition.IsLesser:
  23419. return this._target[this._property] < this.value;
  23420. case ValueCondition.IsEqual:
  23421. case ValueCondition.IsDifferent:
  23422. var check;
  23423. if (this.value.equals) {
  23424. check = this.value.equals(this._target[this._property]);
  23425. }
  23426. else {
  23427. check = this.value === this._target[this._property];
  23428. }
  23429. return this.operator === ValueCondition.IsEqual ? check : !check;
  23430. }
  23431. return false;
  23432. };
  23433. // Statics
  23434. ValueCondition._IsEqual = 0;
  23435. ValueCondition._IsDifferent = 1;
  23436. ValueCondition._IsGreater = 2;
  23437. ValueCondition._IsLesser = 3;
  23438. return ValueCondition;
  23439. })(Condition);
  23440. BABYLON.ValueCondition = ValueCondition;
  23441. var PredicateCondition = (function (_super) {
  23442. __extends(PredicateCondition, _super);
  23443. function PredicateCondition(actionManager, predicate) {
  23444. _super.call(this, actionManager);
  23445. this.predicate = predicate;
  23446. }
  23447. PredicateCondition.prototype.isValid = function () {
  23448. return this.predicate();
  23449. };
  23450. return PredicateCondition;
  23451. })(Condition);
  23452. BABYLON.PredicateCondition = PredicateCondition;
  23453. var StateCondition = (function (_super) {
  23454. __extends(StateCondition, _super);
  23455. function StateCondition(actionManager, target, value) {
  23456. _super.call(this, actionManager);
  23457. this.value = value;
  23458. this._target = target;
  23459. }
  23460. // Methods
  23461. StateCondition.prototype.isValid = function () {
  23462. return this._target.state === this.value;
  23463. };
  23464. return StateCondition;
  23465. })(Condition);
  23466. BABYLON.StateCondition = StateCondition;
  23467. })(BABYLON || (BABYLON = {}));
  23468. //# sourceMappingURL=babylon.condition.js.mapvar BABYLON;
  23469. (function (BABYLON) {
  23470. var Action = (function () {
  23471. function Action(triggerOptions, condition) {
  23472. this.triggerOptions = triggerOptions;
  23473. if (triggerOptions.parameter) {
  23474. this.trigger = triggerOptions.trigger;
  23475. this._triggerParameter = triggerOptions.parameter;
  23476. }
  23477. else {
  23478. this.trigger = triggerOptions;
  23479. }
  23480. this._nextActiveAction = this;
  23481. this._condition = condition;
  23482. }
  23483. // Methods
  23484. Action.prototype._prepare = function () {
  23485. };
  23486. Action.prototype.getTriggerParameter = function () {
  23487. return this._triggerParameter;
  23488. };
  23489. Action.prototype._executeCurrent = function (evt) {
  23490. if (this._nextActiveAction._condition) {
  23491. var condition = this._nextActiveAction._condition;
  23492. var currentRenderId = this._actionManager.getScene().getRenderId();
  23493. // We cache the current evaluation for the current frame
  23494. if (condition._evaluationId === currentRenderId) {
  23495. if (!condition._currentResult) {
  23496. return;
  23497. }
  23498. }
  23499. else {
  23500. condition._evaluationId = currentRenderId;
  23501. if (!condition.isValid()) {
  23502. condition._currentResult = false;
  23503. return;
  23504. }
  23505. condition._currentResult = true;
  23506. }
  23507. }
  23508. this._nextActiveAction.execute(evt);
  23509. if (this._nextActiveAction._child) {
  23510. if (!this._nextActiveAction._child._actionManager) {
  23511. this._nextActiveAction._child._actionManager = this._actionManager;
  23512. }
  23513. this._nextActiveAction = this._nextActiveAction._child;
  23514. }
  23515. else {
  23516. this._nextActiveAction = this;
  23517. }
  23518. };
  23519. Action.prototype.execute = function (evt) {
  23520. };
  23521. Action.prototype.then = function (action) {
  23522. this._child = action;
  23523. action._actionManager = this._actionManager;
  23524. action._prepare();
  23525. return action;
  23526. };
  23527. Action.prototype._getProperty = function (propertyPath) {
  23528. return this._actionManager._getProperty(propertyPath);
  23529. };
  23530. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  23531. return this._actionManager._getEffectiveTarget(target, propertyPath);
  23532. };
  23533. return Action;
  23534. })();
  23535. BABYLON.Action = Action;
  23536. })(BABYLON || (BABYLON = {}));
  23537. //# sourceMappingURL=babylon.action.js.mapvar BABYLON;
  23538. (function (BABYLON) {
  23539. /**
  23540. * ActionEvent is the event beint sent when an action is triggered.
  23541. */
  23542. var ActionEvent = (function () {
  23543. /**
  23544. * @constructor
  23545. * @param source The mesh that triggered the action.
  23546. * @param pointerX the X mouse cursor position at the time of the event
  23547. * @param pointerY the Y mouse cursor position at the time of the event
  23548. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  23549. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  23550. */
  23551. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent) {
  23552. this.source = source;
  23553. this.pointerX = pointerX;
  23554. this.pointerY = pointerY;
  23555. this.meshUnderPointer = meshUnderPointer;
  23556. this.sourceEvent = sourceEvent;
  23557. }
  23558. /**
  23559. * Helper function to auto-create an ActionEvent from a source mesh.
  23560. * @param source the source mesh that triggered the event
  23561. * @param evt {Event} The original (browser) event
  23562. */
  23563. ActionEvent.CreateNew = function (source, evt) {
  23564. var scene = source.getScene();
  23565. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  23566. };
  23567. /**
  23568. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  23569. * @param scene the scene where the event occurred
  23570. * @param evt {Event} The original (browser) event
  23571. */
  23572. ActionEvent.CreateNewFromScene = function (scene, evt) {
  23573. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  23574. };
  23575. return ActionEvent;
  23576. })();
  23577. BABYLON.ActionEvent = ActionEvent;
  23578. /**
  23579. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  23580. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  23581. */
  23582. var ActionManager = (function () {
  23583. function ActionManager(scene) {
  23584. // Members
  23585. this.actions = new Array();
  23586. this._scene = scene;
  23587. scene._actionManagers.push(this);
  23588. }
  23589. Object.defineProperty(ActionManager, "NothingTrigger", {
  23590. get: function () {
  23591. return ActionManager._NothingTrigger;
  23592. },
  23593. enumerable: true,
  23594. configurable: true
  23595. });
  23596. Object.defineProperty(ActionManager, "OnPickTrigger", {
  23597. get: function () {
  23598. return ActionManager._OnPickTrigger;
  23599. },
  23600. enumerable: true,
  23601. configurable: true
  23602. });
  23603. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  23604. get: function () {
  23605. return ActionManager._OnLeftPickTrigger;
  23606. },
  23607. enumerable: true,
  23608. configurable: true
  23609. });
  23610. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  23611. get: function () {
  23612. return ActionManager._OnRightPickTrigger;
  23613. },
  23614. enumerable: true,
  23615. configurable: true
  23616. });
  23617. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  23618. get: function () {
  23619. return ActionManager._OnCenterPickTrigger;
  23620. },
  23621. enumerable: true,
  23622. configurable: true
  23623. });
  23624. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  23625. get: function () {
  23626. return ActionManager._OnPointerOverTrigger;
  23627. },
  23628. enumerable: true,
  23629. configurable: true
  23630. });
  23631. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  23632. get: function () {
  23633. return ActionManager._OnPointerOutTrigger;
  23634. },
  23635. enumerable: true,
  23636. configurable: true
  23637. });
  23638. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  23639. get: function () {
  23640. return ActionManager._OnEveryFrameTrigger;
  23641. },
  23642. enumerable: true,
  23643. configurable: true
  23644. });
  23645. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  23646. get: function () {
  23647. return ActionManager._OnIntersectionEnterTrigger;
  23648. },
  23649. enumerable: true,
  23650. configurable: true
  23651. });
  23652. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  23653. get: function () {
  23654. return ActionManager._OnIntersectionExitTrigger;
  23655. },
  23656. enumerable: true,
  23657. configurable: true
  23658. });
  23659. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  23660. get: function () {
  23661. return ActionManager._OnKeyDownTrigger;
  23662. },
  23663. enumerable: true,
  23664. configurable: true
  23665. });
  23666. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  23667. get: function () {
  23668. return ActionManager._OnKeyUpTrigger;
  23669. },
  23670. enumerable: true,
  23671. configurable: true
  23672. });
  23673. // Methods
  23674. ActionManager.prototype.dispose = function () {
  23675. var index = this._scene._actionManagers.indexOf(this);
  23676. if (index > -1) {
  23677. this._scene._actionManagers.splice(index, 1);
  23678. }
  23679. };
  23680. ActionManager.prototype.getScene = function () {
  23681. return this._scene;
  23682. };
  23683. /**
  23684. * Does this action manager handles actions of any of the given triggers
  23685. * @param {number[]} triggers - the triggers to be tested
  23686. * @return {boolean} whether one (or more) of the triggers is handeled
  23687. */
  23688. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  23689. for (var index = 0; index < this.actions.length; index++) {
  23690. var action = this.actions[index];
  23691. if (triggers.indexOf(action.trigger) > -1) {
  23692. return true;
  23693. }
  23694. }
  23695. return false;
  23696. };
  23697. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  23698. /**
  23699. * Does this action manager has pointer triggers
  23700. * @return {boolean} whether or not it has pointer triggers
  23701. */
  23702. get: function () {
  23703. for (var index = 0; index < this.actions.length; index++) {
  23704. var action = this.actions[index];
  23705. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  23706. return true;
  23707. }
  23708. }
  23709. return false;
  23710. },
  23711. enumerable: true,
  23712. configurable: true
  23713. });
  23714. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  23715. /**
  23716. * Does this action manager has pick triggers
  23717. * @return {boolean} whether or not it has pick triggers
  23718. */
  23719. get: function () {
  23720. for (var index = 0; index < this.actions.length; index++) {
  23721. var action = this.actions[index];
  23722. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnCenterPickTrigger) {
  23723. return true;
  23724. }
  23725. }
  23726. return false;
  23727. },
  23728. enumerable: true,
  23729. configurable: true
  23730. });
  23731. /**
  23732. * Registers an action to this action manager
  23733. * @param {BABYLON.Action} action - the action to be registered
  23734. * @return {BABYLON.Action} the action amended (prepared) after registration
  23735. */
  23736. ActionManager.prototype.registerAction = function (action) {
  23737. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  23738. if (this.getScene().actionManager !== this) {
  23739. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  23740. return null;
  23741. }
  23742. }
  23743. this.actions.push(action);
  23744. action._actionManager = this;
  23745. action._prepare();
  23746. return action;
  23747. };
  23748. /**
  23749. * Process a specific trigger
  23750. * @param {number} trigger - the trigger to process
  23751. * @param evt {BABYLON.ActionEvent} the event details to be processed
  23752. */
  23753. ActionManager.prototype.processTrigger = function (trigger, evt) {
  23754. for (var index = 0; index < this.actions.length; index++) {
  23755. var action = this.actions[index];
  23756. if (action.trigger === trigger) {
  23757. if (trigger === ActionManager.OnKeyUpTrigger || trigger === ActionManager.OnKeyDownTrigger) {
  23758. var parameter = action.getTriggerParameter();
  23759. if (parameter) {
  23760. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  23761. var actualkey = String.fromCharCode(unicode).toLowerCase();
  23762. if (actualkey !== parameter.toLowerCase()) {
  23763. continue;
  23764. }
  23765. }
  23766. }
  23767. action._executeCurrent(evt);
  23768. }
  23769. }
  23770. };
  23771. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  23772. var properties = propertyPath.split(".");
  23773. for (var index = 0; index < properties.length - 1; index++) {
  23774. target = target[properties[index]];
  23775. }
  23776. return target;
  23777. };
  23778. ActionManager.prototype._getProperty = function (propertyPath) {
  23779. var properties = propertyPath.split(".");
  23780. return properties[properties.length - 1];
  23781. };
  23782. // Statics
  23783. ActionManager._NothingTrigger = 0;
  23784. ActionManager._OnPickTrigger = 1;
  23785. ActionManager._OnLeftPickTrigger = 2;
  23786. ActionManager._OnRightPickTrigger = 3;
  23787. ActionManager._OnCenterPickTrigger = 4;
  23788. ActionManager._OnPointerOverTrigger = 5;
  23789. ActionManager._OnPointerOutTrigger = 6;
  23790. ActionManager._OnEveryFrameTrigger = 7;
  23791. ActionManager._OnIntersectionEnterTrigger = 8;
  23792. ActionManager._OnIntersectionExitTrigger = 9;
  23793. ActionManager._OnKeyDownTrigger = 10;
  23794. ActionManager._OnKeyUpTrigger = 11;
  23795. return ActionManager;
  23796. })();
  23797. BABYLON.ActionManager = ActionManager;
  23798. })(BABYLON || (BABYLON = {}));
  23799. //# sourceMappingURL=babylon.actionManager.js.map
  23800. var BABYLON;
  23801. (function (BABYLON) {
  23802. var InterpolateValueAction = (function (_super) {
  23803. __extends(InterpolateValueAction, _super);
  23804. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations) {
  23805. if (duration === void 0) { duration = 1000; }
  23806. _super.call(this, triggerOptions, condition);
  23807. this.propertyPath = propertyPath;
  23808. this.value = value;
  23809. this.duration = duration;
  23810. this.stopOtherAnimations = stopOtherAnimations;
  23811. this._target = target;
  23812. }
  23813. InterpolateValueAction.prototype._prepare = function () {
  23814. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  23815. this._property = this._getProperty(this.propertyPath);
  23816. };
  23817. InterpolateValueAction.prototype.execute = function () {
  23818. var scene = this._actionManager.getScene();
  23819. var keys = [
  23820. {
  23821. frame: 0,
  23822. value: this._target[this._property]
  23823. },
  23824. {
  23825. frame: 100,
  23826. value: this.value
  23827. }
  23828. ];
  23829. var dataType;
  23830. if (typeof this.value === "number") {
  23831. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  23832. }
  23833. else if (this.value instanceof BABYLON.Color3) {
  23834. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  23835. }
  23836. else if (this.value instanceof BABYLON.Vector3) {
  23837. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  23838. }
  23839. else if (this.value instanceof BABYLON.Matrix) {
  23840. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  23841. }
  23842. else if (this.value instanceof BABYLON.Quaternion) {
  23843. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  23844. }
  23845. else {
  23846. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  23847. return;
  23848. }
  23849. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  23850. animation.setKeys(keys);
  23851. if (this.stopOtherAnimations) {
  23852. scene.stopAnimation(this._target);
  23853. }
  23854. scene.beginDirectAnimation(this._target, [animation], 0, 100);
  23855. };
  23856. return InterpolateValueAction;
  23857. })(BABYLON.Action);
  23858. BABYLON.InterpolateValueAction = InterpolateValueAction;
  23859. })(BABYLON || (BABYLON = {}));
  23860. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  23861. var BABYLON;
  23862. (function (BABYLON) {
  23863. var SwitchBooleanAction = (function (_super) {
  23864. __extends(SwitchBooleanAction, _super);
  23865. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  23866. _super.call(this, triggerOptions, condition);
  23867. this.propertyPath = propertyPath;
  23868. this._target = target;
  23869. }
  23870. SwitchBooleanAction.prototype._prepare = function () {
  23871. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  23872. this._property = this._getProperty(this.propertyPath);
  23873. };
  23874. SwitchBooleanAction.prototype.execute = function () {
  23875. this._target[this._property] = !this._target[this._property];
  23876. };
  23877. return SwitchBooleanAction;
  23878. })(BABYLON.Action);
  23879. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  23880. var SetStateAction = (function (_super) {
  23881. __extends(SetStateAction, _super);
  23882. function SetStateAction(triggerOptions, target, value, condition) {
  23883. _super.call(this, triggerOptions, condition);
  23884. this.value = value;
  23885. this._target = target;
  23886. }
  23887. SetStateAction.prototype.execute = function () {
  23888. this._target.state = this.value;
  23889. };
  23890. return SetStateAction;
  23891. })(BABYLON.Action);
  23892. BABYLON.SetStateAction = SetStateAction;
  23893. var SetValueAction = (function (_super) {
  23894. __extends(SetValueAction, _super);
  23895. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  23896. _super.call(this, triggerOptions, condition);
  23897. this.propertyPath = propertyPath;
  23898. this.value = value;
  23899. this._target = target;
  23900. }
  23901. SetValueAction.prototype._prepare = function () {
  23902. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  23903. this._property = this._getProperty(this.propertyPath);
  23904. };
  23905. SetValueAction.prototype.execute = function () {
  23906. this._target[this._property] = this.value;
  23907. };
  23908. return SetValueAction;
  23909. })(BABYLON.Action);
  23910. BABYLON.SetValueAction = SetValueAction;
  23911. var IncrementValueAction = (function (_super) {
  23912. __extends(IncrementValueAction, _super);
  23913. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  23914. _super.call(this, triggerOptions, condition);
  23915. this.propertyPath = propertyPath;
  23916. this.value = value;
  23917. this._target = target;
  23918. }
  23919. IncrementValueAction.prototype._prepare = function () {
  23920. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  23921. this._property = this._getProperty(this.propertyPath);
  23922. if (typeof this._target[this._property] !== "number") {
  23923. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  23924. }
  23925. };
  23926. IncrementValueAction.prototype.execute = function () {
  23927. this._target[this._property] += this.value;
  23928. };
  23929. return IncrementValueAction;
  23930. })(BABYLON.Action);
  23931. BABYLON.IncrementValueAction = IncrementValueAction;
  23932. var PlayAnimationAction = (function (_super) {
  23933. __extends(PlayAnimationAction, _super);
  23934. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  23935. _super.call(this, triggerOptions, condition);
  23936. this.from = from;
  23937. this.to = to;
  23938. this.loop = loop;
  23939. this._target = target;
  23940. }
  23941. PlayAnimationAction.prototype._prepare = function () {
  23942. };
  23943. PlayAnimationAction.prototype.execute = function () {
  23944. var scene = this._actionManager.getScene();
  23945. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  23946. };
  23947. return PlayAnimationAction;
  23948. })(BABYLON.Action);
  23949. BABYLON.PlayAnimationAction = PlayAnimationAction;
  23950. var StopAnimationAction = (function (_super) {
  23951. __extends(StopAnimationAction, _super);
  23952. function StopAnimationAction(triggerOptions, target, condition) {
  23953. _super.call(this, triggerOptions, condition);
  23954. this._target = target;
  23955. }
  23956. StopAnimationAction.prototype._prepare = function () {
  23957. };
  23958. StopAnimationAction.prototype.execute = function () {
  23959. var scene = this._actionManager.getScene();
  23960. scene.stopAnimation(this._target);
  23961. };
  23962. return StopAnimationAction;
  23963. })(BABYLON.Action);
  23964. BABYLON.StopAnimationAction = StopAnimationAction;
  23965. var DoNothingAction = (function (_super) {
  23966. __extends(DoNothingAction, _super);
  23967. function DoNothingAction(triggerOptions, condition) {
  23968. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  23969. _super.call(this, triggerOptions, condition);
  23970. }
  23971. DoNothingAction.prototype.execute = function () {
  23972. };
  23973. return DoNothingAction;
  23974. })(BABYLON.Action);
  23975. BABYLON.DoNothingAction = DoNothingAction;
  23976. var CombineAction = (function (_super) {
  23977. __extends(CombineAction, _super);
  23978. function CombineAction(triggerOptions, children, condition) {
  23979. _super.call(this, triggerOptions, condition);
  23980. this.children = children;
  23981. }
  23982. CombineAction.prototype._prepare = function () {
  23983. for (var index = 0; index < this.children.length; index++) {
  23984. this.children[index]._actionManager = this._actionManager;
  23985. this.children[index]._prepare();
  23986. }
  23987. };
  23988. CombineAction.prototype.execute = function (evt) {
  23989. for (var index = 0; index < this.children.length; index++) {
  23990. this.children[index].execute(evt);
  23991. }
  23992. };
  23993. return CombineAction;
  23994. })(BABYLON.Action);
  23995. BABYLON.CombineAction = CombineAction;
  23996. var ExecuteCodeAction = (function (_super) {
  23997. __extends(ExecuteCodeAction, _super);
  23998. function ExecuteCodeAction(triggerOptions, func, condition) {
  23999. _super.call(this, triggerOptions, condition);
  24000. this.func = func;
  24001. }
  24002. ExecuteCodeAction.prototype.execute = function (evt) {
  24003. this.func(evt);
  24004. };
  24005. return ExecuteCodeAction;
  24006. })(BABYLON.Action);
  24007. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  24008. var SetParentAction = (function (_super) {
  24009. __extends(SetParentAction, _super);
  24010. function SetParentAction(triggerOptions, target, parent, condition) {
  24011. _super.call(this, triggerOptions, condition);
  24012. this._target = target;
  24013. this._parent = parent;
  24014. }
  24015. SetParentAction.prototype._prepare = function () {
  24016. };
  24017. SetParentAction.prototype.execute = function () {
  24018. if (this._target.parent === this._parent) {
  24019. return;
  24020. }
  24021. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  24022. invertParentWorldMatrix.invert();
  24023. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  24024. this._target.parent = this._parent;
  24025. };
  24026. return SetParentAction;
  24027. })(BABYLON.Action);
  24028. BABYLON.SetParentAction = SetParentAction;
  24029. var PlaySoundAction = (function (_super) {
  24030. __extends(PlaySoundAction, _super);
  24031. function PlaySoundAction(triggerOptions, sound, condition) {
  24032. _super.call(this, triggerOptions, condition);
  24033. this._sound = sound;
  24034. }
  24035. PlaySoundAction.prototype._prepare = function () {
  24036. };
  24037. PlaySoundAction.prototype.execute = function () {
  24038. if (this._sound !== undefined)
  24039. this._sound.play();
  24040. };
  24041. return PlaySoundAction;
  24042. })(BABYLON.Action);
  24043. BABYLON.PlaySoundAction = PlaySoundAction;
  24044. var StopSoundAction = (function (_super) {
  24045. __extends(StopSoundAction, _super);
  24046. function StopSoundAction(triggerOptions, sound, condition) {
  24047. _super.call(this, triggerOptions, condition);
  24048. this._sound = sound;
  24049. }
  24050. StopSoundAction.prototype._prepare = function () {
  24051. };
  24052. StopSoundAction.prototype.execute = function () {
  24053. if (this._sound !== undefined)
  24054. this._sound.stop();
  24055. };
  24056. return StopSoundAction;
  24057. })(BABYLON.Action);
  24058. BABYLON.StopSoundAction = StopSoundAction;
  24059. })(BABYLON || (BABYLON = {}));
  24060. //# sourceMappingURL=babylon.directActions.js.map
  24061. var BABYLON;
  24062. (function (BABYLON) {
  24063. var Geometry = (function () {
  24064. function Geometry(id, scene, vertexData, updatable, mesh) {
  24065. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  24066. this._totalVertices = 0;
  24067. this._indices = [];
  24068. this.id = id;
  24069. this._engine = scene.getEngine();
  24070. this._meshes = [];
  24071. this._scene = scene;
  24072. // vertexData
  24073. if (vertexData) {
  24074. this.setAllVerticesData(vertexData, updatable);
  24075. }
  24076. else {
  24077. this._totalVertices = 0;
  24078. this._indices = [];
  24079. }
  24080. // applyToMesh
  24081. if (mesh) {
  24082. this.applyToMesh(mesh);
  24083. mesh.computeWorldMatrix(true);
  24084. }
  24085. }
  24086. Geometry.prototype.getScene = function () {
  24087. return this._scene;
  24088. };
  24089. Geometry.prototype.getEngine = function () {
  24090. return this._engine;
  24091. };
  24092. Geometry.prototype.isReady = function () {
  24093. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  24094. };
  24095. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  24096. vertexData.applyToGeometry(this, updatable);
  24097. };
  24098. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  24099. this._vertexBuffers = this._vertexBuffers || {};
  24100. if (this._vertexBuffers[kind]) {
  24101. this._vertexBuffers[kind].dispose();
  24102. }
  24103. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  24104. if (kind === BABYLON.VertexBuffer.PositionKind) {
  24105. stride = this._vertexBuffers[kind].getStrideSize();
  24106. this._totalVertices = data.length / stride;
  24107. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  24108. var meshes = this._meshes;
  24109. var numOfMeshes = meshes.length;
  24110. for (var index = 0; index < numOfMeshes; index++) {
  24111. var mesh = meshes[index];
  24112. mesh._resetPointsArrayCache();
  24113. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  24114. mesh._createGlobalSubMesh();
  24115. mesh.computeWorldMatrix(true);
  24116. }
  24117. }
  24118. };
  24119. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  24120. var vertexBuffer = this.getVertexBuffer(kind);
  24121. if (!vertexBuffer) {
  24122. return;
  24123. }
  24124. vertexBuffer.updateDirectly(data, offset);
  24125. };
  24126. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  24127. var vertexBuffer = this.getVertexBuffer(kind);
  24128. if (!vertexBuffer) {
  24129. return;
  24130. }
  24131. vertexBuffer.update(data);
  24132. if (kind === BABYLON.VertexBuffer.PositionKind) {
  24133. var extend;
  24134. var stride = vertexBuffer.getStrideSize();
  24135. this._totalVertices = data.length / stride;
  24136. if (updateExtends) {
  24137. extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  24138. }
  24139. var meshes = this._meshes;
  24140. var numOfMeshes = meshes.length;
  24141. for (var index = 0; index < numOfMeshes; index++) {
  24142. var mesh = meshes[index];
  24143. mesh._resetPointsArrayCache();
  24144. if (updateExtends) {
  24145. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  24146. }
  24147. }
  24148. }
  24149. };
  24150. Geometry.prototype.getTotalVertices = function () {
  24151. if (!this.isReady()) {
  24152. return 0;
  24153. }
  24154. return this._totalVertices;
  24155. };
  24156. Geometry.prototype.getVerticesData = function (kind) {
  24157. var vertexBuffer = this.getVertexBuffer(kind);
  24158. if (!vertexBuffer) {
  24159. return null;
  24160. }
  24161. return vertexBuffer.getData();
  24162. };
  24163. Geometry.prototype.getVertexBuffer = function (kind) {
  24164. if (!this.isReady()) {
  24165. return null;
  24166. }
  24167. return this._vertexBuffers[kind];
  24168. };
  24169. Geometry.prototype.getVertexBuffers = function () {
  24170. if (!this.isReady()) {
  24171. return null;
  24172. }
  24173. return this._vertexBuffers;
  24174. };
  24175. Geometry.prototype.isVerticesDataPresent = function (kind) {
  24176. if (!this._vertexBuffers) {
  24177. if (this._delayInfo) {
  24178. return this._delayInfo.indexOf(kind) !== -1;
  24179. }
  24180. return false;
  24181. }
  24182. return this._vertexBuffers[kind] !== undefined;
  24183. };
  24184. Geometry.prototype.getVerticesDataKinds = function () {
  24185. var result = [];
  24186. if (!this._vertexBuffers && this._delayInfo) {
  24187. for (var kind in this._delayInfo) {
  24188. result.push(kind);
  24189. }
  24190. }
  24191. else {
  24192. for (kind in this._vertexBuffers) {
  24193. result.push(kind);
  24194. }
  24195. }
  24196. return result;
  24197. };
  24198. Geometry.prototype.setIndices = function (indices, totalVertices) {
  24199. if (this._indexBuffer) {
  24200. this._engine._releaseBuffer(this._indexBuffer);
  24201. }
  24202. this._indices = indices;
  24203. if (this._meshes.length !== 0 && this._indices) {
  24204. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  24205. }
  24206. if (totalVertices !== undefined) {
  24207. this._totalVertices = totalVertices;
  24208. }
  24209. var meshes = this._meshes;
  24210. var numOfMeshes = meshes.length;
  24211. for (var index = 0; index < numOfMeshes; index++) {
  24212. meshes[index]._createGlobalSubMesh();
  24213. }
  24214. };
  24215. Geometry.prototype.getTotalIndices = function () {
  24216. if (!this.isReady()) {
  24217. return 0;
  24218. }
  24219. return this._indices.length;
  24220. };
  24221. Geometry.prototype.getIndices = function () {
  24222. if (!this.isReady()) {
  24223. return null;
  24224. }
  24225. return this._indices;
  24226. };
  24227. Geometry.prototype.getIndexBuffer = function () {
  24228. if (!this.isReady()) {
  24229. return null;
  24230. }
  24231. return this._indexBuffer;
  24232. };
  24233. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  24234. var meshes = this._meshes;
  24235. var index = meshes.indexOf(mesh);
  24236. if (index === -1) {
  24237. return;
  24238. }
  24239. for (var kind in this._vertexBuffers) {
  24240. this._vertexBuffers[kind].dispose();
  24241. }
  24242. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  24243. this._indexBuffer = null;
  24244. }
  24245. meshes.splice(index, 1);
  24246. mesh._geometry = null;
  24247. if (meshes.length === 0 && shouldDispose) {
  24248. this.dispose();
  24249. }
  24250. };
  24251. Geometry.prototype.applyToMesh = function (mesh) {
  24252. if (mesh._geometry === this) {
  24253. return;
  24254. }
  24255. var previousGeometry = mesh._geometry;
  24256. if (previousGeometry) {
  24257. previousGeometry.releaseForMesh(mesh);
  24258. }
  24259. var meshes = this._meshes;
  24260. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  24261. mesh._geometry = this;
  24262. this._scene.pushGeometry(this);
  24263. meshes.push(mesh);
  24264. if (this.isReady()) {
  24265. this._applyToMesh(mesh);
  24266. }
  24267. else {
  24268. mesh._boundingInfo = this._boundingInfo;
  24269. }
  24270. };
  24271. Geometry.prototype._applyToMesh = function (mesh) {
  24272. var numOfMeshes = this._meshes.length;
  24273. for (var kind in this._vertexBuffers) {
  24274. if (numOfMeshes === 1) {
  24275. this._vertexBuffers[kind].create();
  24276. }
  24277. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  24278. if (kind === BABYLON.VertexBuffer.PositionKind) {
  24279. mesh._resetPointsArrayCache();
  24280. var extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  24281. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  24282. mesh._createGlobalSubMesh();
  24283. //bounding info was just created again, world matrix should be applied again.
  24284. mesh._updateBoundingInfo();
  24285. }
  24286. }
  24287. // indexBuffer
  24288. if (numOfMeshes === 1 && this._indices) {
  24289. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  24290. }
  24291. if (this._indexBuffer) {
  24292. this._indexBuffer.references = numOfMeshes;
  24293. }
  24294. };
  24295. Geometry.prototype.load = function (scene, onLoaded) {
  24296. var _this = this;
  24297. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  24298. return;
  24299. }
  24300. if (this.isReady()) {
  24301. if (onLoaded) {
  24302. onLoaded();
  24303. }
  24304. return;
  24305. }
  24306. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  24307. scene._addPendingData(this);
  24308. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  24309. _this._delayLoadingFunction(JSON.parse(data), _this);
  24310. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  24311. _this._delayInfo = [];
  24312. scene._removePendingData(_this);
  24313. var meshes = _this._meshes;
  24314. var numOfMeshes = meshes.length;
  24315. for (var index = 0; index < numOfMeshes; index++) {
  24316. _this._applyToMesh(meshes[index]);
  24317. }
  24318. if (onLoaded) {
  24319. onLoaded();
  24320. }
  24321. }, function () {
  24322. }, scene.database);
  24323. };
  24324. Geometry.prototype.dispose = function () {
  24325. var meshes = this._meshes;
  24326. var numOfMeshes = meshes.length;
  24327. var index;
  24328. for (index = 0; index < numOfMeshes; index++) {
  24329. this.releaseForMesh(meshes[index]);
  24330. }
  24331. this._meshes = [];
  24332. for (var kind in this._vertexBuffers) {
  24333. this._vertexBuffers[kind].dispose();
  24334. }
  24335. this._vertexBuffers = [];
  24336. this._totalVertices = 0;
  24337. if (this._indexBuffer) {
  24338. this._engine._releaseBuffer(this._indexBuffer);
  24339. }
  24340. this._indexBuffer = null;
  24341. this._indices = [];
  24342. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  24343. this.delayLoadingFile = null;
  24344. this._delayLoadingFunction = null;
  24345. this._delayInfo = [];
  24346. this._boundingInfo = null; // todo: .dispose()
  24347. var geometries = this._scene.getGeometries();
  24348. index = geometries.indexOf(this);
  24349. if (index > -1) {
  24350. geometries.splice(index, 1);
  24351. }
  24352. };
  24353. Geometry.prototype.copy = function (id) {
  24354. var vertexData = new BABYLON.VertexData();
  24355. vertexData.indices = [];
  24356. var indices = this.getIndices();
  24357. for (var index = 0; index < indices.length; index++) {
  24358. vertexData.indices.push(indices[index]);
  24359. }
  24360. var updatable = false;
  24361. var stopChecking = false;
  24362. for (var kind in this._vertexBuffers) {
  24363. vertexData.set(this.getVerticesData(kind), kind);
  24364. if (!stopChecking) {
  24365. updatable = this.getVertexBuffer(kind).isUpdatable();
  24366. stopChecking = !updatable;
  24367. }
  24368. }
  24369. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  24370. geometry.delayLoadState = this.delayLoadState;
  24371. geometry.delayLoadingFile = this.delayLoadingFile;
  24372. geometry._delayLoadingFunction = this._delayLoadingFunction;
  24373. for (kind in this._delayInfo) {
  24374. geometry._delayInfo = geometry._delayInfo || [];
  24375. geometry._delayInfo.push(kind);
  24376. }
  24377. // Bounding info
  24378. var extend = BABYLON.Tools.ExtractMinAndMax(this.getVerticesData(BABYLON.VertexBuffer.PositionKind), 0, this.getTotalVertices());
  24379. geometry._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  24380. return geometry;
  24381. };
  24382. // Statics
  24383. Geometry.ExtractFromMesh = function (mesh, id) {
  24384. var geometry = mesh._geometry;
  24385. if (!geometry) {
  24386. return null;
  24387. }
  24388. return geometry.copy(id);
  24389. };
  24390. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  24391. // be aware Math.random() could cause collisions
  24392. Geometry.RandomId = function () {
  24393. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  24394. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  24395. return v.toString(16);
  24396. });
  24397. };
  24398. return Geometry;
  24399. })();
  24400. BABYLON.Geometry = Geometry;
  24401. /////// Primitives //////////////////////////////////////////////
  24402. var Geometry;
  24403. (function (Geometry) {
  24404. var Primitives;
  24405. (function (Primitives) {
  24406. /// Abstract class
  24407. var _Primitive = (function (_super) {
  24408. __extends(_Primitive, _super);
  24409. function _Primitive(id, scene, vertexData, canBeRegenerated, mesh) {
  24410. this._beingRegenerated = true;
  24411. this._canBeRegenerated = canBeRegenerated;
  24412. _super.call(this, id, scene, vertexData, false, mesh); // updatable = false to be sure not to update vertices
  24413. this._beingRegenerated = false;
  24414. }
  24415. _Primitive.prototype.canBeRegenerated = function () {
  24416. return this._canBeRegenerated;
  24417. };
  24418. _Primitive.prototype.regenerate = function () {
  24419. if (!this._canBeRegenerated) {
  24420. return;
  24421. }
  24422. this._beingRegenerated = true;
  24423. this.setAllVerticesData(this._regenerateVertexData(), false);
  24424. this._beingRegenerated = false;
  24425. };
  24426. _Primitive.prototype.asNewGeometry = function (id) {
  24427. return _super.prototype.copy.call(this, id);
  24428. };
  24429. // overrides
  24430. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  24431. if (!this._beingRegenerated) {
  24432. return;
  24433. }
  24434. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  24435. };
  24436. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  24437. if (!this._beingRegenerated) {
  24438. return;
  24439. }
  24440. _super.prototype.setVerticesData.call(this, kind, data, false);
  24441. };
  24442. // to override
  24443. // protected
  24444. _Primitive.prototype._regenerateVertexData = function () {
  24445. throw new Error("Abstract method");
  24446. };
  24447. _Primitive.prototype.copy = function (id) {
  24448. throw new Error("Must be overriden in sub-classes.");
  24449. };
  24450. return _Primitive;
  24451. })(Geometry);
  24452. Primitives._Primitive = _Primitive;
  24453. var Ribbon = (function (_super) {
  24454. __extends(Ribbon, _super);
  24455. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  24456. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  24457. this.pathArray = pathArray;
  24458. this.closeArray = closeArray;
  24459. this.closePath = closePath;
  24460. this.offset = offset;
  24461. this.side = side;
  24462. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  24463. }
  24464. Ribbon.prototype._regenerateVertexData = function () {
  24465. return BABYLON.VertexData.CreateRibbon(this.pathArray, this.closeArray, this.closePath, this.offset, this.side);
  24466. };
  24467. Ribbon.prototype.copy = function (id) {
  24468. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  24469. };
  24470. return Ribbon;
  24471. })(_Primitive);
  24472. Primitives.Ribbon = Ribbon;
  24473. var Box = (function (_super) {
  24474. __extends(Box, _super);
  24475. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  24476. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  24477. this.size = size;
  24478. this.side = side;
  24479. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  24480. }
  24481. Box.prototype._regenerateVertexData = function () {
  24482. return BABYLON.VertexData.CreateBox(this.size, this.side);
  24483. };
  24484. Box.prototype.copy = function (id) {
  24485. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  24486. };
  24487. return Box;
  24488. })(_Primitive);
  24489. Primitives.Box = Box;
  24490. var Sphere = (function (_super) {
  24491. __extends(Sphere, _super);
  24492. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  24493. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  24494. this.segments = segments;
  24495. this.diameter = diameter;
  24496. this.side = side;
  24497. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  24498. }
  24499. Sphere.prototype._regenerateVertexData = function () {
  24500. return BABYLON.VertexData.CreateSphere(this.segments, this.diameter, this.side);
  24501. };
  24502. Sphere.prototype.copy = function (id) {
  24503. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  24504. };
  24505. return Sphere;
  24506. })(_Primitive);
  24507. Primitives.Sphere = Sphere;
  24508. var Cylinder = (function (_super) {
  24509. __extends(Cylinder, _super);
  24510. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  24511. if (subdivisions === void 0) { subdivisions = 1; }
  24512. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  24513. this.height = height;
  24514. this.diameterTop = diameterTop;
  24515. this.diameterBottom = diameterBottom;
  24516. this.tessellation = tessellation;
  24517. this.subdivisions = subdivisions;
  24518. this.side = side;
  24519. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  24520. }
  24521. Cylinder.prototype._regenerateVertexData = function () {
  24522. return BABYLON.VertexData.CreateCylinder(this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.side);
  24523. };
  24524. Cylinder.prototype.copy = function (id) {
  24525. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  24526. };
  24527. return Cylinder;
  24528. })(_Primitive);
  24529. Primitives.Cylinder = Cylinder;
  24530. var Torus = (function (_super) {
  24531. __extends(Torus, _super);
  24532. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  24533. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  24534. this.diameter = diameter;
  24535. this.thickness = thickness;
  24536. this.tessellation = tessellation;
  24537. this.side = side;
  24538. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  24539. }
  24540. Torus.prototype._regenerateVertexData = function () {
  24541. return BABYLON.VertexData.CreateTorus(this.diameter, this.thickness, this.tessellation, this.side);
  24542. };
  24543. Torus.prototype.copy = function (id) {
  24544. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  24545. };
  24546. return Torus;
  24547. })(_Primitive);
  24548. Primitives.Torus = Torus;
  24549. var Ground = (function (_super) {
  24550. __extends(Ground, _super);
  24551. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  24552. this.width = width;
  24553. this.height = height;
  24554. this.subdivisions = subdivisions;
  24555. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  24556. }
  24557. Ground.prototype._regenerateVertexData = function () {
  24558. return BABYLON.VertexData.CreateGround(this.width, this.height, this.subdivisions);
  24559. };
  24560. Ground.prototype.copy = function (id) {
  24561. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  24562. };
  24563. return Ground;
  24564. })(_Primitive);
  24565. Primitives.Ground = Ground;
  24566. var TiledGround = (function (_super) {
  24567. __extends(TiledGround, _super);
  24568. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  24569. this.xmin = xmin;
  24570. this.zmin = zmin;
  24571. this.xmax = xmax;
  24572. this.zmax = zmax;
  24573. this.subdivisions = subdivisions;
  24574. this.precision = precision;
  24575. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  24576. }
  24577. TiledGround.prototype._regenerateVertexData = function () {
  24578. return BABYLON.VertexData.CreateTiledGround(this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision);
  24579. };
  24580. TiledGround.prototype.copy = function (id) {
  24581. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  24582. };
  24583. return TiledGround;
  24584. })(_Primitive);
  24585. Primitives.TiledGround = TiledGround;
  24586. var Plane = (function (_super) {
  24587. __extends(Plane, _super);
  24588. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  24589. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  24590. this.size = size;
  24591. this.side = side;
  24592. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  24593. }
  24594. Plane.prototype._regenerateVertexData = function () {
  24595. return BABYLON.VertexData.CreatePlane(this.size, this.side);
  24596. };
  24597. Plane.prototype.copy = function (id) {
  24598. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  24599. };
  24600. return Plane;
  24601. })(_Primitive);
  24602. Primitives.Plane = Plane;
  24603. var TorusKnot = (function (_super) {
  24604. __extends(TorusKnot, _super);
  24605. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  24606. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  24607. this.radius = radius;
  24608. this.tube = tube;
  24609. this.radialSegments = radialSegments;
  24610. this.tubularSegments = tubularSegments;
  24611. this.p = p;
  24612. this.q = q;
  24613. this.side = side;
  24614. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  24615. }
  24616. TorusKnot.prototype._regenerateVertexData = function () {
  24617. return BABYLON.VertexData.CreateTorusKnot(this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.side);
  24618. };
  24619. TorusKnot.prototype.copy = function (id) {
  24620. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  24621. };
  24622. return TorusKnot;
  24623. })(_Primitive);
  24624. Primitives.TorusKnot = TorusKnot;
  24625. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  24626. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  24627. })(BABYLON || (BABYLON = {}));
  24628. //# sourceMappingURL=babylon.geometry.js.map
  24629. var BABYLON;
  24630. (function (BABYLON) {
  24631. var Gamepads = (function () {
  24632. function Gamepads(ongamedpadconnected) {
  24633. var _this = this;
  24634. this.babylonGamepads = [];
  24635. this.oneGamepadConnected = false;
  24636. this.isMonitoring = false;
  24637. this.gamepadEventSupported = 'GamepadEvent' in window;
  24638. this.gamepadSupportAvailable = (navigator.getGamepads || !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  24639. 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=";
  24640. this._callbackGamepadConnected = ongamedpadconnected;
  24641. if (this.gamepadSupportAvailable) {
  24642. // Checking if the gamepad connected event is supported (like in Firefox)
  24643. if (this.gamepadEventSupported) {
  24644. window.addEventListener('gamepadconnected', function (evt) {
  24645. _this._onGamepadConnected(evt);
  24646. }, false);
  24647. window.addEventListener('gamepaddisconnected', function (evt) {
  24648. _this._onGamepadDisconnected(evt);
  24649. }, false);
  24650. }
  24651. else {
  24652. this._startMonitoringGamepads();
  24653. }
  24654. if (!this.oneGamepadConnected) {
  24655. this._insertGamepadDOMInstructions();
  24656. }
  24657. }
  24658. else {
  24659. this._insertGamepadDOMNotSupported();
  24660. }
  24661. }
  24662. Gamepads.prototype._insertGamepadDOMInstructions = function () {
  24663. Gamepads.gamepadDOMInfo = document.createElement("div");
  24664. var buttonAImage = document.createElement("img");
  24665. buttonAImage.src = this.buttonADataURL;
  24666. var spanMessage = document.createElement("span");
  24667. spanMessage.innerHTML = "<strong>to activate gamepad</strong>";
  24668. Gamepads.gamepadDOMInfo.appendChild(buttonAImage);
  24669. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  24670. Gamepads.gamepadDOMInfo.style.position = "absolute";
  24671. Gamepads.gamepadDOMInfo.style.width = "100%";
  24672. Gamepads.gamepadDOMInfo.style.height = "48px";
  24673. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  24674. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  24675. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  24676. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  24677. buttonAImage.style.position = "relative";
  24678. buttonAImage.style.bottom = "8px";
  24679. spanMessage.style.position = "relative";
  24680. spanMessage.style.fontSize = "32px";
  24681. spanMessage.style.bottom = "32px";
  24682. spanMessage.style.color = "green";
  24683. document.body.appendChild(Gamepads.gamepadDOMInfo);
  24684. };
  24685. Gamepads.prototype._insertGamepadDOMNotSupported = function () {
  24686. Gamepads.gamepadDOMInfo = document.createElement("div");
  24687. var spanMessage = document.createElement("span");
  24688. spanMessage.innerHTML = "<strong>gamepad not supported</strong>";
  24689. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  24690. Gamepads.gamepadDOMInfo.style.position = "absolute";
  24691. Gamepads.gamepadDOMInfo.style.width = "100%";
  24692. Gamepads.gamepadDOMInfo.style.height = "40px";
  24693. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  24694. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  24695. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  24696. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  24697. spanMessage.style.position = "relative";
  24698. spanMessage.style.fontSize = "32px";
  24699. spanMessage.style.color = "red";
  24700. document.body.appendChild(Gamepads.gamepadDOMInfo);
  24701. };
  24702. Gamepads.prototype.dispose = function () {
  24703. if (Gamepads.gamepadDOMInfo) {
  24704. document.body.removeChild(Gamepads.gamepadDOMInfo);
  24705. }
  24706. };
  24707. Gamepads.prototype._onGamepadConnected = function (evt) {
  24708. var newGamepad = this._addNewGamepad(evt.gamepad);
  24709. if (this._callbackGamepadConnected)
  24710. this._callbackGamepadConnected(newGamepad);
  24711. this._startMonitoringGamepads();
  24712. };
  24713. Gamepads.prototype._addNewGamepad = function (gamepad) {
  24714. if (!this.oneGamepadConnected) {
  24715. this.oneGamepadConnected = true;
  24716. if (Gamepads.gamepadDOMInfo) {
  24717. document.body.removeChild(Gamepads.gamepadDOMInfo);
  24718. Gamepads.gamepadDOMInfo = null;
  24719. }
  24720. }
  24721. var newGamepad;
  24722. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  24723. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  24724. }
  24725. else {
  24726. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  24727. }
  24728. this.babylonGamepads.push(newGamepad);
  24729. return newGamepad;
  24730. };
  24731. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  24732. for (var i in this.babylonGamepads) {
  24733. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  24734. this.babylonGamepads.splice(i, 1);
  24735. break;
  24736. }
  24737. }
  24738. // If no gamepads are left, stop the polling loop.
  24739. if (this.babylonGamepads.length == 0) {
  24740. this._stopMonitoringGamepads();
  24741. }
  24742. };
  24743. Gamepads.prototype._startMonitoringGamepads = function () {
  24744. if (!this.isMonitoring) {
  24745. this.isMonitoring = true;
  24746. this._checkGamepadsStatus();
  24747. }
  24748. };
  24749. Gamepads.prototype._stopMonitoringGamepads = function () {
  24750. this.isMonitoring = false;
  24751. };
  24752. Gamepads.prototype._checkGamepadsStatus = function () {
  24753. var _this = this;
  24754. // updating gamepad objects
  24755. this._updateGamepadObjects();
  24756. for (var i in this.babylonGamepads) {
  24757. this.babylonGamepads[i].update();
  24758. }
  24759. if (this.isMonitoring) {
  24760. if (window.requestAnimationFrame) {
  24761. window.requestAnimationFrame(function () {
  24762. _this._checkGamepadsStatus();
  24763. });
  24764. }
  24765. else if (window.mozRequestAnimationFrame) {
  24766. window.mozRequestAnimationFrame(function () {
  24767. _this._checkGamepadsStatus();
  24768. });
  24769. }
  24770. else if (window.webkitRequestAnimationFrame) {
  24771. window.webkitRequestAnimationFrame(function () {
  24772. _this._checkGamepadsStatus();
  24773. });
  24774. }
  24775. }
  24776. };
  24777. // This function is called only on Chrome, which does not yet support
  24778. // connection/disconnection events, but requires you to monitor
  24779. // an array for changes.
  24780. Gamepads.prototype._updateGamepadObjects = function () {
  24781. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  24782. for (var i = 0; i < gamepads.length; i++) {
  24783. if (gamepads[i]) {
  24784. if (!(gamepads[i].index in this.babylonGamepads)) {
  24785. var newGamepad = this._addNewGamepad(gamepads[i]);
  24786. if (this._callbackGamepadConnected) {
  24787. this._callbackGamepadConnected(newGamepad);
  24788. }
  24789. }
  24790. else {
  24791. this.babylonGamepads[i].browserGamepad = gamepads[i];
  24792. }
  24793. }
  24794. }
  24795. };
  24796. return Gamepads;
  24797. })();
  24798. BABYLON.Gamepads = Gamepads;
  24799. var StickValues = (function () {
  24800. function StickValues(x, y) {
  24801. this.x = x;
  24802. this.y = y;
  24803. }
  24804. return StickValues;
  24805. })();
  24806. BABYLON.StickValues = StickValues;
  24807. var Gamepad = (function () {
  24808. function Gamepad(id, index, browserGamepad) {
  24809. this.id = id;
  24810. this.index = index;
  24811. this.browserGamepad = browserGamepad;
  24812. if (this.browserGamepad.axes.length >= 2) {
  24813. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  24814. }
  24815. if (this.browserGamepad.axes.length >= 4) {
  24816. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  24817. }
  24818. }
  24819. Gamepad.prototype.onleftstickchanged = function (callback) {
  24820. this._onleftstickchanged = callback;
  24821. };
  24822. Gamepad.prototype.onrightstickchanged = function (callback) {
  24823. this._onrightstickchanged = callback;
  24824. };
  24825. Object.defineProperty(Gamepad.prototype, "leftStick", {
  24826. get: function () {
  24827. return this._leftStick;
  24828. },
  24829. set: function (newValues) {
  24830. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  24831. this._onleftstickchanged(newValues);
  24832. }
  24833. this._leftStick = newValues;
  24834. },
  24835. enumerable: true,
  24836. configurable: true
  24837. });
  24838. Object.defineProperty(Gamepad.prototype, "rightStick", {
  24839. get: function () {
  24840. return this._rightStick;
  24841. },
  24842. set: function (newValues) {
  24843. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  24844. this._onrightstickchanged(newValues);
  24845. }
  24846. this._rightStick = newValues;
  24847. },
  24848. enumerable: true,
  24849. configurable: true
  24850. });
  24851. Gamepad.prototype.update = function () {
  24852. if (this._leftStick) {
  24853. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  24854. }
  24855. if (this._rightStick) {
  24856. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  24857. }
  24858. };
  24859. return Gamepad;
  24860. })();
  24861. BABYLON.Gamepad = Gamepad;
  24862. var GenericPad = (function (_super) {
  24863. __extends(GenericPad, _super);
  24864. function GenericPad(id, index, gamepad) {
  24865. _super.call(this, id, index, gamepad);
  24866. this.id = id;
  24867. this.index = index;
  24868. this.gamepad = gamepad;
  24869. this._buttons = new Array(gamepad.buttons.length);
  24870. }
  24871. GenericPad.prototype.onbuttondown = function (callback) {
  24872. this._onbuttondown = callback;
  24873. };
  24874. GenericPad.prototype.onbuttonup = function (callback) {
  24875. this._onbuttonup = callback;
  24876. };
  24877. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  24878. if (newValue !== currentValue) {
  24879. if (this._onbuttondown && newValue === 1) {
  24880. this._onbuttondown(buttonIndex);
  24881. }
  24882. if (this._onbuttonup && newValue === 0) {
  24883. this._onbuttonup(buttonIndex);
  24884. }
  24885. }
  24886. return newValue;
  24887. };
  24888. GenericPad.prototype.update = function () {
  24889. _super.prototype.update.call(this);
  24890. for (var index = 0; index < this._buttons.length; index++) {
  24891. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  24892. }
  24893. };
  24894. return GenericPad;
  24895. })(Gamepad);
  24896. BABYLON.GenericPad = GenericPad;
  24897. (function (Xbox360Button) {
  24898. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  24899. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  24900. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  24901. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  24902. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  24903. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  24904. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  24905. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  24906. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  24907. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  24908. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  24909. var Xbox360Button = BABYLON.Xbox360Button;
  24910. (function (Xbox360Dpad) {
  24911. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  24912. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  24913. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  24914. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  24915. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  24916. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  24917. var Xbox360Pad = (function (_super) {
  24918. __extends(Xbox360Pad, _super);
  24919. function Xbox360Pad() {
  24920. _super.apply(this, arguments);
  24921. this._leftTrigger = 0;
  24922. this._rightTrigger = 0;
  24923. this._buttonA = 0;
  24924. this._buttonB = 0;
  24925. this._buttonX = 0;
  24926. this._buttonY = 0;
  24927. this._buttonBack = 0;
  24928. this._buttonStart = 0;
  24929. this._buttonLB = 0;
  24930. this._buttonRB = 0;
  24931. this._buttonLeftStick = 0;
  24932. this._buttonRightStick = 0;
  24933. this._dPadUp = 0;
  24934. this._dPadDown = 0;
  24935. this._dPadLeft = 0;
  24936. this._dPadRight = 0;
  24937. }
  24938. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  24939. this._onlefttriggerchanged = callback;
  24940. };
  24941. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  24942. this._onrighttriggerchanged = callback;
  24943. };
  24944. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  24945. get: function () {
  24946. return this._leftTrigger;
  24947. },
  24948. set: function (newValue) {
  24949. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  24950. this._onlefttriggerchanged(newValue);
  24951. }
  24952. this._leftTrigger = newValue;
  24953. },
  24954. enumerable: true,
  24955. configurable: true
  24956. });
  24957. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  24958. get: function () {
  24959. return this._rightTrigger;
  24960. },
  24961. set: function (newValue) {
  24962. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  24963. this._onrighttriggerchanged(newValue);
  24964. }
  24965. this._rightTrigger = newValue;
  24966. },
  24967. enumerable: true,
  24968. configurable: true
  24969. });
  24970. Xbox360Pad.prototype.onbuttondown = function (callback) {
  24971. this._onbuttondown = callback;
  24972. };
  24973. Xbox360Pad.prototype.onbuttonup = function (callback) {
  24974. this._onbuttonup = callback;
  24975. };
  24976. Xbox360Pad.prototype.ondpaddown = function (callback) {
  24977. this._ondpaddown = callback;
  24978. };
  24979. Xbox360Pad.prototype.ondpadup = function (callback) {
  24980. this._ondpadup = callback;
  24981. };
  24982. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  24983. if (newValue !== currentValue) {
  24984. if (this._onbuttondown && newValue === 1) {
  24985. this._onbuttondown(buttonType);
  24986. }
  24987. if (this._onbuttonup && newValue === 0) {
  24988. this._onbuttonup(buttonType);
  24989. }
  24990. }
  24991. return newValue;
  24992. };
  24993. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  24994. if (newValue !== currentValue) {
  24995. if (this._ondpaddown && newValue === 1) {
  24996. this._ondpaddown(buttonType);
  24997. }
  24998. if (this._ondpadup && newValue === 0) {
  24999. this._ondpadup(buttonType);
  25000. }
  25001. }
  25002. return newValue;
  25003. };
  25004. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  25005. get: function () {
  25006. return this._buttonA;
  25007. },
  25008. set: function (value) {
  25009. this._buttonA = this._setButtonValue(value, this._buttonA, 0 /* A */);
  25010. },
  25011. enumerable: true,
  25012. configurable: true
  25013. });
  25014. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  25015. get: function () {
  25016. return this._buttonB;
  25017. },
  25018. set: function (value) {
  25019. this._buttonB = this._setButtonValue(value, this._buttonB, 1 /* B */);
  25020. },
  25021. enumerable: true,
  25022. configurable: true
  25023. });
  25024. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  25025. get: function () {
  25026. return this._buttonX;
  25027. },
  25028. set: function (value) {
  25029. this._buttonX = this._setButtonValue(value, this._buttonX, 2 /* X */);
  25030. },
  25031. enumerable: true,
  25032. configurable: true
  25033. });
  25034. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  25035. get: function () {
  25036. return this._buttonY;
  25037. },
  25038. set: function (value) {
  25039. this._buttonY = this._setButtonValue(value, this._buttonY, 3 /* Y */);
  25040. },
  25041. enumerable: true,
  25042. configurable: true
  25043. });
  25044. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  25045. get: function () {
  25046. return this._buttonStart;
  25047. },
  25048. set: function (value) {
  25049. this._buttonStart = this._setButtonValue(value, this._buttonStart, 4 /* Start */);
  25050. },
  25051. enumerable: true,
  25052. configurable: true
  25053. });
  25054. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  25055. get: function () {
  25056. return this._buttonBack;
  25057. },
  25058. set: function (value) {
  25059. this._buttonBack = this._setButtonValue(value, this._buttonBack, 5 /* Back */);
  25060. },
  25061. enumerable: true,
  25062. configurable: true
  25063. });
  25064. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  25065. get: function () {
  25066. return this._buttonLB;
  25067. },
  25068. set: function (value) {
  25069. this._buttonLB = this._setButtonValue(value, this._buttonLB, 6 /* LB */);
  25070. },
  25071. enumerable: true,
  25072. configurable: true
  25073. });
  25074. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  25075. get: function () {
  25076. return this._buttonRB;
  25077. },
  25078. set: function (value) {
  25079. this._buttonRB = this._setButtonValue(value, this._buttonRB, 7 /* RB */);
  25080. },
  25081. enumerable: true,
  25082. configurable: true
  25083. });
  25084. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  25085. get: function () {
  25086. return this._buttonLeftStick;
  25087. },
  25088. set: function (value) {
  25089. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, 8 /* LeftStick */);
  25090. },
  25091. enumerable: true,
  25092. configurable: true
  25093. });
  25094. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  25095. get: function () {
  25096. return this._buttonRightStick;
  25097. },
  25098. set: function (value) {
  25099. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, 9 /* RightStick */);
  25100. },
  25101. enumerable: true,
  25102. configurable: true
  25103. });
  25104. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  25105. get: function () {
  25106. return this._dPadUp;
  25107. },
  25108. set: function (value) {
  25109. this._dPadUp = this._setDPadValue(value, this._dPadUp, 0 /* Up */);
  25110. },
  25111. enumerable: true,
  25112. configurable: true
  25113. });
  25114. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  25115. get: function () {
  25116. return this._dPadDown;
  25117. },
  25118. set: function (value) {
  25119. this._dPadDown = this._setDPadValue(value, this._dPadDown, 1 /* Down */);
  25120. },
  25121. enumerable: true,
  25122. configurable: true
  25123. });
  25124. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  25125. get: function () {
  25126. return this._dPadLeft;
  25127. },
  25128. set: function (value) {
  25129. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, 2 /* Left */);
  25130. },
  25131. enumerable: true,
  25132. configurable: true
  25133. });
  25134. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  25135. get: function () {
  25136. return this._dPadRight;
  25137. },
  25138. set: function (value) {
  25139. this._dPadRight = this._setDPadValue(value, this._dPadRight, 3 /* Right */);
  25140. },
  25141. enumerable: true,
  25142. configurable: true
  25143. });
  25144. Xbox360Pad.prototype.update = function () {
  25145. _super.prototype.update.call(this);
  25146. this.buttonA = this.browserGamepad.buttons[0].value;
  25147. this.buttonB = this.browserGamepad.buttons[1].value;
  25148. this.buttonX = this.browserGamepad.buttons[2].value;
  25149. this.buttonY = this.browserGamepad.buttons[3].value;
  25150. this.buttonLB = this.browserGamepad.buttons[4].value;
  25151. this.buttonRB = this.browserGamepad.buttons[5].value;
  25152. this.leftTrigger = this.browserGamepad.buttons[6].value;
  25153. this.rightTrigger = this.browserGamepad.buttons[7].value;
  25154. this.buttonBack = this.browserGamepad.buttons[8].value;
  25155. this.buttonStart = this.browserGamepad.buttons[9].value;
  25156. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  25157. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  25158. this.dPadUp = this.browserGamepad.buttons[12].value;
  25159. this.dPadDown = this.browserGamepad.buttons[13].value;
  25160. this.dPadLeft = this.browserGamepad.buttons[14].value;
  25161. this.dPadRight = this.browserGamepad.buttons[15].value;
  25162. };
  25163. return Xbox360Pad;
  25164. })(Gamepad);
  25165. BABYLON.Xbox360Pad = Xbox360Pad;
  25166. })(BABYLON || (BABYLON = {}));
  25167. //# sourceMappingURL=babylon.gamepads.js.map
  25168. var BABYLON;
  25169. (function (BABYLON) {
  25170. // We're mainly based on the logic defined into the FreeCamera code
  25171. var GamepadCamera = (function (_super) {
  25172. __extends(GamepadCamera, _super);
  25173. function GamepadCamera(name, position, scene) {
  25174. var _this = this;
  25175. _super.call(this, name, position, scene);
  25176. this.angularSensibility = 200;
  25177. this.moveSensibility = 75;
  25178. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  25179. _this._onNewGameConnected(gamepad);
  25180. });
  25181. }
  25182. GamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  25183. // Only the first gamepad can control the camera
  25184. if (gamepad.index === 0) {
  25185. this._gamepad = gamepad;
  25186. }
  25187. };
  25188. GamepadCamera.prototype._checkInputs = function () {
  25189. if (!this._gamepad) {
  25190. return;
  25191. }
  25192. var LSValues = this._gamepad.leftStick;
  25193. var normalizedLX = LSValues.x / this.moveSensibility;
  25194. var normalizedLY = LSValues.y / this.moveSensibility;
  25195. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  25196. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  25197. var RSValues = this._gamepad.rightStick;
  25198. var normalizedRX = RSValues.x / this.angularSensibility;
  25199. var normalizedRY = RSValues.y / this.angularSensibility;
  25200. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  25201. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  25202. ;
  25203. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  25204. var speed = this._computeLocalCameraSpeed() * 50.0;
  25205. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  25206. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  25207. this.cameraRotation = this.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  25208. };
  25209. GamepadCamera.prototype.dispose = function () {
  25210. this._gamepads.dispose();
  25211. _super.prototype.dispose.call(this);
  25212. };
  25213. return GamepadCamera;
  25214. })(BABYLON.FreeCamera);
  25215. BABYLON.GamepadCamera = GamepadCamera;
  25216. })(BABYLON || (BABYLON = {}));
  25217. //# sourceMappingURL=babylon.gamepadCamera.js.map
  25218. var BABYLON;
  25219. (function (BABYLON) {
  25220. var LinesMesh = (function (_super) {
  25221. __extends(LinesMesh, _super);
  25222. function LinesMesh(name, scene, updatable) {
  25223. if (updatable === void 0) { updatable = false; }
  25224. _super.call(this, name, scene);
  25225. this.color = new BABYLON.Color3(1, 1, 1);
  25226. this.alpha = 1;
  25227. this._indices = new Array();
  25228. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  25229. attributes: ["position"],
  25230. uniforms: ["worldViewProjection", "color"],
  25231. needAlphaBlending: true
  25232. });
  25233. }
  25234. Object.defineProperty(LinesMesh.prototype, "material", {
  25235. get: function () {
  25236. return this._colorShader;
  25237. },
  25238. enumerable: true,
  25239. configurable: true
  25240. });
  25241. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  25242. get: function () {
  25243. return false;
  25244. },
  25245. enumerable: true,
  25246. configurable: true
  25247. });
  25248. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  25249. get: function () {
  25250. return false;
  25251. },
  25252. enumerable: true,
  25253. configurable: true
  25254. });
  25255. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  25256. var engine = this.getScene().getEngine();
  25257. var indexToBind = this._geometry.getIndexBuffer();
  25258. // VBOs
  25259. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  25260. // Color
  25261. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  25262. };
  25263. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  25264. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  25265. return;
  25266. }
  25267. var engine = this.getScene().getEngine();
  25268. // Draw order
  25269. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  25270. };
  25271. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  25272. return null;
  25273. };
  25274. LinesMesh.prototype.dispose = function (doNotRecurse) {
  25275. this._colorShader.dispose();
  25276. _super.prototype.dispose.call(this, doNotRecurse);
  25277. };
  25278. return LinesMesh;
  25279. })(BABYLON.Mesh);
  25280. BABYLON.LinesMesh = LinesMesh;
  25281. })(BABYLON || (BABYLON = {}));
  25282. //# sourceMappingURL=babylon.linesMesh.js.mapvar BABYLON;
  25283. (function (BABYLON) {
  25284. var OutlineRenderer = (function () {
  25285. function OutlineRenderer(scene) {
  25286. this._scene = scene;
  25287. }
  25288. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  25289. var _this = this;
  25290. if (useOverlay === void 0) { useOverlay = false; }
  25291. var scene = this._scene;
  25292. var engine = this._scene.getEngine();
  25293. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  25294. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  25295. return;
  25296. }
  25297. var mesh = subMesh.getRenderingMesh();
  25298. var material = subMesh.getMaterial();
  25299. engine.enableEffect(this._effect);
  25300. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  25301. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  25302. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  25303. // Bones
  25304. if (mesh.useBones) {
  25305. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  25306. }
  25307. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  25308. // Alpha test
  25309. if (material && material.needAlphaTesting()) {
  25310. var alphaTexture = material.getAlphaTestTexture();
  25311. this._effect.setTexture("diffuseSampler", alphaTexture);
  25312. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  25313. }
  25314. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  25315. _this._effect.setMatrix("world", world);
  25316. });
  25317. };
  25318. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  25319. var defines = [];
  25320. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  25321. var mesh = subMesh.getMesh();
  25322. var material = subMesh.getMaterial();
  25323. // Alpha test
  25324. if (material && material.needAlphaTesting()) {
  25325. defines.push("#define ALPHATEST");
  25326. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  25327. attribs.push(BABYLON.VertexBuffer.UVKind);
  25328. defines.push("#define UV1");
  25329. }
  25330. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  25331. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  25332. defines.push("#define UV2");
  25333. }
  25334. }
  25335. // Bones
  25336. if (mesh.useBones) {
  25337. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  25338. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  25339. defines.push("#define BONES");
  25340. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  25341. }
  25342. // Instances
  25343. if (useInstances) {
  25344. defines.push("#define INSTANCES");
  25345. attribs.push("world0");
  25346. attribs.push("world1");
  25347. attribs.push("world2");
  25348. attribs.push("world3");
  25349. }
  25350. // Get correct effect
  25351. var join = defines.join("\n");
  25352. if (this._cachedDefines !== join) {
  25353. this._cachedDefines = join;
  25354. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  25355. }
  25356. return this._effect.isReady();
  25357. };
  25358. return OutlineRenderer;
  25359. })();
  25360. BABYLON.OutlineRenderer = OutlineRenderer;
  25361. })(BABYLON || (BABYLON = {}));
  25362. //# sourceMappingURL=babylon.outlineRenderer.js.mapvar BABYLON;
  25363. (function (BABYLON) {
  25364. var MeshAssetTask = (function () {
  25365. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  25366. this.name = name;
  25367. this.meshesNames = meshesNames;
  25368. this.rootUrl = rootUrl;
  25369. this.sceneFilename = sceneFilename;
  25370. this.isCompleted = false;
  25371. }
  25372. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  25373. var _this = this;
  25374. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  25375. _this.loadedMeshes = meshes;
  25376. _this.loadedParticleSystems = particleSystems;
  25377. _this.loadedSkeletons = skeletons;
  25378. _this.isCompleted = true;
  25379. if (_this.onSuccess) {
  25380. _this.onSuccess(_this);
  25381. }
  25382. onSuccess();
  25383. }, null, function () {
  25384. if (_this.onError) {
  25385. _this.onError(_this);
  25386. }
  25387. onError();
  25388. });
  25389. };
  25390. return MeshAssetTask;
  25391. })();
  25392. BABYLON.MeshAssetTask = MeshAssetTask;
  25393. var TextFileAssetTask = (function () {
  25394. function TextFileAssetTask(name, url) {
  25395. this.name = name;
  25396. this.url = url;
  25397. this.isCompleted = false;
  25398. }
  25399. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  25400. var _this = this;
  25401. BABYLON.Tools.LoadFile(this.url, function (data) {
  25402. _this.text = data;
  25403. _this.isCompleted = true;
  25404. if (_this.onSuccess) {
  25405. _this.onSuccess(_this);
  25406. }
  25407. onSuccess();
  25408. }, null, scene.database, false, function () {
  25409. if (_this.onError) {
  25410. _this.onError(_this);
  25411. }
  25412. onError();
  25413. });
  25414. };
  25415. return TextFileAssetTask;
  25416. })();
  25417. BABYLON.TextFileAssetTask = TextFileAssetTask;
  25418. var BinaryFileAssetTask = (function () {
  25419. function BinaryFileAssetTask(name, url) {
  25420. this.name = name;
  25421. this.url = url;
  25422. this.isCompleted = false;
  25423. }
  25424. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  25425. var _this = this;
  25426. BABYLON.Tools.LoadFile(this.url, function (data) {
  25427. _this.data = data;
  25428. _this.isCompleted = true;
  25429. if (_this.onSuccess) {
  25430. _this.onSuccess(_this);
  25431. }
  25432. onSuccess();
  25433. }, null, scene.database, true, function () {
  25434. if (_this.onError) {
  25435. _this.onError(_this);
  25436. }
  25437. onError();
  25438. });
  25439. };
  25440. return BinaryFileAssetTask;
  25441. })();
  25442. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  25443. var ImageAssetTask = (function () {
  25444. function ImageAssetTask(name, url) {
  25445. this.name = name;
  25446. this.url = url;
  25447. this.isCompleted = false;
  25448. }
  25449. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  25450. var _this = this;
  25451. var img = new Image();
  25452. img.onload = function () {
  25453. _this.image = img;
  25454. _this.isCompleted = true;
  25455. if (_this.onSuccess) {
  25456. _this.onSuccess(_this);
  25457. }
  25458. onSuccess();
  25459. };
  25460. img.onerror = function () {
  25461. if (_this.onError) {
  25462. _this.onError(_this);
  25463. }
  25464. onError();
  25465. };
  25466. img.src = this.url;
  25467. };
  25468. return ImageAssetTask;
  25469. })();
  25470. BABYLON.ImageAssetTask = ImageAssetTask;
  25471. var TextureAssetTask = (function () {
  25472. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  25473. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  25474. this.name = name;
  25475. this.url = url;
  25476. this.noMipmap = noMipmap;
  25477. this.invertY = invertY;
  25478. this.samplingMode = samplingMode;
  25479. this.isCompleted = false;
  25480. }
  25481. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  25482. var _this = this;
  25483. var onload = function () {
  25484. _this.isCompleted = true;
  25485. if (_this.onSuccess) {
  25486. _this.onSuccess(_this);
  25487. }
  25488. onSuccess();
  25489. };
  25490. var onerror = function () {
  25491. if (_this.onError) {
  25492. _this.onError(_this);
  25493. }
  25494. onError();
  25495. };
  25496. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onError);
  25497. };
  25498. return TextureAssetTask;
  25499. })();
  25500. BABYLON.TextureAssetTask = TextureAssetTask;
  25501. var AssetsManager = (function () {
  25502. function AssetsManager(scene) {
  25503. this._tasks = new Array();
  25504. this._waitingTasksCount = 0;
  25505. this.useDefaultLoadingScreen = true;
  25506. this._scene = scene;
  25507. }
  25508. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  25509. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  25510. this._tasks.push(task);
  25511. return task;
  25512. };
  25513. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  25514. var task = new TextFileAssetTask(taskName, url);
  25515. this._tasks.push(task);
  25516. return task;
  25517. };
  25518. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  25519. var task = new BinaryFileAssetTask(taskName, url);
  25520. this._tasks.push(task);
  25521. return task;
  25522. };
  25523. AssetsManager.prototype.addImageTask = function (taskName, url) {
  25524. var task = new ImageAssetTask(taskName, url);
  25525. this._tasks.push(task);
  25526. return task;
  25527. };
  25528. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  25529. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  25530. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  25531. this._tasks.push(task);
  25532. return task;
  25533. };
  25534. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  25535. this._waitingTasksCount--;
  25536. if (this._waitingTasksCount === 0) {
  25537. if (this.onFinish) {
  25538. this.onFinish(this._tasks);
  25539. }
  25540. this._scene.getEngine().hideLoadingUI();
  25541. }
  25542. };
  25543. AssetsManager.prototype._runTask = function (task) {
  25544. var _this = this;
  25545. task.run(this._scene, function () {
  25546. if (_this.onTaskSuccess) {
  25547. _this.onTaskSuccess(task);
  25548. }
  25549. _this._decreaseWaitingTasksCount();
  25550. }, function () {
  25551. if (_this.onTaskError) {
  25552. _this.onTaskError(task);
  25553. }
  25554. _this._decreaseWaitingTasksCount();
  25555. });
  25556. };
  25557. AssetsManager.prototype.reset = function () {
  25558. this._tasks = new Array();
  25559. return this;
  25560. };
  25561. AssetsManager.prototype.load = function () {
  25562. this._waitingTasksCount = this._tasks.length;
  25563. if (this._waitingTasksCount === 0) {
  25564. if (this.onFinish) {
  25565. this.onFinish(this._tasks);
  25566. }
  25567. return this;
  25568. }
  25569. if (this.useDefaultLoadingScreen) {
  25570. this._scene.getEngine().displayLoadingUI();
  25571. }
  25572. for (var index = 0; index < this._tasks.length; index++) {
  25573. var task = this._tasks[index];
  25574. this._runTask(task);
  25575. }
  25576. return this;
  25577. };
  25578. return AssetsManager;
  25579. })();
  25580. BABYLON.AssetsManager = AssetsManager;
  25581. })(BABYLON || (BABYLON = {}));
  25582. //# sourceMappingURL=babylon.assetsManager.js.map
  25583. var BABYLON;
  25584. (function (BABYLON) {
  25585. var VRDeviceOrientationCamera = (function (_super) {
  25586. __extends(VRDeviceOrientationCamera, _super);
  25587. function VRDeviceOrientationCamera(name, position, scene) {
  25588. _super.call(this, name, position, scene);
  25589. this._alpha = 0;
  25590. this._beta = 0;
  25591. this._gamma = 0;
  25592. }
  25593. VRDeviceOrientationCamera.prototype._onOrientationEvent = function (evt) {
  25594. this._alpha = +evt.alpha | 0;
  25595. this._beta = +evt.beta | 0;
  25596. this._gamma = +evt.gamma | 0;
  25597. if (this._gamma < 0) {
  25598. this._gamma = 90 + this._gamma;
  25599. }
  25600. else {
  25601. // Incline it in the correct angle.
  25602. this._gamma = 270 - this._gamma;
  25603. }
  25604. this.rotation.x = this._gamma / 180.0 * Math.PI;
  25605. this.rotation.y = -this._alpha / 180.0 * Math.PI;
  25606. this.rotation.z = this._beta / 180.0 * Math.PI;
  25607. };
  25608. return VRDeviceOrientationCamera;
  25609. })(BABYLON.OculusCamera);
  25610. BABYLON.VRDeviceOrientationCamera = VRDeviceOrientationCamera;
  25611. })(BABYLON || (BABYLON = {}));
  25612. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  25613. var BABYLON;
  25614. (function (BABYLON) {
  25615. var WebVRCamera = (function (_super) {
  25616. __extends(WebVRCamera, _super);
  25617. function WebVRCamera(name, position, scene) {
  25618. _super.call(this, name, position, scene);
  25619. this._hmdDevice = null;
  25620. this._sensorDevice = null;
  25621. this._cacheState = null;
  25622. this._cacheQuaternion = new BABYLON.Quaternion();
  25623. this._cacheRotation = BABYLON.Vector3.Zero();
  25624. this._vrEnabled = false;
  25625. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  25626. }
  25627. WebVRCamera.prototype._getWebVRDevices = function (devices) {
  25628. var size = devices.length;
  25629. var i = 0;
  25630. // Reset devices.
  25631. this._sensorDevice = null;
  25632. this._hmdDevice = null;
  25633. while (i < size && this._hmdDevice === null) {
  25634. if (devices[i] instanceof HMDVRDevice) {
  25635. this._hmdDevice = devices[i];
  25636. }
  25637. i++;
  25638. }
  25639. i = 0;
  25640. while (i < size && this._sensorDevice === null) {
  25641. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  25642. this._sensorDevice = devices[i];
  25643. }
  25644. i++;
  25645. }
  25646. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  25647. };
  25648. WebVRCamera.prototype._update = function () {
  25649. if (this._vrEnabled) {
  25650. this._cacheState = this._sensorDevice.getState();
  25651. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  25652. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  25653. this.rotation.x = -this._cacheRotation.z;
  25654. this.rotation.y = -this._cacheRotation.y;
  25655. this.rotation.z = this._cacheRotation.x;
  25656. }
  25657. _super.prototype._update.call(this);
  25658. };
  25659. WebVRCamera.prototype.attachControl = function (element, noPreventDefault) {
  25660. _super.prototype.attachControl.call(this, element, noPreventDefault);
  25661. if (navigator.getVRDevices) {
  25662. navigator.getVRDevices().then(this._getWebVRDevices);
  25663. }
  25664. else if (navigator.mozGetVRDevices) {
  25665. navigator.mozGetVRDevices(this._getWebVRDevices);
  25666. }
  25667. };
  25668. WebVRCamera.prototype.detachControl = function (element) {
  25669. _super.prototype.detachControl.call(this, element);
  25670. this._vrEnabled = false;
  25671. };
  25672. return WebVRCamera;
  25673. })(BABYLON.OculusCamera);
  25674. BABYLON.WebVRCamera = WebVRCamera;
  25675. })(BABYLON || (BABYLON = {}));
  25676. //# sourceMappingURL=babylon.webVRCamera.js.map
  25677. var BABYLON;
  25678. (function (BABYLON) {
  25679. // Standard optimizations
  25680. var SceneOptimization = (function () {
  25681. function SceneOptimization(priority) {
  25682. if (priority === void 0) { priority = 0; }
  25683. this.priority = priority;
  25684. this.apply = function (scene) {
  25685. return true; // Return true if everything that can be done was applied
  25686. };
  25687. }
  25688. return SceneOptimization;
  25689. })();
  25690. BABYLON.SceneOptimization = SceneOptimization;
  25691. var TextureOptimization = (function (_super) {
  25692. __extends(TextureOptimization, _super);
  25693. function TextureOptimization(priority, maximumSize) {
  25694. var _this = this;
  25695. if (priority === void 0) { priority = 0; }
  25696. if (maximumSize === void 0) { maximumSize = 1024; }
  25697. _super.call(this, priority);
  25698. this.priority = priority;
  25699. this.maximumSize = maximumSize;
  25700. this.apply = function (scene) {
  25701. var allDone = true;
  25702. for (var index = 0; index < scene.textures.length; index++) {
  25703. var texture = scene.textures[index];
  25704. if (!texture.canRescale) {
  25705. continue;
  25706. }
  25707. var currentSize = texture.getSize();
  25708. var maxDimension = Math.max(currentSize.width, currentSize.height);
  25709. if (maxDimension > _this.maximumSize) {
  25710. texture.scale(0.5);
  25711. allDone = false;
  25712. }
  25713. }
  25714. return allDone;
  25715. };
  25716. }
  25717. return TextureOptimization;
  25718. })(SceneOptimization);
  25719. BABYLON.TextureOptimization = TextureOptimization;
  25720. var HardwareScalingOptimization = (function (_super) {
  25721. __extends(HardwareScalingOptimization, _super);
  25722. function HardwareScalingOptimization(priority, maximumScale) {
  25723. var _this = this;
  25724. if (priority === void 0) { priority = 0; }
  25725. if (maximumScale === void 0) { maximumScale = 2; }
  25726. _super.call(this, priority);
  25727. this.priority = priority;
  25728. this.maximumScale = maximumScale;
  25729. this._currentScale = 1;
  25730. this.apply = function (scene) {
  25731. _this._currentScale++;
  25732. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  25733. return _this._currentScale >= _this.maximumScale;
  25734. };
  25735. }
  25736. return HardwareScalingOptimization;
  25737. })(SceneOptimization);
  25738. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  25739. var ShadowsOptimization = (function (_super) {
  25740. __extends(ShadowsOptimization, _super);
  25741. function ShadowsOptimization() {
  25742. _super.apply(this, arguments);
  25743. this.apply = function (scene) {
  25744. scene.shadowsEnabled = false;
  25745. return true;
  25746. };
  25747. }
  25748. return ShadowsOptimization;
  25749. })(SceneOptimization);
  25750. BABYLON.ShadowsOptimization = ShadowsOptimization;
  25751. var PostProcessesOptimization = (function (_super) {
  25752. __extends(PostProcessesOptimization, _super);
  25753. function PostProcessesOptimization() {
  25754. _super.apply(this, arguments);
  25755. this.apply = function (scene) {
  25756. scene.postProcessesEnabled = false;
  25757. return true;
  25758. };
  25759. }
  25760. return PostProcessesOptimization;
  25761. })(SceneOptimization);
  25762. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  25763. var LensFlaresOptimization = (function (_super) {
  25764. __extends(LensFlaresOptimization, _super);
  25765. function LensFlaresOptimization() {
  25766. _super.apply(this, arguments);
  25767. this.apply = function (scene) {
  25768. scene.lensFlaresEnabled = false;
  25769. return true;
  25770. };
  25771. }
  25772. return LensFlaresOptimization;
  25773. })(SceneOptimization);
  25774. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  25775. var ParticlesOptimization = (function (_super) {
  25776. __extends(ParticlesOptimization, _super);
  25777. function ParticlesOptimization() {
  25778. _super.apply(this, arguments);
  25779. this.apply = function (scene) {
  25780. scene.particlesEnabled = false;
  25781. return true;
  25782. };
  25783. }
  25784. return ParticlesOptimization;
  25785. })(SceneOptimization);
  25786. BABYLON.ParticlesOptimization = ParticlesOptimization;
  25787. var RenderTargetsOptimization = (function (_super) {
  25788. __extends(RenderTargetsOptimization, _super);
  25789. function RenderTargetsOptimization() {
  25790. _super.apply(this, arguments);
  25791. this.apply = function (scene) {
  25792. scene.renderTargetsEnabled = false;
  25793. return true;
  25794. };
  25795. }
  25796. return RenderTargetsOptimization;
  25797. })(SceneOptimization);
  25798. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  25799. var MergeMeshesOptimization = (function (_super) {
  25800. __extends(MergeMeshesOptimization, _super);
  25801. function MergeMeshesOptimization() {
  25802. var _this = this;
  25803. _super.apply(this, arguments);
  25804. this._canBeMerged = function (abstractMesh) {
  25805. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  25806. return false;
  25807. }
  25808. var mesh = abstractMesh;
  25809. if (!mesh.isVisible || !mesh.isEnabled()) {
  25810. return false;
  25811. }
  25812. if (mesh.instances.length > 0) {
  25813. return false;
  25814. }
  25815. if (mesh.skeleton || mesh.hasLODLevels) {
  25816. return false;
  25817. }
  25818. return true;
  25819. };
  25820. this.apply = function (scene) {
  25821. var globalPool = scene.meshes.slice(0);
  25822. var globalLength = globalPool.length;
  25823. for (var index = 0; index < globalLength; index++) {
  25824. var currentPool = new Array();
  25825. var current = globalPool[index];
  25826. // Checks
  25827. if (!_this._canBeMerged(current)) {
  25828. continue;
  25829. }
  25830. currentPool.push(current);
  25831. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  25832. var otherMesh = globalPool[subIndex];
  25833. if (!_this._canBeMerged(otherMesh)) {
  25834. continue;
  25835. }
  25836. if (otherMesh.material !== current.material) {
  25837. continue;
  25838. }
  25839. if (otherMesh.checkCollisions !== current.checkCollisions) {
  25840. continue;
  25841. }
  25842. currentPool.push(otherMesh);
  25843. globalLength--;
  25844. globalPool.splice(subIndex, 1);
  25845. subIndex--;
  25846. }
  25847. if (currentPool.length < 2) {
  25848. continue;
  25849. }
  25850. // Merge meshes
  25851. BABYLON.Mesh.MergeMeshes(currentPool);
  25852. }
  25853. return true;
  25854. };
  25855. }
  25856. return MergeMeshesOptimization;
  25857. })(SceneOptimization);
  25858. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  25859. // Options
  25860. var SceneOptimizerOptions = (function () {
  25861. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  25862. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  25863. if (trackerDuration === void 0) { trackerDuration = 2000; }
  25864. this.targetFrameRate = targetFrameRate;
  25865. this.trackerDuration = trackerDuration;
  25866. this.optimizations = new Array();
  25867. }
  25868. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  25869. var result = new SceneOptimizerOptions(targetFrameRate);
  25870. var priority = 0;
  25871. result.optimizations.push(new MergeMeshesOptimization(priority));
  25872. result.optimizations.push(new ShadowsOptimization(priority));
  25873. result.optimizations.push(new LensFlaresOptimization(priority));
  25874. // Next priority
  25875. priority++;
  25876. result.optimizations.push(new PostProcessesOptimization(priority));
  25877. result.optimizations.push(new ParticlesOptimization(priority));
  25878. // Next priority
  25879. priority++;
  25880. result.optimizations.push(new TextureOptimization(priority, 1024));
  25881. return result;
  25882. };
  25883. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  25884. var result = new SceneOptimizerOptions(targetFrameRate);
  25885. var priority = 0;
  25886. result.optimizations.push(new MergeMeshesOptimization(priority));
  25887. result.optimizations.push(new ShadowsOptimization(priority));
  25888. result.optimizations.push(new LensFlaresOptimization(priority));
  25889. // Next priority
  25890. priority++;
  25891. result.optimizations.push(new PostProcessesOptimization(priority));
  25892. result.optimizations.push(new ParticlesOptimization(priority));
  25893. // Next priority
  25894. priority++;
  25895. result.optimizations.push(new TextureOptimization(priority, 512));
  25896. // Next priority
  25897. priority++;
  25898. result.optimizations.push(new RenderTargetsOptimization(priority));
  25899. // Next priority
  25900. priority++;
  25901. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  25902. return result;
  25903. };
  25904. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  25905. var result = new SceneOptimizerOptions(targetFrameRate);
  25906. var priority = 0;
  25907. result.optimizations.push(new MergeMeshesOptimization(priority));
  25908. result.optimizations.push(new ShadowsOptimization(priority));
  25909. result.optimizations.push(new LensFlaresOptimization(priority));
  25910. // Next priority
  25911. priority++;
  25912. result.optimizations.push(new PostProcessesOptimization(priority));
  25913. result.optimizations.push(new ParticlesOptimization(priority));
  25914. // Next priority
  25915. priority++;
  25916. result.optimizations.push(new TextureOptimization(priority, 256));
  25917. // Next priority
  25918. priority++;
  25919. result.optimizations.push(new RenderTargetsOptimization(priority));
  25920. // Next priority
  25921. priority++;
  25922. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  25923. return result;
  25924. };
  25925. return SceneOptimizerOptions;
  25926. })();
  25927. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  25928. // Scene optimizer tool
  25929. var SceneOptimizer = (function () {
  25930. function SceneOptimizer() {
  25931. }
  25932. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  25933. // TODO: add an epsilon
  25934. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  25935. if (onSuccess) {
  25936. onSuccess();
  25937. }
  25938. return;
  25939. }
  25940. // Apply current level of optimizations
  25941. var allDone = true;
  25942. var noOptimizationApplied = true;
  25943. for (var index = 0; index < options.optimizations.length; index++) {
  25944. var optimization = options.optimizations[index];
  25945. if (optimization.priority === currentPriorityLevel) {
  25946. noOptimizationApplied = false;
  25947. allDone = allDone && optimization.apply(scene);
  25948. }
  25949. }
  25950. // If no optimization was applied, this is a failure :(
  25951. if (noOptimizationApplied) {
  25952. if (onFailure) {
  25953. onFailure();
  25954. }
  25955. return;
  25956. }
  25957. // If all optimizations were done, move to next level
  25958. if (allDone) {
  25959. currentPriorityLevel++;
  25960. }
  25961. // Let's the system running for a specific amount of time before checking FPS
  25962. scene.executeWhenReady(function () {
  25963. setTimeout(function () {
  25964. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  25965. }, options.trackerDuration);
  25966. });
  25967. };
  25968. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  25969. if (!options) {
  25970. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  25971. }
  25972. // Let's the system running for a specific amount of time before checking FPS
  25973. scene.executeWhenReady(function () {
  25974. setTimeout(function () {
  25975. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  25976. }, options.trackerDuration);
  25977. });
  25978. };
  25979. return SceneOptimizer;
  25980. })();
  25981. BABYLON.SceneOptimizer = SceneOptimizer;
  25982. })(BABYLON || (BABYLON = {}));
  25983. //# sourceMappingURL=babylon.sceneOptimizer.js.mapvar BABYLON;
  25984. (function (BABYLON) {
  25985. var Internals;
  25986. (function (Internals) {
  25987. var MeshLODLevel = (function () {
  25988. function MeshLODLevel(distance, mesh) {
  25989. this.distance = distance;
  25990. this.mesh = mesh;
  25991. }
  25992. return MeshLODLevel;
  25993. })();
  25994. Internals.MeshLODLevel = MeshLODLevel;
  25995. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  25996. })(BABYLON || (BABYLON = {}));
  25997. //# sourceMappingURL=babylon.meshLODLevel.js.mapvar BABYLON;
  25998. (function (BABYLON) {
  25999. var AudioEngine = (function () {
  26000. function AudioEngine() {
  26001. this.audioContext = null;
  26002. this.canUseWebAudio = false;
  26003. this.WarnedWebAudioUnsupported = false;
  26004. try {
  26005. if (typeof AudioContext !== 'undefined') {
  26006. this.audioContext = new AudioContext();
  26007. this.canUseWebAudio = true;
  26008. }
  26009. else if (typeof webkitAudioContext !== 'undefined') {
  26010. this.audioContext = new webkitAudioContext();
  26011. this.canUseWebAudio = true;
  26012. }
  26013. }
  26014. catch (e) {
  26015. this.canUseWebAudio = false;
  26016. BABYLON.Tools.Error("Web Audio: " + e.message);
  26017. }
  26018. // create a global volume gain node
  26019. if (this.canUseWebAudio) {
  26020. this.masterGain = this.audioContext.createGain();
  26021. this.masterGain.gain.value = 1;
  26022. this.masterGain.connect(this.audioContext.destination);
  26023. }
  26024. }
  26025. AudioEngine.prototype.dispose = function () {
  26026. if (this.canUseWebAudio) {
  26027. if (this._connectedAnalyser) {
  26028. this._connectedAnalyser.stopDebugCanvas();
  26029. this._connectedAnalyser.dispose();
  26030. this.masterGain.disconnect();
  26031. this.masterGain.connect(this.audioContext.destination);
  26032. this._connectedAnalyser = null;
  26033. }
  26034. this.masterGain.gain.value = 1;
  26035. }
  26036. this.WarnedWebAudioUnsupported = false;
  26037. };
  26038. AudioEngine.prototype.getGlobalVolume = function () {
  26039. if (this.canUseWebAudio) {
  26040. return this.masterGain.gain.value;
  26041. }
  26042. else {
  26043. return -1;
  26044. }
  26045. };
  26046. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  26047. if (this.canUseWebAudio) {
  26048. this.masterGain.gain.value = newVolume;
  26049. }
  26050. };
  26051. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  26052. if (this._connectedAnalyser) {
  26053. this._connectedAnalyser.stopDebugCanvas();
  26054. }
  26055. this._connectedAnalyser = analyser;
  26056. if (this.canUseWebAudio) {
  26057. this.masterGain.disconnect();
  26058. this._connectedAnalyser.connectAudioNodes(this.masterGain, this.audioContext.destination);
  26059. }
  26060. };
  26061. return AudioEngine;
  26062. })();
  26063. BABYLON.AudioEngine = AudioEngine;
  26064. })(BABYLON || (BABYLON = {}));
  26065. //# sourceMappingURL=babylon.audioengine.js.mapvar BABYLON;
  26066. (function (BABYLON) {
  26067. var Sound = (function () {
  26068. /**
  26069. * Create a sound and attach it to a scene
  26070. * @param name Name of your sound
  26071. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  26072. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  26073. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel
  26074. */
  26075. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  26076. var _this = this;
  26077. this.autoplay = false;
  26078. this.loop = false;
  26079. this.useCustomAttenuation = false;
  26080. this.spatialSound = false;
  26081. this.refDistance = 1;
  26082. this.rolloffFactor = 1;
  26083. this.maxDistance = 100;
  26084. this.distanceModel = "linear";
  26085. this.panningModel = "HRTF";
  26086. this._playbackRate = 1;
  26087. this._startTime = 0;
  26088. this._startOffset = 0;
  26089. this._position = BABYLON.Vector3.Zero();
  26090. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  26091. this._volume = 1;
  26092. this._isLoaded = false;
  26093. this._isReadyToPlay = false;
  26094. this._isPlaying = false;
  26095. this._isDirectional = false;
  26096. // Used if you'd like to create a directional sound.
  26097. // If not set, the sound will be omnidirectional
  26098. this._coneInnerAngle = 360;
  26099. this._coneOuterAngle = 360;
  26100. this._coneOuterGain = 0;
  26101. this.name = name;
  26102. this._scene = scene;
  26103. this._readyToPlayCallback = readyToPlayCallback;
  26104. // Default custom attenuation function is a linear attenuation
  26105. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  26106. if (currentDistance < maxDistance) {
  26107. return currentVolume * (1 - currentDistance / maxDistance);
  26108. }
  26109. else {
  26110. return 0;
  26111. }
  26112. };
  26113. if (options) {
  26114. this.autoplay = options.autoplay || false;
  26115. this.loop = options.loop || false;
  26116. // if volume === 0, we need another way to check this option
  26117. if (options.volume !== undefined) {
  26118. this._volume = options.volume;
  26119. }
  26120. this.spatialSound = options.spatialSound || false;
  26121. this.maxDistance = options.maxDistance || 100;
  26122. this.useCustomAttenuation = options.useCustomAttenuation || false;
  26123. this.rolloffFactor = options.rolloffFactor || 1;
  26124. this.refDistance = options.refDistance || 1;
  26125. this.distanceModel = options.distanceModel || "linear";
  26126. this.panningModel = options.panningModel || "HRTF";
  26127. this._playbackRate = options.playbackRate || 1;
  26128. }
  26129. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  26130. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  26131. this._soundGain.gain.value = this._volume;
  26132. this._inputAudioNode = this._soundGain;
  26133. this._ouputAudioNode = this._soundGain;
  26134. if (this.spatialSound) {
  26135. this._createSpatialParameters();
  26136. }
  26137. this._scene.mainSoundTrack.AddSound(this);
  26138. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  26139. if (urlOrArrayBuffer) {
  26140. // If it's an URL
  26141. if (typeof (urlOrArrayBuffer) === "string") {
  26142. BABYLON.Tools.LoadFile(urlOrArrayBuffer, function (data) {
  26143. _this._soundLoaded(data);
  26144. }, null, null, true);
  26145. }
  26146. else {
  26147. if (urlOrArrayBuffer instanceof ArrayBuffer) {
  26148. this._soundLoaded(urlOrArrayBuffer);
  26149. }
  26150. else {
  26151. BABYLON.Tools.Error("Parameter must be a URL to the sound or an ArrayBuffer of the sound.");
  26152. }
  26153. }
  26154. }
  26155. }
  26156. else {
  26157. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  26158. this._scene.mainSoundTrack.AddSound(this);
  26159. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  26160. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  26161. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  26162. }
  26163. }
  26164. }
  26165. Sound.prototype.dispose = function () {
  26166. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  26167. if (this._isPlaying) {
  26168. this.stop();
  26169. }
  26170. this._isReadyToPlay = false;
  26171. if (this.soundTrackId === -1) {
  26172. this._scene.mainSoundTrack.RemoveSound(this);
  26173. }
  26174. else {
  26175. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  26176. }
  26177. if (this._soundGain) {
  26178. this._soundGain.disconnect();
  26179. this._soundGain = null;
  26180. }
  26181. if (this._soundPanner) {
  26182. this._soundPanner.disconnect();
  26183. this._soundPanner = null;
  26184. }
  26185. if (this._soundSource) {
  26186. this._soundSource.disconnect();
  26187. this._soundSource = null;
  26188. }
  26189. this._audioBuffer = null;
  26190. if (this._connectedMesh) {
  26191. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  26192. this._connectedMesh = null;
  26193. }
  26194. }
  26195. };
  26196. Sound.prototype._soundLoaded = function (audioData) {
  26197. var _this = this;
  26198. this._isLoaded = true;
  26199. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  26200. _this._audioBuffer = buffer;
  26201. _this._isReadyToPlay = true;
  26202. if (_this.autoplay) {
  26203. _this.play();
  26204. }
  26205. if (_this._readyToPlayCallback) {
  26206. _this._readyToPlayCallback();
  26207. }
  26208. }, function (error) {
  26209. BABYLON.Tools.Error("Error while decoding audio data: " + error.err);
  26210. });
  26211. };
  26212. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  26213. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  26214. this._audioBuffer = audioBuffer;
  26215. this._isReadyToPlay = true;
  26216. }
  26217. };
  26218. Sound.prototype.updateOptions = function (options) {
  26219. if (options) {
  26220. this.loop = options.loop || this.loop;
  26221. this.maxDistance = options.maxDistance || this.maxDistance;
  26222. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  26223. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  26224. this.refDistance = options.refDistance || this.refDistance;
  26225. this.distanceModel = options.distanceModel || this.distanceModel;
  26226. this.panningModel = options.panningModel || this.panningModel;
  26227. this._playbackRate = options.playbackRate || this._playbackRate;
  26228. }
  26229. };
  26230. Sound.prototype._createSpatialParameters = function () {
  26231. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  26232. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  26233. if (this.useCustomAttenuation) {
  26234. // Tricks to disable in a way embedded Web Audio attenuation
  26235. this._soundPanner.distanceModel = "linear";
  26236. this._soundPanner.maxDistance = Number.MAX_VALUE;
  26237. this._soundPanner.refDistance = 1;
  26238. this._soundPanner.rolloffFactor = 1;
  26239. this._soundPanner.panningModel = "HRTF";
  26240. }
  26241. else {
  26242. this._soundPanner.distanceModel = this.distanceModel;
  26243. this._soundPanner.maxDistance = this.maxDistance;
  26244. this._soundPanner.refDistance = this.refDistance;
  26245. this._soundPanner.rolloffFactor = this.rolloffFactor;
  26246. this._soundPanner.panningModel = this.panningModel;
  26247. }
  26248. this._soundPanner.connect(this._ouputAudioNode);
  26249. this._inputAudioNode = this._soundPanner;
  26250. }
  26251. };
  26252. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  26253. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  26254. this._ouputAudioNode.disconnect();
  26255. this._ouputAudioNode.connect(soundTrackAudioNode);
  26256. }
  26257. };
  26258. /**
  26259. * Transform this sound into a directional source
  26260. * @param coneInnerAngle Size of the inner cone in degree
  26261. * @param coneOuterAngle Size of the outer cone in degree
  26262. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  26263. */
  26264. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  26265. if (coneOuterAngle < coneInnerAngle) {
  26266. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  26267. return;
  26268. }
  26269. this._coneInnerAngle = coneInnerAngle;
  26270. this._coneOuterAngle = coneOuterAngle;
  26271. this._coneOuterGain = coneOuterGain;
  26272. this._isDirectional = true;
  26273. if (this._isPlaying && this.loop) {
  26274. this.stop();
  26275. this.play();
  26276. }
  26277. };
  26278. Sound.prototype.setPosition = function (newPosition) {
  26279. this._position = newPosition;
  26280. if (this._isPlaying && this.spatialSound) {
  26281. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  26282. }
  26283. };
  26284. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  26285. this._localDirection = newLocalDirection;
  26286. if (this._connectedMesh && this._isPlaying) {
  26287. this._updateDirection();
  26288. }
  26289. };
  26290. Sound.prototype._updateDirection = function () {
  26291. var mat = this._connectedMesh.getWorldMatrix();
  26292. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  26293. direction.normalize();
  26294. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  26295. };
  26296. Sound.prototype.updateDistanceFromListener = function () {
  26297. if (this._connectedMesh && this.useCustomAttenuation) {
  26298. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  26299. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  26300. }
  26301. };
  26302. Sound.prototype.setAttenuationFunction = function (callback) {
  26303. this._customAttenuationFunction = callback;
  26304. };
  26305. /**
  26306. * Play the sound
  26307. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  26308. */
  26309. Sound.prototype.play = function (time) {
  26310. if (this._isReadyToPlay) {
  26311. try {
  26312. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : 0;
  26313. if (!this._soundSource) {
  26314. if (this.spatialSound) {
  26315. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  26316. if (this._isDirectional) {
  26317. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  26318. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  26319. this._soundPanner.coneOuterGain = this._coneOuterGain;
  26320. if (this._connectedMesh) {
  26321. this._updateDirection();
  26322. }
  26323. else {
  26324. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  26325. }
  26326. }
  26327. }
  26328. }
  26329. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  26330. this._soundSource.buffer = this._audioBuffer;
  26331. this._soundSource.connect(this._inputAudioNode);
  26332. this._soundSource.loop = this.loop;
  26333. this._soundSource.playbackRate.value = this._playbackRate;
  26334. this._startTime = startTime;
  26335. if (this.onended) {
  26336. this._soundSource.onended = this.onended;
  26337. }
  26338. this._soundSource.start(startTime, this._startOffset % this._soundSource.buffer.duration);
  26339. this._isPlaying = true;
  26340. }
  26341. catch (ex) {
  26342. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  26343. }
  26344. }
  26345. };
  26346. /**
  26347. * Stop the sound
  26348. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  26349. */
  26350. Sound.prototype.stop = function (time) {
  26351. if (this._isPlaying) {
  26352. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : 0;
  26353. this._soundSource.stop(stopTime);
  26354. this._isPlaying = false;
  26355. }
  26356. };
  26357. Sound.prototype.pause = function () {
  26358. if (this._isPlaying) {
  26359. this._soundSource.stop(0);
  26360. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  26361. }
  26362. };
  26363. Sound.prototype.setVolume = function (newVolume, time) {
  26364. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  26365. if (time) {
  26366. this._soundGain.gain.linearRampToValueAtTime(this._volume, BABYLON.Engine.audioEngine.audioContext.currentTime);
  26367. this._soundGain.gain.linearRampToValueAtTime(newVolume, time);
  26368. }
  26369. else {
  26370. this._soundGain.gain.value = newVolume;
  26371. }
  26372. }
  26373. this._volume = newVolume;
  26374. };
  26375. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  26376. this._playbackRate = newPlaybackRate;
  26377. if (this._isPlaying) {
  26378. this._soundSource.playbackRate.value = this._playbackRate;
  26379. }
  26380. };
  26381. Sound.prototype.getVolume = function () {
  26382. return this._volume;
  26383. };
  26384. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  26385. var _this = this;
  26386. this._connectedMesh = meshToConnectTo;
  26387. if (!this.spatialSound) {
  26388. this._createSpatialParameters();
  26389. this.spatialSound = true;
  26390. if (this._isPlaying && this.loop) {
  26391. this.stop();
  26392. this.play();
  26393. }
  26394. }
  26395. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  26396. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  26397. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  26398. };
  26399. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  26400. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  26401. if (this._isDirectional && this._isPlaying) {
  26402. this._updateDirection();
  26403. }
  26404. };
  26405. return Sound;
  26406. })();
  26407. BABYLON.Sound = Sound;
  26408. })(BABYLON || (BABYLON = {}));
  26409. //# sourceMappingURL=babylon.sound.js.mapvar BABYLON;
  26410. (function (BABYLON) {
  26411. var SoundTrack = (function () {
  26412. function SoundTrack(scene, options) {
  26413. this.id = -1;
  26414. this._isMainTrack = false;
  26415. this._scene = scene;
  26416. this._audioEngine = BABYLON.Engine.audioEngine;
  26417. this.soundCollection = new Array();
  26418. if (this._audioEngine.canUseWebAudio) {
  26419. this._trackGain = this._audioEngine.audioContext.createGain();
  26420. this._trackGain.connect(this._audioEngine.masterGain);
  26421. if (options) {
  26422. if (options.volume) {
  26423. this._trackGain.gain.value = options.volume;
  26424. }
  26425. if (options.mainTrack) {
  26426. this._isMainTrack = options.mainTrack;
  26427. }
  26428. }
  26429. }
  26430. if (!this._isMainTrack) {
  26431. this._scene.soundTracks.push(this);
  26432. this.id = this._scene.soundTracks.length - 1;
  26433. }
  26434. }
  26435. SoundTrack.prototype.dispose = function () {
  26436. if (this._audioEngine.canUseWebAudio) {
  26437. if (this._connectedAnalyser) {
  26438. this._connectedAnalyser.stopDebugCanvas();
  26439. }
  26440. while (this.soundCollection.length) {
  26441. this.soundCollection[0].dispose();
  26442. }
  26443. this._trackGain.disconnect();
  26444. this._trackGain = null;
  26445. }
  26446. };
  26447. SoundTrack.prototype.AddSound = function (sound) {
  26448. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  26449. sound.connectToSoundTrackAudioNode(this._trackGain);
  26450. }
  26451. if (sound.soundTrackId) {
  26452. if (sound.soundTrackId === -1) {
  26453. this._scene.mainSoundTrack.RemoveSound(sound);
  26454. }
  26455. else {
  26456. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  26457. }
  26458. }
  26459. this.soundCollection.push(sound);
  26460. sound.soundTrackId = this.id;
  26461. };
  26462. SoundTrack.prototype.RemoveSound = function (sound) {
  26463. var index = this.soundCollection.indexOf(sound);
  26464. if (index !== -1) {
  26465. this.soundCollection.splice(index, 1);
  26466. }
  26467. };
  26468. SoundTrack.prototype.setVolume = function (newVolume) {
  26469. if (this._audioEngine.canUseWebAudio) {
  26470. this._trackGain.gain.value = newVolume;
  26471. }
  26472. };
  26473. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  26474. if (this._connectedAnalyser) {
  26475. this._connectedAnalyser.stopDebugCanvas();
  26476. }
  26477. this._connectedAnalyser = analyser;
  26478. if (this._audioEngine.canUseWebAudio) {
  26479. this._trackGain.disconnect();
  26480. this._connectedAnalyser.connectAudioNodes(this._trackGain, this._audioEngine.masterGain);
  26481. }
  26482. };
  26483. return SoundTrack;
  26484. })();
  26485. BABYLON.SoundTrack = SoundTrack;
  26486. })(BABYLON || (BABYLON = {}));
  26487. //# sourceMappingURL=babylon.soundtrack.js.mapvar BABYLON;
  26488. (function (BABYLON) {
  26489. var DebugLayer = (function () {
  26490. function DebugLayer(scene) {
  26491. var _this = this;
  26492. this._transformationMatrix = BABYLON.Matrix.Identity();
  26493. this._enabled = false;
  26494. this._labelsEnabled = false;
  26495. this._displayStatistics = true;
  26496. this._displayTree = false;
  26497. this._displayLogs = false;
  26498. this._identityMatrix = BABYLON.Matrix.Identity();
  26499. this.axisRatio = 0.02;
  26500. this.accentColor = "orange";
  26501. this._scene = scene;
  26502. this._syncPositions = function () {
  26503. var engine = _this._scene.getEngine();
  26504. var canvasRect = engine.getRenderingCanvasClientRect();
  26505. if (_this._showUI) {
  26506. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  26507. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  26508. _this._statsDiv.style.width = "400px";
  26509. _this._statsDiv.style.height = "auto";
  26510. _this._statsSubsetDiv.style.maxHeight = "240px";
  26511. _this._optionsDiv.style.left = "0px";
  26512. _this._optionsDiv.style.top = "10px";
  26513. _this._optionsDiv.style.width = "200px";
  26514. _this._optionsDiv.style.height = "auto";
  26515. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  26516. _this._logDiv.style.left = "0px";
  26517. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  26518. _this._logDiv.style.width = "600px";
  26519. _this._logDiv.style.height = "160px";
  26520. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  26521. _this._treeDiv.style.top = "10px";
  26522. _this._treeDiv.style.width = "300px";
  26523. _this._treeDiv.style.height = "auto";
  26524. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  26525. }
  26526. _this._globalDiv.style.left = canvasRect.left + "px";
  26527. _this._globalDiv.style.top = canvasRect.top + "px";
  26528. _this._drawingCanvas.style.left = "0px";
  26529. _this._drawingCanvas.style.top = "0px";
  26530. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  26531. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  26532. var devicePixelRatio = window.devicePixelRatio || 1;
  26533. var context = _this._drawingContext;
  26534. var backingStoreRatio = context.webkitBackingStorePixelRatio || context.mozBackingStorePixelRatio || context.msBackingStorePixelRatio || context.oBackingStorePixelRatio || context.backingStorePixelRatio || 1;
  26535. _this._ratio = devicePixelRatio / backingStoreRatio;
  26536. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  26537. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  26538. };
  26539. this._onCanvasClick = function (evt) {
  26540. _this._clickPosition = {
  26541. x: evt.clientX * _this._ratio,
  26542. y: evt.clientY * _this._ratio
  26543. };
  26544. };
  26545. this._syncData = function () {
  26546. if (_this._showUI) {
  26547. if (_this._displayStatistics) {
  26548. _this._displayStats();
  26549. _this._statsDiv.style.display = "";
  26550. }
  26551. else {
  26552. _this._statsDiv.style.display = "none";
  26553. }
  26554. if (_this._displayLogs) {
  26555. _this._logDiv.style.display = "";
  26556. }
  26557. else {
  26558. _this._logDiv.style.display = "none";
  26559. }
  26560. if (_this._displayTree) {
  26561. _this._treeDiv.style.display = "";
  26562. if (_this._needToRefreshMeshesTree) {
  26563. _this._needToRefreshMeshesTree = false;
  26564. _this._refreshMeshesTreeContent();
  26565. }
  26566. }
  26567. else {
  26568. _this._treeDiv.style.display = "none";
  26569. }
  26570. }
  26571. if (_this._labelsEnabled || !_this._showUI) {
  26572. _this._camera.getViewMatrix().multiplyToRef(_this._camera.getProjectionMatrix(), _this._transformationMatrix);
  26573. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  26574. var engine = _this._scene.getEngine();
  26575. var viewport = _this._camera.viewport;
  26576. var globalViewport = viewport.toGlobal(engine);
  26577. // Meshes
  26578. var meshes = _this._camera.getActiveMeshes();
  26579. for (var index = 0; index < meshes.length; index++) {
  26580. var mesh = meshes.data[index];
  26581. var position = mesh.getBoundingInfo().boundingSphere.center;
  26582. var projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  26583. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  26584. _this._renderAxis(projectedPosition, mesh, globalViewport);
  26585. }
  26586. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  26587. _this._renderLabel(mesh.name, projectedPosition, 12, function () {
  26588. mesh.renderOverlay = !mesh.renderOverlay;
  26589. }, function () {
  26590. return mesh.renderOverlay ? 'red' : 'black';
  26591. });
  26592. }
  26593. }
  26594. // Cameras
  26595. var cameras = _this._scene.cameras;
  26596. for (index = 0; index < cameras.length; index++) {
  26597. var camera = cameras[index];
  26598. if (camera === _this._camera) {
  26599. continue;
  26600. }
  26601. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  26602. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  26603. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  26604. _this._camera.detachControl(engine.getRenderingCanvas());
  26605. _this._camera = camera;
  26606. _this._camera.attachControl(engine.getRenderingCanvas());
  26607. }, function () {
  26608. return "purple";
  26609. });
  26610. }
  26611. }
  26612. // Lights
  26613. var lights = _this._scene.lights;
  26614. for (index = 0; index < lights.length; index++) {
  26615. var light = lights[index];
  26616. if (light.position) {
  26617. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._transformationMatrix, globalViewport);
  26618. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  26619. _this._renderLabel(light.name, projectedPosition, -20, function () {
  26620. light.setEnabled(!light.isEnabled());
  26621. }, function () {
  26622. return light.isEnabled() ? "orange" : "gray";
  26623. });
  26624. }
  26625. }
  26626. }
  26627. }
  26628. _this._clickPosition = undefined;
  26629. };
  26630. }
  26631. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  26632. while (this._treeSubsetDiv.hasChildNodes()) {
  26633. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  26634. }
  26635. // Add meshes
  26636. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  26637. sortedArray.sort(function (a, b) {
  26638. if (a.name === b.name) {
  26639. return 0;
  26640. }
  26641. return (a.name > b.name) ? 1 : -1;
  26642. });
  26643. for (var index = 0; index < sortedArray.length; index++) {
  26644. var mesh = sortedArray[index];
  26645. if (!mesh.isEnabled()) {
  26646. continue;
  26647. }
  26648. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  26649. m.isVisible = element.checked;
  26650. }, mesh);
  26651. }
  26652. };
  26653. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  26654. this._drawingContext.beginPath();
  26655. this._drawingContext.moveTo(zero.x, zero.y);
  26656. this._drawingContext.lineTo(unit.x, unit.y);
  26657. this._drawingContext.strokeStyle = color;
  26658. this._drawingContext.lineWidth = 4;
  26659. this._drawingContext.stroke();
  26660. this._drawingContext.font = "normal 14px Segoe UI";
  26661. this._drawingContext.fillStyle = color;
  26662. this._drawingContext.fillText(label, unitText.x, unitText.y);
  26663. };
  26664. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  26665. var position = mesh.getBoundingInfo().boundingSphere.center;
  26666. var worldMatrix = mesh.getWorldMatrix();
  26667. var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._transformationMatrix);
  26668. var unit = (unprojectedVector.subtract(position)).length();
  26669. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  26670. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  26671. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  26672. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  26673. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  26674. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  26675. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._transformationMatrix, globalViewport);
  26676. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._transformationMatrix, globalViewport);
  26677. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  26678. };
  26679. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  26680. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  26681. this._drawingContext.font = "normal 12px Segoe UI";
  26682. var textMetrics = this._drawingContext.measureText(text);
  26683. var centerX = projectedPosition.x - textMetrics.width / 2;
  26684. var centerY = projectedPosition.y;
  26685. var clientRect = this._drawingCanvas.getBoundingClientRect();
  26686. if (this._isClickInsideRect(clientRect.left * this._ratio + centerX - 5, clientRect.top * this._ratio + centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  26687. onClick();
  26688. }
  26689. this._drawingContext.beginPath();
  26690. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  26691. this._drawingContext.fillStyle = getFillStyle();
  26692. this._drawingContext.globalAlpha = 0.5;
  26693. this._drawingContext.fill();
  26694. this._drawingContext.globalAlpha = 1.0;
  26695. this._drawingContext.strokeStyle = '#FFFFFF';
  26696. this._drawingContext.lineWidth = 1;
  26697. this._drawingContext.stroke();
  26698. this._drawingContext.fillStyle = "#FFFFFF";
  26699. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  26700. this._drawingContext.beginPath();
  26701. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  26702. this._drawingContext.fill();
  26703. }
  26704. };
  26705. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  26706. if (!this._clickPosition) {
  26707. return false;
  26708. }
  26709. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  26710. return false;
  26711. }
  26712. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  26713. return false;
  26714. }
  26715. return true;
  26716. };
  26717. DebugLayer.prototype.isVisible = function () {
  26718. return this._enabled;
  26719. };
  26720. DebugLayer.prototype.hide = function () {
  26721. if (!this._enabled) {
  26722. return;
  26723. }
  26724. this._enabled = false;
  26725. var engine = this._scene.getEngine();
  26726. this._scene.unregisterAfterRender(this._syncData);
  26727. document.body.removeChild(this._globalDiv);
  26728. window.removeEventListener("resize", this._syncPositions);
  26729. this._scene.forceShowBoundingBoxes = false;
  26730. this._scene.forceWireframe = false;
  26731. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  26732. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  26733. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  26734. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  26735. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  26736. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  26737. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  26738. this._scene.shadowsEnabled = true;
  26739. this._scene.particlesEnabled = true;
  26740. this._scene.postProcessesEnabled = true;
  26741. this._scene.collisionsEnabled = true;
  26742. this._scene.lightsEnabled = true;
  26743. this._scene.texturesEnabled = true;
  26744. this._scene.lensFlaresEnabled = true;
  26745. this._scene.proceduralTexturesEnabled = true;
  26746. this._scene.renderTargetsEnabled = true;
  26747. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  26748. };
  26749. DebugLayer.prototype.show = function (showUI, camera) {
  26750. if (showUI === void 0) { showUI = true; }
  26751. if (camera === void 0) { camera = null; }
  26752. if (this._enabled) {
  26753. return;
  26754. }
  26755. if (camera) {
  26756. this._camera = camera;
  26757. }
  26758. else {
  26759. this._camera = this._scene.activeCamera;
  26760. }
  26761. this._enabled = true;
  26762. this._showUI = showUI;
  26763. var engine = this._scene.getEngine();
  26764. this._globalDiv = document.createElement("div");
  26765. document.body.appendChild(this._globalDiv);
  26766. this._generateDOMelements();
  26767. window.addEventListener("resize", this._syncPositions);
  26768. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  26769. this._syncPositions();
  26770. this._scene.registerAfterRender(this._syncData);
  26771. };
  26772. DebugLayer.prototype._clearLabels = function () {
  26773. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  26774. for (var index = 0; index < this._scene.meshes.length; index++) {
  26775. var mesh = this._scene.meshes[index];
  26776. mesh.renderOverlay = false;
  26777. }
  26778. };
  26779. DebugLayer.prototype._generateheader = function (root, text) {
  26780. var header = document.createElement("div");
  26781. header.innerHTML = text + "&nbsp;";
  26782. header.style.textAlign = "right";
  26783. header.style.width = "100%";
  26784. header.style.color = "white";
  26785. header.style.backgroundColor = "Black";
  26786. header.style.padding = "5px 5px 4px 0px";
  26787. header.style.marginLeft = "-5px";
  26788. header.style.fontWeight = "bold";
  26789. root.appendChild(header);
  26790. };
  26791. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  26792. var label = document.createElement("label");
  26793. label.innerHTML = title;
  26794. label.style.color = color;
  26795. root.appendChild(label);
  26796. root.appendChild(document.createElement("br"));
  26797. };
  26798. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  26799. if (tag === void 0) { tag = null; }
  26800. var label = document.createElement("label");
  26801. var boundingBoxesCheckbox = document.createElement("input");
  26802. boundingBoxesCheckbox.type = "checkbox";
  26803. boundingBoxesCheckbox.checked = initialState;
  26804. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  26805. task(evt.target, tag);
  26806. });
  26807. label.appendChild(boundingBoxesCheckbox);
  26808. var container = document.createElement("span");
  26809. var leftPart = document.createElement("span");
  26810. var rightPart = document.createElement("span");
  26811. rightPart.style.cssFloat = "right";
  26812. leftPart.innerHTML = leftTitle;
  26813. rightPart.innerHTML = rightTitle;
  26814. rightPart.style.fontSize = "12px";
  26815. rightPart.style.maxWidth = "200px";
  26816. container.appendChild(leftPart);
  26817. container.appendChild(rightPart);
  26818. label.appendChild(container);
  26819. root.appendChild(label);
  26820. root.appendChild(document.createElement("br"));
  26821. };
  26822. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  26823. if (tag === void 0) { tag = null; }
  26824. var label = document.createElement("label");
  26825. var boundingBoxesCheckbox = document.createElement("input");
  26826. boundingBoxesCheckbox.type = "checkbox";
  26827. boundingBoxesCheckbox.checked = initialState;
  26828. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  26829. task(evt.target, tag);
  26830. });
  26831. label.appendChild(boundingBoxesCheckbox);
  26832. label.appendChild(document.createTextNode(title));
  26833. root.appendChild(label);
  26834. root.appendChild(document.createElement("br"));
  26835. };
  26836. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  26837. if (tag === void 0) { tag = null; }
  26838. var label = document.createElement("label");
  26839. var boundingBoxesRadio = document.createElement("input");
  26840. boundingBoxesRadio.type = "radio";
  26841. boundingBoxesRadio.name = name;
  26842. boundingBoxesRadio.checked = initialState;
  26843. boundingBoxesRadio.addEventListener("change", function (evt) {
  26844. task(evt.target, tag);
  26845. });
  26846. label.appendChild(boundingBoxesRadio);
  26847. label.appendChild(document.createTextNode(title));
  26848. root.appendChild(label);
  26849. root.appendChild(document.createElement("br"));
  26850. };
  26851. DebugLayer.prototype._generateDOMelements = function () {
  26852. var _this = this;
  26853. this._globalDiv.id = "DebugLayer";
  26854. this._globalDiv.style.position = "absolute";
  26855. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  26856. this._globalDiv.style.fontSize = "14px";
  26857. this._globalDiv.style.color = "white";
  26858. // Drawing canvas
  26859. this._drawingCanvas = document.createElement("canvas");
  26860. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  26861. this._drawingCanvas.style.position = "absolute";
  26862. this._drawingCanvas.style.pointerEvents = "none";
  26863. this._drawingContext = this._drawingCanvas.getContext("2d");
  26864. this._globalDiv.appendChild(this._drawingCanvas);
  26865. if (this._showUI) {
  26866. var background = "rgba(128, 128, 128, 0.4)";
  26867. var border = "rgb(180, 180, 180) solid 1px";
  26868. // Stats
  26869. this._statsDiv = document.createElement("div");
  26870. this._statsDiv.id = "DebugLayerStats";
  26871. this._statsDiv.style.border = border;
  26872. this._statsDiv.style.position = "absolute";
  26873. this._statsDiv.style.background = background;
  26874. this._statsDiv.style.padding = "0px 0px 0px 5px";
  26875. this._generateheader(this._statsDiv, "STATISTICS");
  26876. this._statsSubsetDiv = document.createElement("div");
  26877. this._statsSubsetDiv.style.paddingTop = "5px";
  26878. this._statsSubsetDiv.style.paddingBottom = "5px";
  26879. this._statsSubsetDiv.style.overflowY = "auto";
  26880. this._statsDiv.appendChild(this._statsSubsetDiv);
  26881. // Tree
  26882. this._treeDiv = document.createElement("div");
  26883. this._treeDiv.id = "DebugLayerTree";
  26884. this._treeDiv.style.border = border;
  26885. this._treeDiv.style.position = "absolute";
  26886. this._treeDiv.style.background = background;
  26887. this._treeDiv.style.padding = "0px 0px 0px 5px";
  26888. this._treeDiv.style.display = "none";
  26889. this._generateheader(this._treeDiv, "MESHES TREE");
  26890. this._treeSubsetDiv = document.createElement("div");
  26891. this._treeSubsetDiv.style.paddingTop = "5px";
  26892. this._treeSubsetDiv.style.paddingRight = "5px";
  26893. this._treeSubsetDiv.style.overflowY = "auto";
  26894. this._treeSubsetDiv.style.maxHeight = "300px";
  26895. this._treeDiv.appendChild(this._treeSubsetDiv);
  26896. this._needToRefreshMeshesTree = true;
  26897. // Logs
  26898. this._logDiv = document.createElement("div");
  26899. this._logDiv.style.border = border;
  26900. this._logDiv.id = "DebugLayerLogs";
  26901. this._logDiv.style.position = "absolute";
  26902. this._logDiv.style.background = background;
  26903. this._logDiv.style.padding = "0px 0px 0px 5px";
  26904. this._logDiv.style.display = "none";
  26905. this._generateheader(this._logDiv, "LOGS");
  26906. this._logSubsetDiv = document.createElement("div");
  26907. this._logSubsetDiv.style.height = "127px";
  26908. this._logSubsetDiv.style.paddingTop = "5px";
  26909. this._logSubsetDiv.style.overflowY = "auto";
  26910. this._logSubsetDiv.style.fontSize = "12px";
  26911. this._logSubsetDiv.style.fontFamily = "consolas";
  26912. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  26913. this._logDiv.appendChild(this._logSubsetDiv);
  26914. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  26915. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  26916. };
  26917. // Options
  26918. this._optionsDiv = document.createElement("div");
  26919. this._optionsDiv.id = "DebugLayerOptions";
  26920. this._optionsDiv.style.border = border;
  26921. this._optionsDiv.style.position = "absolute";
  26922. this._optionsDiv.style.background = background;
  26923. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  26924. this._optionsDiv.style.overflowY = "auto";
  26925. this._generateheader(this._optionsDiv, "OPTIONS");
  26926. this._optionsSubsetDiv = document.createElement("div");
  26927. this._optionsSubsetDiv.style.paddingTop = "5px";
  26928. this._optionsSubsetDiv.style.paddingBottom = "5px";
  26929. this._optionsSubsetDiv.style.overflowY = "auto";
  26930. this._optionsSubsetDiv.style.maxHeight = "200px";
  26931. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  26932. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  26933. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) {
  26934. _this._displayStatistics = element.checked;
  26935. });
  26936. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) {
  26937. _this._displayLogs = element.checked;
  26938. });
  26939. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  26940. _this._displayTree = element.checked;
  26941. _this._needToRefreshMeshesTree = true;
  26942. });
  26943. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  26944. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  26945. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) {
  26946. _this._scene.forceShowBoundingBoxes = element.checked;
  26947. });
  26948. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  26949. _this._labelsEnabled = element.checked;
  26950. if (!_this._labelsEnabled) {
  26951. _this._clearLabels();
  26952. }
  26953. });
  26954. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  26955. if (element.checked) {
  26956. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  26957. }
  26958. else {
  26959. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  26960. }
  26961. });
  26962. ;
  26963. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  26964. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  26965. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  26966. if (element.checked) {
  26967. _this._scene.forceWireframe = false;
  26968. _this._scene.forcePointsCloud = false;
  26969. }
  26970. });
  26971. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  26972. if (element.checked) {
  26973. _this._scene.forceWireframe = true;
  26974. _this._scene.forcePointsCloud = false;
  26975. }
  26976. });
  26977. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  26978. if (element.checked) {
  26979. _this._scene.forceWireframe = false;
  26980. _this._scene.forcePointsCloud = true;
  26981. }
  26982. });
  26983. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  26984. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  26985. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) {
  26986. BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked;
  26987. });
  26988. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) {
  26989. BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked;
  26990. });
  26991. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) {
  26992. BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked;
  26993. });
  26994. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) {
  26995. BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked;
  26996. });
  26997. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) {
  26998. BABYLON.StandardMaterial.BumpTextureEnabled = element.checked;
  26999. });
  27000. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) {
  27001. BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked;
  27002. });
  27003. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) {
  27004. BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked;
  27005. });
  27006. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) {
  27007. BABYLON.StandardMaterial.FresnelEnabled = element.checked;
  27008. });
  27009. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27010. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  27011. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) {
  27012. _this._scene.animationsEnabled = element.checked;
  27013. });
  27014. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) {
  27015. _this._scene.collisionsEnabled = element.checked;
  27016. });
  27017. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) {
  27018. _this._scene.fogEnabled = element.checked;
  27019. });
  27020. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) {
  27021. _this._scene.lensFlaresEnabled = element.checked;
  27022. });
  27023. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) {
  27024. _this._scene.lightsEnabled = element.checked;
  27025. });
  27026. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) {
  27027. _this._scene.particlesEnabled = element.checked;
  27028. });
  27029. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) {
  27030. _this._scene.postProcessesEnabled = element.checked;
  27031. });
  27032. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) {
  27033. _this._scene.proceduralTexturesEnabled = element.checked;
  27034. });
  27035. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) {
  27036. _this._scene.renderTargetsEnabled = element.checked;
  27037. });
  27038. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) {
  27039. _this._scene.shadowsEnabled = element.checked;
  27040. });
  27041. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) {
  27042. _this._scene.skeletonsEnabled = element.checked;
  27043. });
  27044. this._generateCheckBox(this._optionsSubsetDiv, "Sprites", this._scene.spritesEnabled, function (element) {
  27045. _this._scene.spritesEnabled = element.checked;
  27046. });
  27047. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) {
  27048. _this._scene.texturesEnabled = element.checked;
  27049. });
  27050. this._globalDiv.appendChild(this._statsDiv);
  27051. this._globalDiv.appendChild(this._logDiv);
  27052. this._globalDiv.appendChild(this._optionsDiv);
  27053. this._globalDiv.appendChild(this._treeDiv);
  27054. }
  27055. };
  27056. DebugLayer.prototype._displayStats = function () {
  27057. var scene = this._scene;
  27058. var engine = scene.getEngine();
  27059. var glInfo = engine.getGlInfo();
  27060. 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>";
  27061. if (this.customStatsFunction) {
  27062. this._statsSubsetDiv.innerHTML += this._statsSubsetDiv.innerHTML;
  27063. }
  27064. };
  27065. return DebugLayer;
  27066. })();
  27067. BABYLON.DebugLayer = DebugLayer;
  27068. })(BABYLON || (BABYLON = {}));
  27069. //# sourceMappingURL=babylon.debugLayer.js.map
  27070. var BABYLON;
  27071. (function (BABYLON) {
  27072. var RawTexture = (function (_super) {
  27073. __extends(RawTexture, _super);
  27074. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  27075. if (generateMipMaps === void 0) { generateMipMaps = true; }
  27076. if (invertY === void 0) { invertY = false; }
  27077. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  27078. _super.call(this, null, scene, !generateMipMaps, invertY);
  27079. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  27080. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  27081. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  27082. }
  27083. // Statics
  27084. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  27085. if (generateMipMaps === void 0) { generateMipMaps = true; }
  27086. if (invertY === void 0) { invertY = false; }
  27087. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  27088. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  27089. };
  27090. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  27091. if (generateMipMaps === void 0) { generateMipMaps = true; }
  27092. if (invertY === void 0) { invertY = false; }
  27093. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  27094. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  27095. };
  27096. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  27097. if (generateMipMaps === void 0) { generateMipMaps = true; }
  27098. if (invertY === void 0) { invertY = false; }
  27099. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  27100. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  27101. };
  27102. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  27103. if (generateMipMaps === void 0) { generateMipMaps = true; }
  27104. if (invertY === void 0) { invertY = false; }
  27105. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  27106. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  27107. };
  27108. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  27109. if (generateMipMaps === void 0) { generateMipMaps = true; }
  27110. if (invertY === void 0) { invertY = false; }
  27111. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  27112. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  27113. };
  27114. return RawTexture;
  27115. })(BABYLON.Texture);
  27116. BABYLON.RawTexture = RawTexture;
  27117. })(BABYLON || (BABYLON = {}));
  27118. //# sourceMappingURL=babylon.rawTexture.js.map
  27119. var BABYLON;
  27120. (function (BABYLON) {
  27121. var IndexedVector2 = (function (_super) {
  27122. __extends(IndexedVector2, _super);
  27123. function IndexedVector2(original, index) {
  27124. _super.call(this, original.x, original.y);
  27125. this.index = index;
  27126. }
  27127. return IndexedVector2;
  27128. })(BABYLON.Vector2);
  27129. var PolygonPoints = (function () {
  27130. function PolygonPoints() {
  27131. this.elements = new Array();
  27132. }
  27133. PolygonPoints.prototype.add = function (originalPoints) {
  27134. var _this = this;
  27135. var result = new Array();
  27136. originalPoints.forEach(function (point) {
  27137. if (result.length === 0 || !(BABYLON.Tools.WithinEpsilon(point.x, result[0].x, 0.00001) && BABYLON.Tools.WithinEpsilon(point.y, result[0].y, 0.00001))) {
  27138. var newPoint = new IndexedVector2(point, _this.elements.length);
  27139. result.push(newPoint);
  27140. _this.elements.push(newPoint);
  27141. }
  27142. });
  27143. return result;
  27144. };
  27145. PolygonPoints.prototype.computeBounds = function () {
  27146. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  27147. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  27148. this.elements.forEach(function (point) {
  27149. // x
  27150. if (point.x < lmin.x) {
  27151. lmin.x = point.x;
  27152. }
  27153. else if (point.x > lmax.x) {
  27154. lmax.x = point.x;
  27155. }
  27156. // y
  27157. if (point.y < lmin.y) {
  27158. lmin.y = point.y;
  27159. }
  27160. else if (point.y > lmax.y) {
  27161. lmax.y = point.y;
  27162. }
  27163. });
  27164. return {
  27165. min: lmin,
  27166. max: lmax,
  27167. width: lmax.x - lmin.x,
  27168. height: lmax.y - lmin.y
  27169. };
  27170. };
  27171. return PolygonPoints;
  27172. })();
  27173. var Polygon = (function () {
  27174. function Polygon() {
  27175. }
  27176. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  27177. return [
  27178. new BABYLON.Vector2(xmin, ymin),
  27179. new BABYLON.Vector2(xmax, ymin),
  27180. new BABYLON.Vector2(xmax, ymax),
  27181. new BABYLON.Vector2(xmin, ymax)
  27182. ];
  27183. };
  27184. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  27185. if (cx === void 0) { cx = 0; }
  27186. if (cy === void 0) { cy = 0; }
  27187. if (numberOfSides === void 0) { numberOfSides = 32; }
  27188. var result = new Array();
  27189. var angle = 0;
  27190. var increment = (Math.PI * 2) / numberOfSides;
  27191. for (var i = 0; i < numberOfSides; i++) {
  27192. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  27193. angle -= increment;
  27194. }
  27195. return result;
  27196. };
  27197. Polygon.Parse = function (input) {
  27198. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  27199. var i, result = [];
  27200. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  27201. result.push(new poly2tri.Point(floats[i], floats[i + 1]));
  27202. }
  27203. return result;
  27204. };
  27205. Polygon.StartingAt = function (x, y) {
  27206. return BABYLON.Path2.StartingAt(x, y);
  27207. };
  27208. return Polygon;
  27209. })();
  27210. BABYLON.Polygon = Polygon;
  27211. var PolygonMeshBuilder = (function () {
  27212. function PolygonMeshBuilder(name, contours, scene) {
  27213. this._points = new PolygonPoints();
  27214. if (!("poly2tri" in window)) {
  27215. throw "PolygonMeshBuilder cannot be used because poly2tri is not referenced";
  27216. }
  27217. this._name = name;
  27218. this._scene = scene;
  27219. var points;
  27220. if (contours instanceof BABYLON.Path2) {
  27221. points = contours.getPoints();
  27222. }
  27223. else {
  27224. points = contours;
  27225. }
  27226. this._swctx = new poly2tri.SweepContext(this._points.add(points));
  27227. }
  27228. PolygonMeshBuilder.prototype.addHole = function (hole) {
  27229. this._swctx.addHole(this._points.add(hole));
  27230. return this;
  27231. };
  27232. PolygonMeshBuilder.prototype.build = function (updatable) {
  27233. if (updatable === void 0) { updatable = false; }
  27234. var result = new BABYLON.Mesh(this._name, this._scene);
  27235. var normals = [];
  27236. var positions = [];
  27237. var uvs = [];
  27238. var bounds = this._points.computeBounds();
  27239. this._points.elements.forEach(function (p) {
  27240. normals.push(0, 1.0, 0);
  27241. positions.push(p.x, 0, p.y);
  27242. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  27243. });
  27244. var indices = [];
  27245. this._swctx.triangulate();
  27246. this._swctx.getTriangles().forEach(function (triangle) {
  27247. triangle.getPoints().forEach(function (point) {
  27248. indices.push(point.index);
  27249. });
  27250. });
  27251. result.setVerticesData(positions, BABYLON.VertexBuffer.PositionKind, updatable);
  27252. result.setVerticesData(normals, BABYLON.VertexBuffer.NormalKind, updatable);
  27253. result.setVerticesData(uvs, BABYLON.VertexBuffer.UVKind, updatable);
  27254. result.setIndices(indices);
  27255. return result;
  27256. };
  27257. return PolygonMeshBuilder;
  27258. })();
  27259. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  27260. })(BABYLON || (BABYLON = {}));
  27261. //# sourceMappingURL=babylon.polygonMesh.js.mapvar BABYLON;
  27262. (function (BABYLON) {
  27263. var SimplificationSettings = (function () {
  27264. function SimplificationSettings(quality, distance) {
  27265. this.quality = quality;
  27266. this.distance = distance;
  27267. }
  27268. return SimplificationSettings;
  27269. })();
  27270. BABYLON.SimplificationSettings = SimplificationSettings;
  27271. /**
  27272. * The implemented types of simplification.
  27273. * At the moment only Quadratic Error Decimation is implemented.
  27274. */
  27275. (function (SimplificationType) {
  27276. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  27277. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  27278. var SimplificationType = BABYLON.SimplificationType;
  27279. var DecimationTriangle = (function () {
  27280. function DecimationTriangle(vertices) {
  27281. this.vertices = vertices;
  27282. this.error = new Array(4);
  27283. this.deleted = false;
  27284. this.isDirty = false;
  27285. this.borderFactor = 0;
  27286. }
  27287. return DecimationTriangle;
  27288. })();
  27289. BABYLON.DecimationTriangle = DecimationTriangle;
  27290. var DecimationVertex = (function () {
  27291. function DecimationVertex(position, normal, uv, id) {
  27292. this.position = position;
  27293. this.normal = normal;
  27294. this.uv = uv;
  27295. this.id = id;
  27296. this.isBorder = true;
  27297. this.q = new QuadraticMatrix();
  27298. this.triangleCount = 0;
  27299. this.triangleStart = 0;
  27300. }
  27301. return DecimationVertex;
  27302. })();
  27303. BABYLON.DecimationVertex = DecimationVertex;
  27304. var QuadraticMatrix = (function () {
  27305. function QuadraticMatrix(data) {
  27306. this.data = new Array(10);
  27307. for (var i = 0; i < 10; ++i) {
  27308. if (data && data[i]) {
  27309. this.data[i] = data[i];
  27310. }
  27311. else {
  27312. this.data[i] = 0;
  27313. }
  27314. }
  27315. }
  27316. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  27317. 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];
  27318. return det;
  27319. };
  27320. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  27321. for (var i = 0; i < 10; ++i) {
  27322. this.data[i] += matrix.data[i];
  27323. }
  27324. };
  27325. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  27326. for (var i = 0; i < 10; ++i) {
  27327. this.data[i] += data[i];
  27328. }
  27329. };
  27330. QuadraticMatrix.prototype.add = function (matrix) {
  27331. var m = new QuadraticMatrix();
  27332. for (var i = 0; i < 10; ++i) {
  27333. m.data[i] = this.data[i] + matrix.data[i];
  27334. }
  27335. return m;
  27336. };
  27337. QuadraticMatrix.FromData = function (a, b, c, d) {
  27338. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  27339. };
  27340. //returning an array to avoid garbage collection
  27341. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  27342. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  27343. };
  27344. return QuadraticMatrix;
  27345. })();
  27346. BABYLON.QuadraticMatrix = QuadraticMatrix;
  27347. var Reference = (function () {
  27348. function Reference(vertexId, triangleId) {
  27349. this.vertexId = vertexId;
  27350. this.triangleId = triangleId;
  27351. }
  27352. return Reference;
  27353. })();
  27354. BABYLON.Reference = Reference;
  27355. /**
  27356. * An implementation of the Quadratic Error simplification algorithm.
  27357. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  27358. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  27359. * @author RaananW
  27360. */
  27361. var QuadraticErrorSimplification = (function () {
  27362. function QuadraticErrorSimplification(_mesh) {
  27363. this._mesh = _mesh;
  27364. this.initialised = false;
  27365. this.syncIterations = 5000;
  27366. this.aggressiveness = 7;
  27367. this.decimationIterations = 100;
  27368. }
  27369. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  27370. var _this = this;
  27371. this.initWithMesh(this._mesh, function () {
  27372. _this.runDecimation(settings, successCallback);
  27373. });
  27374. };
  27375. QuadraticErrorSimplification.prototype.runDecimation = function (settings, successCallback) {
  27376. var _this = this;
  27377. var targetCount = ~~(this.triangles.length * settings.quality);
  27378. var deletedTriangles = 0;
  27379. var triangleCount = this.triangles.length;
  27380. var iterationFunction = function (iteration, callback) {
  27381. setTimeout(function () {
  27382. if (iteration % 5 === 0) {
  27383. _this.updateMesh(iteration === 0);
  27384. }
  27385. for (var i = 0; i < _this.triangles.length; ++i) {
  27386. _this.triangles[i].isDirty = false;
  27387. }
  27388. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  27389. var trianglesIterator = function (i) {
  27390. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  27391. var t = _this.triangles[tIdx];
  27392. if (!t)
  27393. return;
  27394. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  27395. return;
  27396. }
  27397. for (var j = 0; j < 3; ++j) {
  27398. if (t.error[j] < threshold) {
  27399. var deleted0 = [];
  27400. var deleted1 = [];
  27401. var i0 = t.vertices[j];
  27402. var i1 = t.vertices[(j + 1) % 3];
  27403. var v0 = _this.vertices[i0];
  27404. var v1 = _this.vertices[i1];
  27405. if (v0.isBorder !== v1.isBorder)
  27406. continue;
  27407. var p = BABYLON.Vector3.Zero();
  27408. var n = BABYLON.Vector3.Zero();
  27409. var uv = BABYLON.Vector2.Zero();
  27410. var color = new BABYLON.Color4(0, 0, 0, 1);
  27411. _this.calculateError(v0, v1, p, n, uv, color);
  27412. var delTr = [];
  27413. if (_this.isFlipped(v0, i1, p, deleted0, t.borderFactor, delTr))
  27414. continue;
  27415. if (_this.isFlipped(v1, i0, p, deleted1, t.borderFactor, delTr))
  27416. continue;
  27417. if (delTr.length == 2 || delTr[0] === delTr[1]) {
  27418. continue;
  27419. }
  27420. v0.normal = n;
  27421. if (v0.uv)
  27422. v0.uv = uv;
  27423. else if (v0.color)
  27424. v0.color = color;
  27425. v0.q = v1.q.add(v0.q);
  27426. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  27427. continue;
  27428. if (p.equals(v0.position))
  27429. continue;
  27430. v0.position = p;
  27431. var tStart = _this.references.length;
  27432. deletedTriangles = _this.updateTriangles(v0.id, v0, deleted0, deletedTriangles);
  27433. deletedTriangles = _this.updateTriangles(v0.id, v1, deleted1, deletedTriangles);
  27434. var tCount = _this.references.length - tStart;
  27435. if (tCount <= v0.triangleCount) {
  27436. if (tCount) {
  27437. for (var c = 0; c < tCount; c++) {
  27438. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  27439. }
  27440. }
  27441. }
  27442. else {
  27443. v0.triangleStart = tStart;
  27444. }
  27445. v0.triangleCount = tCount;
  27446. break;
  27447. }
  27448. }
  27449. };
  27450. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () {
  27451. return (triangleCount - deletedTriangles <= targetCount);
  27452. });
  27453. }, 0);
  27454. };
  27455. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  27456. if (triangleCount - deletedTriangles <= targetCount)
  27457. loop.breakLoop();
  27458. else {
  27459. iterationFunction(loop.index, function () {
  27460. loop.executeNext();
  27461. });
  27462. }
  27463. }, function () {
  27464. setTimeout(function () {
  27465. successCallback(_this.reconstructMesh());
  27466. }, 0);
  27467. });
  27468. };
  27469. QuadraticErrorSimplification.prototype.initWithMesh = function (mesh, callback) {
  27470. var _this = this;
  27471. if (!mesh)
  27472. return;
  27473. this.vertices = [];
  27474. this.triangles = [];
  27475. this._mesh = mesh;
  27476. //It is assumed that a mesh has positions, normals and either uvs or colors.
  27477. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27478. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  27479. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  27480. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  27481. var indices = mesh.getIndices();
  27482. var vertexInit = function (i) {
  27483. var vertex = new DecimationVertex(BABYLON.Vector3.FromArray(positionData, i * 3), BABYLON.Vector3.FromArray(normalData, i * 3), null, i);
  27484. if (_this._mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  27485. vertex.uv = BABYLON.Vector2.FromArray(uvs, i * 2);
  27486. }
  27487. else if (_this._mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  27488. vertex.color = BABYLON.Color4.FromArray(colorsData, i * 4);
  27489. }
  27490. _this.vertices.push(vertex);
  27491. };
  27492. var totalVertices = mesh.getTotalVertices();
  27493. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, this.syncIterations, vertexInit, function () {
  27494. var indicesInit = function (i) {
  27495. var pos = i * 3;
  27496. var i0 = indices[pos + 0];
  27497. var i1 = indices[pos + 1];
  27498. var i2 = indices[pos + 2];
  27499. var triangle = new DecimationTriangle([_this.vertices[i0].id, _this.vertices[i1].id, _this.vertices[i2].id]);
  27500. _this.triangles.push(triangle);
  27501. };
  27502. BABYLON.AsyncLoop.SyncAsyncForLoop(indices.length / 3, _this.syncIterations, indicesInit, function () {
  27503. _this.init(callback);
  27504. });
  27505. });
  27506. };
  27507. QuadraticErrorSimplification.prototype.init = function (callback) {
  27508. var _this = this;
  27509. var triangleInit1 = function (i) {
  27510. var t = _this.triangles[i];
  27511. 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();
  27512. for (var j = 0; j < 3; j++) {
  27513. _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))));
  27514. }
  27515. };
  27516. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  27517. var triangleInit2 = function (i) {
  27518. var t = _this.triangles[i];
  27519. for (var j = 0; j < 3; ++j) {
  27520. t.error[j] = _this.calculateError(_this.vertices[t.vertices[j]], _this.vertices[t.vertices[(j + 1) % 3]]);
  27521. }
  27522. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  27523. };
  27524. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  27525. _this.initialised = true;
  27526. callback();
  27527. });
  27528. });
  27529. };
  27530. QuadraticErrorSimplification.prototype.reconstructMesh = function () {
  27531. var newTriangles = [];
  27532. var i;
  27533. for (i = 0; i < this.vertices.length; ++i) {
  27534. this.vertices[i].triangleCount = 0;
  27535. }
  27536. var t;
  27537. var j;
  27538. for (i = 0; i < this.triangles.length; ++i) {
  27539. if (!this.triangles[i].deleted) {
  27540. t = this.triangles[i];
  27541. for (j = 0; j < 3; ++j) {
  27542. this.vertices[t.vertices[j]].triangleCount = 1;
  27543. }
  27544. newTriangles.push(t);
  27545. }
  27546. }
  27547. var newVerticesOrder = [];
  27548. //compact vertices, get the IDs of the vertices used.
  27549. var dst = 0;
  27550. for (i = 0; i < this.vertices.length; ++i) {
  27551. if (this.vertices[i].triangleCount) {
  27552. this.vertices[i].triangleStart = dst;
  27553. this.vertices[dst].position = this.vertices[i].position;
  27554. this.vertices[dst].normal = this.vertices[i].normal;
  27555. this.vertices[dst].uv = this.vertices[i].uv;
  27556. this.vertices[dst].color = this.vertices[i].color;
  27557. newVerticesOrder.push(i);
  27558. dst++;
  27559. }
  27560. }
  27561. for (i = 0; i < newTriangles.length; ++i) {
  27562. t = newTriangles[i];
  27563. for (j = 0; j < 3; ++j) {
  27564. t.vertices[j] = this.vertices[t.vertices[j]].triangleStart;
  27565. }
  27566. }
  27567. this.vertices = this.vertices.slice(0, dst);
  27568. var newPositionData = [];
  27569. var newNormalData = [];
  27570. var newUVsData = [];
  27571. var newColorsData = [];
  27572. for (i = 0; i < newVerticesOrder.length; ++i) {
  27573. newPositionData.push(this.vertices[i].position.x);
  27574. newPositionData.push(this.vertices[i].position.y);
  27575. newPositionData.push(this.vertices[i].position.z);
  27576. newNormalData.push(this.vertices[i].normal.x);
  27577. newNormalData.push(this.vertices[i].normal.y);
  27578. newNormalData.push(this.vertices[i].normal.z);
  27579. if (this.vertices[i].uv) {
  27580. newUVsData.push(this.vertices[i].uv.x);
  27581. newUVsData.push(this.vertices[i].uv.y);
  27582. }
  27583. else if (this.vertices[i].color) {
  27584. newColorsData.push(this.vertices[i].color.r);
  27585. newColorsData.push(this.vertices[i].color.g);
  27586. newColorsData.push(this.vertices[i].color.b);
  27587. newColorsData.push(this.vertices[i].color.a);
  27588. }
  27589. }
  27590. var newIndicesArray = [];
  27591. for (i = 0; i < newTriangles.length; ++i) {
  27592. newIndicesArray.push(newTriangles[i].vertices[0]);
  27593. newIndicesArray.push(newTriangles[i].vertices[1]);
  27594. newIndicesArray.push(newTriangles[i].vertices[2]);
  27595. }
  27596. //not cloning, to avoid geometry problems. Creating a whole new mesh.
  27597. var newMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  27598. newMesh.material = this._mesh.material;
  27599. newMesh.parent = this._mesh.parent;
  27600. newMesh.setIndices(newIndicesArray);
  27601. newMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  27602. newMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  27603. if (newUVsData.length > 0)
  27604. newMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  27605. if (newColorsData.length > 0)
  27606. newMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  27607. //preparing the skeleton support
  27608. if (this._mesh.skeleton) {
  27609. }
  27610. return newMesh;
  27611. };
  27612. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, index2, point, deletedArray, borderFactor, delTr) {
  27613. for (var i = 0; i < vertex1.triangleCount; ++i) {
  27614. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  27615. if (t.deleted)
  27616. continue;
  27617. var s = this.references[vertex1.triangleStart + i].vertexId;
  27618. var id1 = t.vertices[(s + 1) % 3];
  27619. var id2 = t.vertices[(s + 2) % 3];
  27620. if ((id1 === index2 || id2 === index2) && borderFactor < 2) {
  27621. deletedArray[i] = true;
  27622. delTr.push(t);
  27623. continue;
  27624. }
  27625. var d1 = this.vertices[id1].position.subtract(point);
  27626. d1 = d1.normalize();
  27627. var d2 = this.vertices[id2].position.subtract(point);
  27628. d2 = d2.normalize();
  27629. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  27630. return true;
  27631. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  27632. deletedArray[i] = false;
  27633. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  27634. return true;
  27635. }
  27636. return false;
  27637. };
  27638. QuadraticErrorSimplification.prototype.updateTriangles = function (vertexId, vertex, deletedArray, deletedTriangles) {
  27639. var newDeleted = deletedTriangles;
  27640. for (var i = 0; i < vertex.triangleCount; ++i) {
  27641. var ref = this.references[vertex.triangleStart + i];
  27642. var t = this.triangles[ref.triangleId];
  27643. if (t.deleted)
  27644. continue;
  27645. if (deletedArray[i]) {
  27646. t.deleted = true;
  27647. newDeleted++;
  27648. continue;
  27649. }
  27650. t.vertices[ref.vertexId] = vertexId;
  27651. t.isDirty = true;
  27652. t.error[0] = this.calculateError(this.vertices[t.vertices[0]], this.vertices[t.vertices[1]]) + (t.borderFactor / 2);
  27653. t.error[1] = this.calculateError(this.vertices[t.vertices[1]], this.vertices[t.vertices[2]]) + (t.borderFactor / 2);
  27654. t.error[2] = this.calculateError(this.vertices[t.vertices[2]], this.vertices[t.vertices[0]]) + (t.borderFactor / 2);
  27655. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  27656. this.references.push(ref);
  27657. }
  27658. return newDeleted;
  27659. };
  27660. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  27661. for (var i = 0; i < this.vertices.length; ++i) {
  27662. var vCount = [];
  27663. var vId = [];
  27664. var v = this.vertices[i];
  27665. var j;
  27666. for (j = 0; j < v.triangleCount; ++j) {
  27667. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  27668. for (var ii = 0; ii < 3; ii++) {
  27669. var ofs = 0;
  27670. var id = triangle.vertices[ii];
  27671. while (ofs < vCount.length) {
  27672. if (vId[ofs] === id)
  27673. break;
  27674. ++ofs;
  27675. }
  27676. if (ofs === vCount.length) {
  27677. vCount.push(1);
  27678. vId.push(id);
  27679. }
  27680. else {
  27681. vCount[ofs]++;
  27682. }
  27683. }
  27684. }
  27685. for (j = 0; j < vCount.length; ++j) {
  27686. if (vCount[j] === 1) {
  27687. this.vertices[vId[j]].isBorder = true;
  27688. }
  27689. else {
  27690. this.vertices[vId[j]].isBorder = false;
  27691. }
  27692. }
  27693. }
  27694. };
  27695. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  27696. if (identifyBorders === void 0) { identifyBorders = false; }
  27697. var i;
  27698. if (!identifyBorders) {
  27699. var newTrianglesVector = [];
  27700. for (i = 0; i < this.triangles.length; ++i) {
  27701. if (!this.triangles[i].deleted) {
  27702. newTrianglesVector.push(this.triangles[i]);
  27703. }
  27704. }
  27705. this.triangles = newTrianglesVector;
  27706. }
  27707. for (i = 0; i < this.vertices.length; ++i) {
  27708. this.vertices[i].triangleCount = 0;
  27709. this.vertices[i].triangleStart = 0;
  27710. }
  27711. var t;
  27712. var j;
  27713. var v;
  27714. for (i = 0; i < this.triangles.length; ++i) {
  27715. t = this.triangles[i];
  27716. for (j = 0; j < 3; ++j) {
  27717. v = this.vertices[t.vertices[j]];
  27718. v.triangleCount++;
  27719. }
  27720. }
  27721. var tStart = 0;
  27722. for (i = 0; i < this.vertices.length; ++i) {
  27723. this.vertices[i].triangleStart = tStart;
  27724. tStart += this.vertices[i].triangleCount;
  27725. this.vertices[i].triangleCount = 0;
  27726. }
  27727. var newReferences = new Array(this.triangles.length * 3);
  27728. for (i = 0; i < this.triangles.length; ++i) {
  27729. t = this.triangles[i];
  27730. for (j = 0; j < 3; ++j) {
  27731. v = this.vertices[t.vertices[j]];
  27732. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  27733. v.triangleCount++;
  27734. }
  27735. }
  27736. this.references = newReferences;
  27737. if (identifyBorders) {
  27738. this.identifyBorder();
  27739. }
  27740. };
  27741. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  27742. var x = point.x;
  27743. var y = point.y;
  27744. var z = point.z;
  27745. 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];
  27746. };
  27747. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  27748. var q = vertex1.q.add(vertex2.q);
  27749. var border = vertex1.isBorder && vertex2.isBorder;
  27750. var error = 0;
  27751. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  27752. if (qDet !== 0 && !border) {
  27753. if (!pointResult) {
  27754. pointResult = BABYLON.Vector3.Zero();
  27755. }
  27756. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  27757. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  27758. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  27759. error = this.vertexError(q, pointResult);
  27760. //TODO this should be correctly calculated
  27761. if (normalResult) {
  27762. normalResult.copyFrom(vertex1.normal);
  27763. if (vertex1.uv)
  27764. uvResult.copyFrom(vertex1.uv);
  27765. else if (vertex1.color)
  27766. colorResult.copyFrom(vertex1.color);
  27767. }
  27768. }
  27769. else {
  27770. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  27771. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  27772. var error1 = this.vertexError(q, vertex1.position);
  27773. var error2 = this.vertexError(q, vertex2.position);
  27774. var error3 = this.vertexError(q, p3);
  27775. error = Math.min(error1, error2, error3);
  27776. if (error === error1) {
  27777. if (pointResult) {
  27778. pointResult.copyFrom(vertex1.position);
  27779. normalResult.copyFrom(vertex1.normal);
  27780. if (vertex1.uv)
  27781. uvResult.copyFrom(vertex1.uv);
  27782. else if (vertex1.color)
  27783. colorResult.copyFrom(vertex1.color);
  27784. }
  27785. }
  27786. else if (error === error2) {
  27787. if (pointResult) {
  27788. pointResult.copyFrom(vertex2.position);
  27789. normalResult.copyFrom(vertex2.normal);
  27790. if (vertex2.uv)
  27791. uvResult.copyFrom(vertex2.uv);
  27792. else if (vertex2.color)
  27793. colorResult.copyFrom(vertex2.color);
  27794. }
  27795. }
  27796. else {
  27797. if (pointResult) {
  27798. pointResult.copyFrom(p3);
  27799. normalResult.copyFrom(vertex1.normal);
  27800. if (vertex1.uv)
  27801. uvResult.copyFrom(vertex1.uv);
  27802. else if (vertex1.color)
  27803. colorResult.copyFrom(vertex1.color);
  27804. }
  27805. }
  27806. }
  27807. return error;
  27808. };
  27809. return QuadraticErrorSimplification;
  27810. })();
  27811. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  27812. })(BABYLON || (BABYLON = {}));
  27813. //# sourceMappingURL=babylon.meshSimplification.js.mapvar BABYLON;
  27814. (function (BABYLON) {
  27815. var Analyser = (function () {
  27816. function Analyser(scene) {
  27817. this.SMOOTHING = 0.75;
  27818. this.FFT_SIZE = 512;
  27819. this.BARGRAPHAMPLITUDE = 256;
  27820. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  27821. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  27822. this._scene = scene;
  27823. this._audioEngine = BABYLON.Engine.audioEngine;
  27824. if (this._audioEngine.canUseWebAudio) {
  27825. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  27826. this._webAudioAnalyser.minDecibels = -140;
  27827. this._webAudioAnalyser.maxDecibels = 0;
  27828. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  27829. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  27830. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  27831. }
  27832. }
  27833. Analyser.prototype.getFrequencyBinCount = function () {
  27834. if (this._audioEngine.canUseWebAudio) {
  27835. return this._webAudioAnalyser.frequencyBinCount;
  27836. }
  27837. else {
  27838. return 0;
  27839. }
  27840. };
  27841. Analyser.prototype.getByteFrequencyData = function () {
  27842. if (this._audioEngine.canUseWebAudio) {
  27843. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  27844. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  27845. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  27846. }
  27847. return this._byteFreqs;
  27848. };
  27849. Analyser.prototype.getByteTimeDomainData = function () {
  27850. if (this._audioEngine.canUseWebAudio) {
  27851. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  27852. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  27853. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  27854. }
  27855. return this._byteTime;
  27856. };
  27857. Analyser.prototype.getFloatFrequencyData = function () {
  27858. if (this._audioEngine.canUseWebAudio) {
  27859. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  27860. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  27861. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  27862. }
  27863. return this._floatFreqs;
  27864. };
  27865. Analyser.prototype.drawDebugCanvas = function () {
  27866. var _this = this;
  27867. if (this._audioEngine.canUseWebAudio) {
  27868. if (!this._debugCanvas) {
  27869. this._debugCanvas = document.createElement("canvas");
  27870. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  27871. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  27872. this._debugCanvas.style.position = "absolute";
  27873. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  27874. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  27875. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  27876. document.body.appendChild(this._debugCanvas);
  27877. this._registerFunc = function () {
  27878. _this.drawDebugCanvas();
  27879. };
  27880. this._scene.registerBeforeRender(this._registerFunc);
  27881. }
  27882. if (this._registerFunc) {
  27883. var workingArray = this.getByteFrequencyData();
  27884. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  27885. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  27886. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  27887. var value = workingArray[i];
  27888. var percent = value / this.BARGRAPHAMPLITUDE;
  27889. var height = this.DEBUGCANVASSIZE.height * percent;
  27890. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  27891. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  27892. var hue = i / this.getFrequencyBinCount() * 360;
  27893. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  27894. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  27895. }
  27896. }
  27897. }
  27898. };
  27899. Analyser.prototype.stopDebugCanvas = function () {
  27900. if (this._debugCanvas) {
  27901. this._scene.unregisterBeforeRender(this._registerFunc);
  27902. this._registerFunc = null;
  27903. document.body.removeChild(this._debugCanvas);
  27904. this._debugCanvas = null;
  27905. this._debugCanvasContext = null;
  27906. }
  27907. };
  27908. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  27909. if (this._audioEngine.canUseWebAudio) {
  27910. inputAudioNode.connect(this._webAudioAnalyser);
  27911. this._webAudioAnalyser.connect(outputAudioNode);
  27912. }
  27913. };
  27914. Analyser.prototype.dispose = function () {
  27915. if (this._audioEngine.canUseWebAudio) {
  27916. this._webAudioAnalyser.disconnect();
  27917. }
  27918. };
  27919. return Analyser;
  27920. })();
  27921. BABYLON.Analyser = Analyser;
  27922. })(BABYLON || (BABYLON = {}));
  27923. //# sourceMappingURL=babylon.analyser.js.mapvar BABYLON;
  27924. (function (BABYLON) {
  27925. var DepthRenderer = (function () {
  27926. function DepthRenderer(scene, type) {
  27927. var _this = this;
  27928. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  27929. this._viewMatrix = BABYLON.Matrix.Zero();
  27930. this._projectionMatrix = BABYLON.Matrix.Zero();
  27931. this._transformMatrix = BABYLON.Matrix.Zero();
  27932. this._worldViewProjection = BABYLON.Matrix.Zero();
  27933. this._scene = scene;
  27934. var engine = scene.getEngine();
  27935. // Render target
  27936. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  27937. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  27938. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  27939. this._depthMap.refreshRate = 1;
  27940. this._depthMap.renderParticles = false;
  27941. this._depthMap.renderList = null;
  27942. // Custom render function
  27943. var renderSubMesh = function (subMesh) {
  27944. var mesh = subMesh.getRenderingMesh();
  27945. var scene = _this._scene;
  27946. var engine = scene.getEngine();
  27947. // Culling
  27948. engine.setState(subMesh.getMaterial().backFaceCulling);
  27949. // Managing instances
  27950. var batch = mesh._getInstancesRenderList(subMesh._id);
  27951. if (batch.mustReturn) {
  27952. return;
  27953. }
  27954. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  27955. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  27956. engine.enableEffect(_this._effect);
  27957. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  27958. var material = subMesh.getMaterial();
  27959. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  27960. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  27961. // Alpha test
  27962. if (material && material.needAlphaTesting()) {
  27963. var alphaTexture = material.getAlphaTestTexture();
  27964. _this._effect.setTexture("diffuseSampler", alphaTexture);
  27965. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  27966. }
  27967. // Bones
  27968. if (mesh.useBones) {
  27969. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  27970. }
  27971. // Draw
  27972. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  27973. }
  27974. };
  27975. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  27976. var index;
  27977. for (index = 0; index < opaqueSubMeshes.length; index++) {
  27978. renderSubMesh(opaqueSubMeshes.data[index]);
  27979. }
  27980. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  27981. renderSubMesh(alphaTestSubMeshes.data[index]);
  27982. }
  27983. };
  27984. }
  27985. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  27986. var defines = [];
  27987. var attribs = [BABYLON.VertexBuffer.PositionKind];
  27988. var mesh = subMesh.getMesh();
  27989. var scene = mesh.getScene();
  27990. var material = subMesh.getMaterial();
  27991. // Alpha test
  27992. if (material && material.needAlphaTesting()) {
  27993. defines.push("#define ALPHATEST");
  27994. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  27995. attribs.push(BABYLON.VertexBuffer.UVKind);
  27996. defines.push("#define UV1");
  27997. }
  27998. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  27999. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  28000. defines.push("#define UV2");
  28001. }
  28002. }
  28003. // Bones
  28004. if (mesh.useBones) {
  28005. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  28006. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  28007. defines.push("#define BONES");
  28008. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  28009. }
  28010. // Instances
  28011. if (useInstances) {
  28012. defines.push("#define INSTANCES");
  28013. attribs.push("world0");
  28014. attribs.push("world1");
  28015. attribs.push("world2");
  28016. attribs.push("world3");
  28017. }
  28018. // Get correct effect
  28019. var join = defines.join("\n");
  28020. if (this._cachedDefines !== join) {
  28021. this._cachedDefines = join;
  28022. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  28023. }
  28024. return this._effect.isReady();
  28025. };
  28026. DepthRenderer.prototype.getDepthMap = function () {
  28027. return this._depthMap;
  28028. };
  28029. // Methods
  28030. DepthRenderer.prototype.dispose = function () {
  28031. this._depthMap.dispose();
  28032. };
  28033. return DepthRenderer;
  28034. })();
  28035. BABYLON.DepthRenderer = DepthRenderer;
  28036. })(BABYLON || (BABYLON = {}));
  28037. //# sourceMappingURL=babylon.depthRenderer.js.map
  28038. var BABYLON;
  28039. (function (BABYLON) {
  28040. var SSAORenderingPipeline = (function (_super) {
  28041. __extends(SSAORenderingPipeline, _super);
  28042. /**
  28043. * @constructor
  28044. * @param {string} name - The rendering pipeline name
  28045. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  28046. * @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)
  28047. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  28048. */
  28049. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  28050. var _this = this;
  28051. _super.call(this, scene.getEngine(), name);
  28052. // Members
  28053. /**
  28054. * The PassPostProcess id in the pipeline that contains the original scene color
  28055. * @type {string}
  28056. */
  28057. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  28058. /**
  28059. * The SSAO PostProcess id in the pipeline
  28060. * @type {string}
  28061. */
  28062. this.SSAORenderEffect = "SSAORenderEffect";
  28063. /**
  28064. * The horizontal blur PostProcess id in the pipeline
  28065. * @type {string}
  28066. */
  28067. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  28068. /**
  28069. * The vertical blur PostProcess id in the pipeline
  28070. * @type {string}
  28071. */
  28072. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  28073. /**
  28074. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  28075. * @type {string}
  28076. */
  28077. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  28078. this._firstUpdate = true;
  28079. this._scene = scene;
  28080. // Set up assets
  28081. this._createRandomTexture();
  28082. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  28083. var ssaoRatio = ratio.ssaoRatio || ratio;
  28084. var combineRatio = ratio.combineRatio || ratio;
  28085. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  28086. this._createSSAOPostProcess(ssaoRatio);
  28087. this._blurHPostProcess = new BABYLON.BlurPostProcess("SSAOBlurH", new BABYLON.Vector2(2.0, 0.0), 1.3, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  28088. this._blurVPostProcess = new BABYLON.BlurPostProcess("SSAOBlurV", new BABYLON.Vector2(0.0, 2.0), 1.3, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  28089. this._createSSAOCombinePostProcess(combineRatio);
  28090. // Set up pipeline
  28091. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () {
  28092. return _this._originalColorPostProcess;
  28093. }, true));
  28094. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () {
  28095. return _this._ssaoPostProcess;
  28096. }, true));
  28097. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () {
  28098. return _this._blurHPostProcess;
  28099. }, true));
  28100. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () {
  28101. return _this._blurVPostProcess;
  28102. }, true));
  28103. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () {
  28104. return _this._ssaoCombinePostProcess;
  28105. }, true));
  28106. // Finish
  28107. scene.postProcessRenderPipelineManager.addPipeline(this);
  28108. if (cameras)
  28109. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  28110. }
  28111. // Public Methods
  28112. /**
  28113. * Returns the horizontal blur PostProcess
  28114. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  28115. */
  28116. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  28117. return this._blurHPostProcess;
  28118. };
  28119. /**
  28120. * Returns the vertical blur PostProcess
  28121. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  28122. */
  28123. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  28124. return this._blurVPostProcess;
  28125. };
  28126. /**
  28127. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  28128. */
  28129. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  28130. if (disableDepthRender === void 0) { disableDepthRender = false; }
  28131. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  28132. this._originalColorPostProcess = undefined;
  28133. this._ssaoPostProcess = undefined;
  28134. this._blurHPostProcess = undefined;
  28135. this._blurVPostProcess = undefined;
  28136. this._ssaoCombinePostProcess = undefined;
  28137. this._randomTexture.dispose();
  28138. if (disableDepthRender)
  28139. this._scene.disableDepthRenderer();
  28140. };
  28141. // Private Methods
  28142. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  28143. var _this = this;
  28144. var sampleSphere = [
  28145. 0.5381,
  28146. 0.1856,
  28147. -0.4319,
  28148. 0.1379,
  28149. 0.2486,
  28150. 0.4430,
  28151. 0.3371,
  28152. 0.5679,
  28153. -0.0057,
  28154. -0.6999,
  28155. -0.0451,
  28156. -0.0019,
  28157. 0.0689,
  28158. -0.1598,
  28159. -0.8547,
  28160. 0.0560,
  28161. 0.0069,
  28162. -0.1843,
  28163. -0.0146,
  28164. 0.1402,
  28165. 0.0762,
  28166. 0.0100,
  28167. -0.1924,
  28168. -0.0344,
  28169. -0.3577,
  28170. -0.5301,
  28171. -0.4358,
  28172. -0.3169,
  28173. 0.1063,
  28174. 0.0158,
  28175. 0.0103,
  28176. -0.5869,
  28177. 0.0046,
  28178. -0.0897,
  28179. -0.4940,
  28180. 0.3287,
  28181. 0.7119,
  28182. -0.0154,
  28183. -0.0918,
  28184. -0.0533,
  28185. 0.0596,
  28186. -0.5411,
  28187. 0.0352,
  28188. -0.0631,
  28189. 0.5460,
  28190. -0.4776,
  28191. 0.2847,
  28192. -0.0271
  28193. ];
  28194. var samplesFactor = 1.0 / 16.0;
  28195. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", ["sampleSphere", "samplesFactor", "randTextureTiles"], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  28196. this._ssaoPostProcess.onApply = function (effect) {
  28197. if (_this._firstUpdate) {
  28198. effect.setArray3("sampleSphere", sampleSphere);
  28199. effect.setFloat("samplesFactor", samplesFactor);
  28200. effect.setFloat("randTextureTiles", 4.0 / ratio);
  28201. _this._firstUpdate = false;
  28202. }
  28203. effect.setTexture("textureSampler", _this._depthTexture);
  28204. effect.setTexture("randomSampler", _this._randomTexture);
  28205. };
  28206. };
  28207. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  28208. var _this = this;
  28209. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  28210. this._ssaoCombinePostProcess.onApply = function (effect) {
  28211. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  28212. };
  28213. };
  28214. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  28215. var size = 512;
  28216. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  28217. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  28218. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  28219. var context = this._randomTexture.getContext();
  28220. var rand = function (min, max) {
  28221. return Math.random() * (max - min) + min;
  28222. };
  28223. for (var x = 0; x < size; x++) {
  28224. for (var y = 0; y < size; y++) {
  28225. var randVector = BABYLON.Vector3.Zero();
  28226. randVector.x = Math.floor(rand(0.0, 1.0) * 255);
  28227. randVector.y = Math.floor(rand(0.0, 1.0) * 255);
  28228. randVector.z = Math.floor(rand(0.0, 1.0) * 255);
  28229. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  28230. context.fillRect(x, y, 1, 1);
  28231. }
  28232. }
  28233. this._randomTexture.update(false);
  28234. };
  28235. return SSAORenderingPipeline;
  28236. })(BABYLON.PostProcessRenderPipeline);
  28237. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  28238. })(BABYLON || (BABYLON = {}));
  28239. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  28240. var BABYLON;
  28241. (function (BABYLON) {
  28242. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  28243. var VolumetricLightScatteringPostProcess = (function (_super) {
  28244. __extends(VolumetricLightScatteringPostProcess, _super);
  28245. /**
  28246. * @constructor
  28247. * @param {string} name - The post-process name
  28248. * @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)
  28249. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  28250. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  28251. * @param {number} samples - The post-process quality, default 100
  28252. * @param {number} samplingMode - The post-process filtering mode
  28253. * @param {BABYLON.Engine} engine - The babylon engine
  28254. * @param {boolean} reusable - If the post-process is reusable
  28255. */
  28256. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable) {
  28257. var _this = this;
  28258. if (samples === void 0) { samples = 100; }
  28259. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  28260. _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  28261. this._screenCoordinates = BABYLON.Vector2.Zero();
  28262. /**
  28263. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  28264. * @type {boolean}
  28265. */
  28266. this.useCustomMeshPosition = false;
  28267. /**
  28268. * If the post-process should inverse the light scattering direction
  28269. * @type {boolean}
  28270. */
  28271. this.invert = true;
  28272. /**
  28273. * Array containing the excluded meshes not rendered in the internal pass
  28274. */
  28275. this.excludedMeshes = new Array();
  28276. this.exposure = 0.3;
  28277. this.decay = 0.96815;
  28278. this.weight = 0.58767;
  28279. this.density = 0.926;
  28280. var scene = camera.getScene();
  28281. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(scene.getEngine());
  28282. // Configure mesh
  28283. this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  28284. // Configure
  28285. this._createPass(scene, ratio.passRatio || ratio);
  28286. this.onApply = function (effect) {
  28287. _this._updateMeshScreenCoordinates(scene);
  28288. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  28289. effect.setFloat("exposure", _this.exposure);
  28290. effect.setFloat("decay", _this.decay);
  28291. effect.setFloat("weight", _this.weight);
  28292. effect.setFloat("density", _this.density);
  28293. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  28294. };
  28295. }
  28296. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  28297. var mesh = subMesh.getMesh();
  28298. var defines = [];
  28299. var attribs = [BABYLON.VertexBuffer.PositionKind];
  28300. var material = subMesh.getMaterial();
  28301. // Render this.mesh as default
  28302. if (mesh === this.mesh) {
  28303. defines.push("#define BASIC_RENDER");
  28304. }
  28305. // Alpha test
  28306. if (material) {
  28307. if (material.needAlphaTesting() || mesh === this.mesh)
  28308. defines.push("#define ALPHATEST");
  28309. if (material.opacityTexture !== undefined)
  28310. defines.push("#define OPACITY");
  28311. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  28312. attribs.push(BABYLON.VertexBuffer.UVKind);
  28313. defines.push("#define UV1");
  28314. }
  28315. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  28316. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  28317. defines.push("#define UV2");
  28318. }
  28319. }
  28320. // Bones
  28321. if (mesh.useBones) {
  28322. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  28323. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  28324. defines.push("#define BONES");
  28325. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  28326. }
  28327. // Instances
  28328. if (useInstances) {
  28329. defines.push("#define INSTANCES");
  28330. attribs.push("world0");
  28331. attribs.push("world1");
  28332. attribs.push("world2");
  28333. attribs.push("world3");
  28334. }
  28335. // Get correct effect
  28336. var join = defines.join("\n");
  28337. if (this._cachedDefines !== join) {
  28338. this._cachedDefines = join;
  28339. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler", "opacitySampler"], join);
  28340. }
  28341. return this._volumetricLightScatteringPass.isReady();
  28342. };
  28343. /**
  28344. * Sets the new light position for light scattering effect
  28345. * @param {BABYLON.Vector3} The new custom light position
  28346. */
  28347. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  28348. this._customMeshPosition = position;
  28349. };
  28350. /**
  28351. * Returns the light position for light scattering effect
  28352. * @return {BABYLON.Vector3} The custom light position
  28353. */
  28354. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  28355. return this._customMeshPosition;
  28356. };
  28357. /**
  28358. * Disposes the internal assets and detaches the post-process from the camera
  28359. */
  28360. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  28361. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  28362. if (rttIndex !== -1) {
  28363. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  28364. }
  28365. this._volumetricLightScatteringRTT.dispose();
  28366. _super.prototype.dispose.call(this, camera);
  28367. };
  28368. /**
  28369. * Returns the render target texture used by the post-process
  28370. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  28371. */
  28372. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  28373. return this._volumetricLightScatteringRTT;
  28374. };
  28375. // Private methods
  28376. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  28377. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  28378. return true;
  28379. }
  28380. return false;
  28381. };
  28382. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  28383. var _this = this;
  28384. var engine = scene.getEngine();
  28385. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  28386. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  28387. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  28388. this._volumetricLightScatteringRTT.renderList = null;
  28389. this._volumetricLightScatteringRTT.renderParticles = false;
  28390. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  28391. // Custom render function for submeshes
  28392. var renderSubMesh = function (subMesh) {
  28393. var mesh = subMesh.getRenderingMesh();
  28394. if (_this._meshExcluded(mesh)) {
  28395. return;
  28396. }
  28397. var scene = mesh.getScene();
  28398. var engine = scene.getEngine();
  28399. // Culling
  28400. engine.setState(subMesh.getMaterial().backFaceCulling);
  28401. // Managing instances
  28402. var batch = mesh._getInstancesRenderList(subMesh._id);
  28403. if (batch.mustReturn) {
  28404. return;
  28405. }
  28406. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  28407. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  28408. engine.enableEffect(_this._volumetricLightScatteringPass);
  28409. mesh._bind(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode);
  28410. var material = subMesh.getMaterial();
  28411. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  28412. // Alpha test
  28413. if (material && (mesh === _this.mesh || material.needAlphaTesting() || material.opacityTexture !== undefined)) {
  28414. var alphaTexture = material.getAlphaTestTexture();
  28415. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  28416. if (_this.mesh.material && alphaTexture)
  28417. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  28418. if (material.opacityTexture !== undefined)
  28419. _this._volumetricLightScatteringPass.setTexture("opacitySampler", material.opacityTexture);
  28420. }
  28421. // Bones
  28422. if (mesh.useBones) {
  28423. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  28424. }
  28425. // Draw
  28426. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._volumetricLightScatteringPass.setMatrix("world", world); });
  28427. }
  28428. };
  28429. // Render target texture callbacks
  28430. var savedSceneClearColor;
  28431. var sceneClearColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  28432. this._volumetricLightScatteringRTT.onBeforeRender = function () {
  28433. savedSceneClearColor = scene.clearColor;
  28434. scene.clearColor = sceneClearColor;
  28435. };
  28436. this._volumetricLightScatteringRTT.onAfterRender = function () {
  28437. scene.clearColor = savedSceneClearColor;
  28438. };
  28439. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  28440. var index;
  28441. for (index = 0; index < opaqueSubMeshes.length; index++) {
  28442. renderSubMesh(opaqueSubMeshes.data[index]);
  28443. }
  28444. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  28445. renderSubMesh(alphaTestSubMeshes.data[index]);
  28446. }
  28447. for (index = 0; index < transparentSubMeshes.length; index++) {
  28448. renderSubMesh(transparentSubMeshes.data[index]);
  28449. }
  28450. };
  28451. };
  28452. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  28453. var transform = scene.getTransformMatrix();
  28454. var pos = BABYLON.Vector3.Project(this.useCustomMeshPosition ? this._customMeshPosition : this.mesh.position, BABYLON.Matrix.Identity(), transform, this._viewPort);
  28455. this._screenCoordinates.x = pos.x / this._viewPort.width;
  28456. this._screenCoordinates.y = pos.y / this._viewPort.height;
  28457. if (this.invert)
  28458. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  28459. };
  28460. // Static methods
  28461. /**
  28462. * Creates a default mesh for the Volumeric Light Scattering post-process
  28463. * @param {string} The mesh name
  28464. * @param {BABYLON.Scene} The scene where to create the mesh
  28465. * @return {BABYLON.Mesh} the default mesh
  28466. */
  28467. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  28468. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  28469. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  28470. mesh.material = new BABYLON.StandardMaterial(name + "Material", scene);
  28471. return mesh;
  28472. };
  28473. return VolumetricLightScatteringPostProcess;
  28474. })(BABYLON.PostProcess);
  28475. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  28476. })(BABYLON || (BABYLON = {}));
  28477. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  28478. var BABYLON;
  28479. (function (BABYLON) {
  28480. var LensRenderingPipeline = (function (_super) {
  28481. __extends(LensRenderingPipeline, _super);
  28482. /**
  28483. * @constructor
  28484. * @param {string} name - The rendering pipeline name
  28485. * @param {object} parameters - An object containing all parameters (see below)
  28486. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  28487. * @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)
  28488. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  28489. Effect parameters are as follow:
  28490. {
  28491. chromatic_aberration: number; // from 0 to x (1 for realism)
  28492. edge_blur: number; // from 0 to x (1 for realism)
  28493. distortion: number; // from 0 to x (1 for realism)
  28494. grain_amount: number; // from 0 to 1
  28495. grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  28496. dof_focus_depth: number; // depth-of-field: focus depth; unset to disable
  28497. dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  28498. dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  28499. dof_gain: boolean; // depth-of-field: depthOfField gain (default: 1)
  28500. dof_threshold: boolean; // depth-of-field: depthOfField threshold (default: 1)
  28501. blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  28502. }
  28503. Note: if an effect parameter is unset, effect is disabled
  28504. */
  28505. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  28506. var _this = this;
  28507. if (ratio === void 0) { ratio = 1.0; }
  28508. _super.call(this, scene.getEngine(), name);
  28509. // Lens effects can be of the following:
  28510. // - chromatic aberration (slight shift of RGB colors)
  28511. // - blur on the edge of the lens
  28512. // - lens distortion
  28513. // - depth-of-field 'bokeh' effect (shapes appearing in blured areas, stronger highlights)
  28514. // - grain/dust-on-lens effect
  28515. // Two additional texture samplers are needed:
  28516. // - depth map (for depth-of-field)
  28517. // - grain texture
  28518. /**
  28519. * The chromatic aberration PostProcess id in the pipeline
  28520. * @type {string}
  28521. */
  28522. this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  28523. /**
  28524. * The depth-of-field PostProcess id in the pipeline
  28525. * @type {string}
  28526. */
  28527. this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  28528. this._scene = scene;
  28529. // Fetch texture samplers
  28530. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  28531. if (parameters.grain_texture) {
  28532. this._grainTexture = parameters.grain_texture;
  28533. }
  28534. else {
  28535. this._createGrainTexture();
  28536. }
  28537. // save parameters
  28538. this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  28539. this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  28540. this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  28541. this._distortion = parameters.distortion ? parameters.distortion : 0;
  28542. this._highlightsGain = parameters.dof_gain ? parameters.dof_gain : 1;
  28543. this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  28544. this._dofDepth = parameters.dof_focus_depth !== undefined ? parameters.dof_focus_depth : -1;
  28545. this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  28546. this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  28547. this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  28548. // Create effects
  28549. this._createChromaticAberrationPostProcess(ratio);
  28550. this._createDepthOfFieldPostProcess(ratio);
  28551. // Set up pipeline
  28552. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensChromaticAberrationEffect, function () {
  28553. return _this._chromaticAberrationPostProcess;
  28554. }, true));
  28555. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensDepthOfFieldEffect, function () {
  28556. return _this._depthOfFieldPostProcess;
  28557. }, true));
  28558. // Finish
  28559. scene.postProcessRenderPipelineManager.addPipeline(this);
  28560. if (cameras) {
  28561. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  28562. }
  28563. }
  28564. // public methods
  28565. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) {
  28566. this._edgeBlur = amount;
  28567. };
  28568. LensRenderingPipeline.prototype.disableEdgeBlur = function () {
  28569. this._edgeBlur = 0;
  28570. };
  28571. LensRenderingPipeline.prototype.setGrainAmount = function (amount) {
  28572. this._grainAmount = amount;
  28573. };
  28574. LensRenderingPipeline.prototype.disableGrain = function () {
  28575. this._grainAmount = 0;
  28576. };
  28577. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) {
  28578. this._chromaticAberration = amount;
  28579. };
  28580. LensRenderingPipeline.prototype.disableChromaticAberration = function () {
  28581. this._chromaticAberration = 0;
  28582. };
  28583. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) {
  28584. this._distortion = amount;
  28585. };
  28586. LensRenderingPipeline.prototype.disableEdgeDistortion = function () {
  28587. this._distortion = 0;
  28588. };
  28589. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  28590. this._highlightsGain = amount;
  28591. };
  28592. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  28593. this._highlightsThreshold = amount;
  28594. };
  28595. LensRenderingPipeline.prototype.setFocusDepth = function (amount) {
  28596. this._dofDepth = amount;
  28597. };
  28598. LensRenderingPipeline.prototype.disableDepthOfField = function () {
  28599. this._dofDepth = -1;
  28600. };
  28601. LensRenderingPipeline.prototype.setAperture = function (amount) {
  28602. this._dofAperture = amount;
  28603. };
  28604. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  28605. this._dofPentagon = true;
  28606. };
  28607. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  28608. this._dofPentagon = false;
  28609. };
  28610. LensRenderingPipeline.prototype.enableNoiseBlur = function () {
  28611. this._blurNoise = true;
  28612. };
  28613. LensRenderingPipeline.prototype.disableNoiseBlur = function () {
  28614. this._blurNoise = false;
  28615. };
  28616. /**
  28617. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  28618. */
  28619. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  28620. if (disableDepthRender === void 0) { disableDepthRender = false; }
  28621. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  28622. this._chromaticAberrationPostProcess = undefined;
  28623. this._depthOfFieldPostProcess = undefined;
  28624. this._grainTexture.dispose();
  28625. if (disableDepthRender)
  28626. this._scene.disableDepthRenderer();
  28627. };
  28628. // colors shifting and distortion
  28629. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  28630. var _this = this;
  28631. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], [], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  28632. this._chromaticAberrationPostProcess.onApply = function (effect) {
  28633. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  28634. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  28635. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  28636. };
  28637. };
  28638. // colors shifting and distortion
  28639. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  28640. var _this = this;
  28641. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  28642. "gain",
  28643. "threshold",
  28644. "focus_depth",
  28645. "aperture",
  28646. "pentagon",
  28647. "maxZ",
  28648. "edge_blur",
  28649. "chromatic_aberration",
  28650. "distortion",
  28651. "blur_noise",
  28652. "grain_amount",
  28653. "screen_width",
  28654. "screen_height"
  28655. ], ["depthSampler", "grainSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  28656. this._depthOfFieldPostProcess.onApply = function (effect) {
  28657. effect.setBool('pentagon', _this._dofPentagon);
  28658. effect.setBool('blur_noise', _this._blurNoise);
  28659. effect.setFloat('maxZ', _this._scene.activeCamera.maxZ);
  28660. effect.setFloat('grain_amount', _this._grainAmount);
  28661. effect.setTexture("depthSampler", _this._depthTexture);
  28662. effect.setTexture("grainSampler", _this._grainTexture);
  28663. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  28664. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  28665. effect.setFloat('distortion', _this._distortion);
  28666. effect.setFloat('focus_depth', _this._dofDepth);
  28667. effect.setFloat('aperture', _this._dofAperture);
  28668. effect.setFloat('gain', _this._highlightsGain);
  28669. effect.setFloat('threshold', _this._highlightsThreshold);
  28670. effect.setFloat('edge_blur', _this._edgeBlur);
  28671. };
  28672. };
  28673. // creates a black and white random noise texture, 512x512
  28674. LensRenderingPipeline.prototype._createGrainTexture = function () {
  28675. var size = 512;
  28676. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  28677. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  28678. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  28679. var context = this._grainTexture.getContext();
  28680. var rand = function (min, max) {
  28681. return Math.random() * (max - min) + min;
  28682. };
  28683. var value;
  28684. for (var x = 0; x < size; x++) {
  28685. for (var y = 0; y < size; y++) {
  28686. value = Math.floor(rand(0.42, 0.58) * 255);
  28687. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  28688. context.fillRect(x, y, 1, 1);
  28689. }
  28690. }
  28691. this._grainTexture.update(false);
  28692. };
  28693. return LensRenderingPipeline;
  28694. })(BABYLON.PostProcessRenderPipeline);
  28695. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  28696. })(BABYLON || (BABYLON = {}));
  28697. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map