babylon.2.0-alpha.debug.js 1.2 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723
  1. var __extends = this.__extends || function (d, b) {
  2. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  3. function __() { this.constructor = d; }
  4. __.prototype = b.prototype;
  5. d.prototype = new __();
  6. };var BABYLON;
  7. (function (BABYLON) {
  8. var Color3 = (function () {
  9. function Color3(r, g, b) {
  10. if (typeof r === "undefined") { r = 0; }
  11. if (typeof g === "undefined") { g = 0; }
  12. if (typeof b === "undefined") { b = 0; }
  13. this.r = r;
  14. this.g = g;
  15. this.b = b;
  16. }
  17. Color3.prototype.toString = function () {
  18. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  19. };
  20. // Operators
  21. Color3.prototype.toArray = function (array, index) {
  22. if (index === undefined) {
  23. index = 0;
  24. }
  25. array[index] = this.r;
  26. array[index + 1] = this.g;
  27. array[index + 2] = this.b;
  28. };
  29. Color3.prototype.toColor4 = function (alpha) {
  30. if (typeof alpha === "undefined") { alpha = 1; }
  31. return new Color4(this.r, this.g, this.b, alpha);
  32. };
  33. Color3.prototype.asArray = function () {
  34. var result = [];
  35. this.toArray(result, 0);
  36. return result;
  37. };
  38. Color3.prototype.toLuminance = function () {
  39. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  40. };
  41. Color3.prototype.multiply = function (otherColor) {
  42. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  43. };
  44. Color3.prototype.multiplyToRef = function (otherColor, result) {
  45. result.r = this.r * otherColor.r;
  46. result.g = this.g * otherColor.g;
  47. result.b = this.b * otherColor.b;
  48. };
  49. Color3.prototype.equals = function (otherColor) {
  50. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  51. };
  52. Color3.prototype.scale = function (scale) {
  53. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  54. };
  55. Color3.prototype.scaleToRef = function (scale, result) {
  56. result.r = this.r * scale;
  57. result.g = this.g * scale;
  58. result.b = this.b * scale;
  59. };
  60. Color3.prototype.add = function (otherColor) {
  61. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  62. };
  63. Color3.prototype.addToRef = function (otherColor, result) {
  64. result.r = this.r + otherColor.r;
  65. result.g = this.g + otherColor.g;
  66. result.b = this.b + otherColor.b;
  67. };
  68. Color3.prototype.subtract = function (otherColor) {
  69. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  70. };
  71. Color3.prototype.subtractToRef = function (otherColor, result) {
  72. result.r = this.r - otherColor.r;
  73. result.g = this.g - otherColor.g;
  74. result.b = this.b - otherColor.b;
  75. };
  76. Color3.prototype.clone = function () {
  77. return new Color3(this.r, this.g, this.b);
  78. };
  79. Color3.prototype.copyFrom = function (source) {
  80. this.r = source.r;
  81. this.g = source.g;
  82. this.b = source.b;
  83. };
  84. Color3.prototype.copyFromFloats = function (r, g, b) {
  85. this.r = r;
  86. this.g = g;
  87. this.b = b;
  88. };
  89. // Statics
  90. Color3.FromArray = function (array) {
  91. return new Color3(array[0], array[1], array[2]);
  92. };
  93. Color3.FromInts = function (r, g, b) {
  94. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  95. };
  96. Color3.Lerp = function (start, end, amount) {
  97. var r = start.r + ((end.r - start.r) * amount);
  98. var g = start.g + ((end.g - start.g) * amount);
  99. var b = start.b + ((end.b - start.b) * amount);
  100. return new Color3(r, g, b);
  101. };
  102. Color3.Red = function () {
  103. return new Color3(1, 0, 0);
  104. };
  105. Color3.Green = function () {
  106. return new Color3(0, 1, 0);
  107. };
  108. Color3.Blue = function () {
  109. return new Color3(0, 0, 1);
  110. };
  111. Color3.Black = function () {
  112. return new Color3(0, 0, 0);
  113. };
  114. Color3.White = function () {
  115. return new Color3(1, 1, 1);
  116. };
  117. Color3.Purple = function () {
  118. return new Color3(0.5, 0, 0.5);
  119. };
  120. Color3.Magenta = function () {
  121. return new Color3(1, 0, 1);
  122. };
  123. Color3.Yellow = function () {
  124. return new Color3(1, 1, 0);
  125. };
  126. Color3.Gray = function () {
  127. return new Color3(0.5, 0.5, 0.5);
  128. };
  129. return Color3;
  130. })();
  131. BABYLON.Color3 = Color3;
  132. var Color4 = (function () {
  133. function Color4(r, g, b, a) {
  134. this.r = r;
  135. this.g = g;
  136. this.b = b;
  137. this.a = a;
  138. }
  139. // Operators
  140. Color4.prototype.addInPlace = function (right) {
  141. this.r += right.r;
  142. this.g += right.g;
  143. this.b += right.b;
  144. this.a += right.a;
  145. };
  146. Color4.prototype.asArray = function () {
  147. var result = [];
  148. this.toArray(result, 0);
  149. return result;
  150. };
  151. Color4.prototype.toArray = function (array, index) {
  152. if (index === undefined) {
  153. index = 0;
  154. }
  155. array[index] = this.r;
  156. array[index + 1] = this.g;
  157. array[index + 2] = this.b;
  158. array[index + 3] = this.a;
  159. };
  160. Color4.prototype.add = function (right) {
  161. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  162. };
  163. Color4.prototype.subtract = function (right) {
  164. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  165. };
  166. Color4.prototype.subtractToRef = function (right, result) {
  167. result.r = this.r - right.r;
  168. result.g = this.g - right.g;
  169. result.b = this.b - right.b;
  170. result.a = this.a - right.a;
  171. };
  172. Color4.prototype.scale = function (scale) {
  173. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  174. };
  175. Color4.prototype.scaleToRef = function (scale, result) {
  176. result.r = this.r * scale;
  177. result.g = this.g * scale;
  178. result.b = this.b * scale;
  179. result.a = this.a * scale;
  180. };
  181. Color4.prototype.toString = function () {
  182. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  183. };
  184. Color4.prototype.clone = function () {
  185. return new Color4(this.r, this.g, this.b, this.a);
  186. };
  187. // Statics
  188. Color4.Lerp = function (left, right, amount) {
  189. var result = new Color4(0, 0, 0, 0);
  190. Color4.LerpToRef(left, right, amount, result);
  191. return result;
  192. };
  193. Color4.LerpToRef = function (left, right, amount, result) {
  194. result.r = left.r + (right.r - left.r) * amount;
  195. result.g = left.g + (right.g - left.g) * amount;
  196. result.b = left.b + (right.b - left.b) * amount;
  197. result.a = left.a + (right.a - left.a) * amount;
  198. };
  199. Color4.FromArray = function (array, offset) {
  200. if (typeof offset === "undefined") { offset = 0; }
  201. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  202. };
  203. Color4.FromInts = function (r, g, b, a) {
  204. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  205. };
  206. return Color4;
  207. })();
  208. BABYLON.Color4 = Color4;
  209. var Vector2 = (function () {
  210. function Vector2(x, y) {
  211. this.x = x;
  212. this.y = y;
  213. }
  214. Vector2.prototype.toString = function () {
  215. return "{X: " + this.x + " Y:" + this.y + "}";
  216. };
  217. // Operators
  218. Vector2.prototype.toArray = function (array, index) {
  219. if (index === undefined) {
  220. index = 0;
  221. }
  222. array[index] = this.x;
  223. array[index + 1] = this.y;
  224. };
  225. Vector2.prototype.asArray = function () {
  226. var result = [];
  227. this.toArray(result, 0);
  228. return result;
  229. };
  230. Vector2.prototype.copyFrom = function (source) {
  231. this.x = source.x;
  232. this.y = source.y;
  233. };
  234. Vector2.prototype.copyFromFloats = function (x, y) {
  235. this.x = x;
  236. this.y = y;
  237. };
  238. Vector2.prototype.add = function (otherVector) {
  239. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  240. };
  241. Vector2.prototype.addVector3 = function (otherVector) {
  242. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  243. };
  244. Vector2.prototype.subtract = function (otherVector) {
  245. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  246. };
  247. Vector2.prototype.subtractInPlace = function (otherVector) {
  248. this.x -= otherVector.x;
  249. this.y -= otherVector.y;
  250. };
  251. Vector2.prototype.multiplyInPlace = function (otherVector) {
  252. this.x *= otherVector.x;
  253. this.y *= otherVector.y;
  254. };
  255. Vector2.prototype.multiply = function (otherVector) {
  256. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  257. };
  258. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  259. result.x = this.x * otherVector.x;
  260. result.y = this.y * otherVector.y;
  261. };
  262. Vector2.prototype.multiplyByFloats = function (x, y) {
  263. return new Vector2(this.x * x, this.y * y);
  264. };
  265. Vector2.prototype.divide = function (otherVector) {
  266. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  267. };
  268. Vector2.prototype.divideToRef = function (otherVector, result) {
  269. result.x = this.x / otherVector.x;
  270. result.y = this.y / otherVector.y;
  271. };
  272. Vector2.prototype.negate = function () {
  273. return new Vector2(-this.x, -this.y);
  274. };
  275. Vector2.prototype.scaleInPlace = function (scale) {
  276. this.x *= scale;
  277. this.y *= scale;
  278. return this;
  279. };
  280. Vector2.prototype.scale = function (scale) {
  281. return new Vector2(this.x * scale, this.y * scale);
  282. };
  283. Vector2.prototype.equals = function (otherVector) {
  284. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  285. };
  286. // Properties
  287. Vector2.prototype.length = function () {
  288. return Math.sqrt(this.x * this.x + this.y * this.y);
  289. };
  290. Vector2.prototype.lengthSquared = function () {
  291. return (this.x * this.x + this.y * this.y);
  292. };
  293. // Methods
  294. Vector2.prototype.normalize = function () {
  295. var len = this.length();
  296. if (len === 0)
  297. return this;
  298. var num = 1.0 / len;
  299. this.x *= num;
  300. this.y *= num;
  301. return this;
  302. };
  303. Vector2.prototype.clone = function () {
  304. return new Vector2(this.x, this.y);
  305. };
  306. // Statics
  307. Vector2.Zero = function () {
  308. return new Vector2(0, 0);
  309. };
  310. Vector2.FromArray = function (array, offset) {
  311. if (!offset) {
  312. offset = 0;
  313. }
  314. return new Vector2(array[offset], array[offset + 1]);
  315. };
  316. Vector2.FromArrayToRef = function (array, offset, result) {
  317. result.x = array[offset];
  318. result.y = array[offset + 1];
  319. };
  320. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  321. var squared = amount * amount;
  322. var cubed = amount * squared;
  323. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) + (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) + ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  324. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) + (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) + ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  325. return new Vector2(x, y);
  326. };
  327. Vector2.Clamp = function (value, min, max) {
  328. var x = value.x;
  329. x = (x > max.x) ? max.x : x;
  330. x = (x < min.x) ? min.x : x;
  331. var y = value.y;
  332. y = (y > max.y) ? max.y : y;
  333. y = (y < min.y) ? min.y : y;
  334. return new Vector2(x, y);
  335. };
  336. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  337. var squared = amount * amount;
  338. var cubed = amount * squared;
  339. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  340. var part2 = (-2.0 * cubed) + (3.0 * squared);
  341. var part3 = (cubed - (2.0 * squared)) + amount;
  342. var part4 = cubed - squared;
  343. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  344. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  345. return new Vector2(x, y);
  346. };
  347. Vector2.Lerp = function (start, end, amount) {
  348. var x = start.x + ((end.x - start.x) * amount);
  349. var y = start.y + ((end.y - start.y) * amount);
  350. return new Vector2(x, y);
  351. };
  352. Vector2.Dot = function (left, right) {
  353. return left.x * right.x + left.y * right.y;
  354. };
  355. Vector2.Normalize = function (vector) {
  356. var newVector = vector.clone();
  357. newVector.normalize();
  358. return newVector;
  359. };
  360. Vector2.Minimize = function (left, right) {
  361. var x = (left.x < right.x) ? left.x : right.x;
  362. var y = (left.y < right.y) ? left.y : right.y;
  363. return new Vector2(x, y);
  364. };
  365. Vector2.Maximize = function (left, right) {
  366. var x = (left.x > right.x) ? left.x : right.x;
  367. var y = (left.y > right.y) ? left.y : right.y;
  368. return new Vector2(x, y);
  369. };
  370. Vector2.Transform = function (vector, transformation) {
  371. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]);
  372. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]);
  373. return new Vector2(x, y);
  374. };
  375. Vector2.Distance = function (value1, value2) {
  376. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  377. };
  378. Vector2.DistanceSquared = function (value1, value2) {
  379. var x = value1.x - value2.x;
  380. var y = value1.y - value2.y;
  381. return (x * x) + (y * y);
  382. };
  383. return Vector2;
  384. })();
  385. BABYLON.Vector2 = Vector2;
  386. var Vector3 = (function () {
  387. function Vector3(x, y, z) {
  388. this.x = x;
  389. this.y = y;
  390. this.z = z;
  391. }
  392. Vector3.prototype.toString = function () {
  393. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  394. };
  395. // Operators
  396. Vector3.prototype.asArray = function () {
  397. var result = [];
  398. this.toArray(result, 0);
  399. return result;
  400. };
  401. Vector3.prototype.toArray = function (array, index) {
  402. if (index === undefined) {
  403. index = 0;
  404. }
  405. array[index] = this.x;
  406. array[index + 1] = this.y;
  407. array[index + 2] = this.z;
  408. };
  409. Vector3.prototype.addInPlace = function (otherVector) {
  410. this.x += otherVector.x;
  411. this.y += otherVector.y;
  412. this.z += otherVector.z;
  413. };
  414. Vector3.prototype.add = function (otherVector) {
  415. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  416. };
  417. Vector3.prototype.addToRef = function (otherVector, result) {
  418. result.x = this.x + otherVector.x;
  419. result.y = this.y + otherVector.y;
  420. result.z = this.z + otherVector.z;
  421. };
  422. Vector3.prototype.subtractInPlace = function (otherVector) {
  423. this.x -= otherVector.x;
  424. this.y -= otherVector.y;
  425. this.z -= otherVector.z;
  426. };
  427. Vector3.prototype.subtract = function (otherVector) {
  428. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  429. };
  430. Vector3.prototype.subtractToRef = function (otherVector, result) {
  431. result.x = this.x - otherVector.x;
  432. result.y = this.y - otherVector.y;
  433. result.z = this.z - otherVector.z;
  434. };
  435. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  436. return new Vector3(this.x - x, this.y - y, this.z - z);
  437. };
  438. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  439. result.x = this.x - x;
  440. result.y = this.y - y;
  441. result.z = this.z - z;
  442. };
  443. Vector3.prototype.negate = function () {
  444. return new Vector3(-this.x, -this.y, -this.z);
  445. };
  446. Vector3.prototype.scaleInPlace = function (scale) {
  447. this.x *= scale;
  448. this.y *= scale;
  449. this.z *= scale;
  450. return this;
  451. };
  452. Vector3.prototype.scale = function (scale) {
  453. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  454. };
  455. Vector3.prototype.scaleToRef = function (scale, result) {
  456. result.x = this.x * scale;
  457. result.y = this.y * scale;
  458. result.z = this.z * scale;
  459. };
  460. Vector3.prototype.equals = function (otherVector) {
  461. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  462. };
  463. Vector3.prototype.equalsWithEpsilon = function (otherVector) {
  464. return Math.abs(this.x - otherVector.x) < BABYLON.Engine.Epsilon && Math.abs(this.y - otherVector.y) < BABYLON.Engine.Epsilon && Math.abs(this.z - otherVector.z) < BABYLON.Engine.Epsilon;
  465. };
  466. Vector3.prototype.equalsToFloats = function (x, y, z) {
  467. return this.x === x && this.y === y && this.z === z;
  468. };
  469. Vector3.prototype.multiplyInPlace = function (otherVector) {
  470. this.x *= otherVector.x;
  471. this.y *= otherVector.y;
  472. this.z *= otherVector.z;
  473. };
  474. Vector3.prototype.multiply = function (otherVector) {
  475. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  476. };
  477. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  478. result.x = this.x * otherVector.x;
  479. result.y = this.y * otherVector.y;
  480. result.z = this.z * otherVector.z;
  481. };
  482. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  483. return new Vector3(this.x * x, this.y * y, this.z * z);
  484. };
  485. Vector3.prototype.divide = function (otherVector) {
  486. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  487. };
  488. Vector3.prototype.divideToRef = function (otherVector, result) {
  489. result.x = this.x / otherVector.x;
  490. result.y = this.y / otherVector.y;
  491. result.z = this.z / otherVector.z;
  492. };
  493. Vector3.prototype.MinimizeInPlace = function (other) {
  494. if (other.x < this.x)
  495. this.x = other.x;
  496. if (other.y < this.y)
  497. this.y = other.y;
  498. if (other.z < this.z)
  499. this.z = other.z;
  500. };
  501. Vector3.prototype.MaximizeInPlace = function (other) {
  502. if (other.x > this.x)
  503. this.x = other.x;
  504. if (other.y > this.y)
  505. this.y = other.y;
  506. if (other.z > this.z)
  507. this.z = other.z;
  508. };
  509. // Properties
  510. Vector3.prototype.length = function () {
  511. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  512. };
  513. Vector3.prototype.lengthSquared = function () {
  514. return (this.x * this.x + this.y * this.y + this.z * this.z);
  515. };
  516. // Methods
  517. Vector3.prototype.normalize = function () {
  518. var len = this.length();
  519. if (len === 0)
  520. return this;
  521. var num = 1.0 / len;
  522. this.x *= num;
  523. this.y *= num;
  524. this.z *= num;
  525. return this;
  526. };
  527. Vector3.prototype.clone = function () {
  528. return new Vector3(this.x, this.y, this.z);
  529. };
  530. Vector3.prototype.copyFrom = function (source) {
  531. this.x = source.x;
  532. this.y = source.y;
  533. this.z = source.z;
  534. };
  535. Vector3.prototype.copyFromFloats = function (x, y, z) {
  536. this.x = x;
  537. this.y = y;
  538. this.z = z;
  539. };
  540. // Statics
  541. Vector3.FromArray = function (array, offset) {
  542. if (!offset) {
  543. offset = 0;
  544. }
  545. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  546. };
  547. Vector3.FromArrayToRef = function (array, offset, result) {
  548. result.x = array[offset];
  549. result.y = array[offset + 1];
  550. result.z = array[offset + 2];
  551. };
  552. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  553. result.x = array[offset];
  554. result.y = array[offset + 1];
  555. result.z = array[offset + 2];
  556. };
  557. Vector3.FromFloatsToRef = function (x, y, z, result) {
  558. result.x = x;
  559. result.y = y;
  560. result.z = z;
  561. };
  562. Vector3.Zero = function () {
  563. return new Vector3(0, 0, 0);
  564. };
  565. Vector3.Up = function () {
  566. return new Vector3(0, 1.0, 0);
  567. };
  568. Vector3.TransformCoordinates = function (vector, transformation) {
  569. var result = Vector3.Zero();
  570. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  571. return result;
  572. };
  573. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  574. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  575. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  576. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  577. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  578. result.x = x / w;
  579. result.y = y / w;
  580. result.z = z / w;
  581. };
  582. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  583. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  584. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  585. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  586. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  587. result.x = rx / rw;
  588. result.y = ry / rw;
  589. result.z = rz / rw;
  590. };
  591. Vector3.TransformNormal = function (vector, transformation) {
  592. var result = Vector3.Zero();
  593. Vector3.TransformNormalToRef(vector, transformation, result);
  594. return result;
  595. };
  596. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  597. result.x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  598. result.y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  599. result.z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  600. };
  601. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  602. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  603. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  604. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  605. };
  606. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  607. var squared = amount * amount;
  608. var cubed = amount * squared;
  609. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) + (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) + ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  610. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) + (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) + ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  611. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) + (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) + ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  612. return new Vector3(x, y, z);
  613. };
  614. Vector3.Clamp = function (value, min, max) {
  615. var x = value.x;
  616. x = (x > max.x) ? max.x : x;
  617. x = (x < min.x) ? min.x : x;
  618. var y = value.y;
  619. y = (y > max.y) ? max.y : y;
  620. y = (y < min.y) ? min.y : y;
  621. var z = value.z;
  622. z = (z > max.z) ? max.z : z;
  623. z = (z < min.z) ? min.z : z;
  624. return new Vector3(x, y, z);
  625. };
  626. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  627. var squared = amount * amount;
  628. var cubed = amount * squared;
  629. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  630. var part2 = (-2.0 * cubed) + (3.0 * squared);
  631. var part3 = (cubed - (2.0 * squared)) + amount;
  632. var part4 = cubed - squared;
  633. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  634. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  635. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  636. return new Vector3(x, y, z);
  637. };
  638. Vector3.Lerp = function (start, end, amount) {
  639. var x = start.x + ((end.x - start.x) * amount);
  640. var y = start.y + ((end.y - start.y) * amount);
  641. var z = start.z + ((end.z - start.z) * amount);
  642. return new Vector3(x, y, z);
  643. };
  644. Vector3.Dot = function (left, right) {
  645. return (left.x * right.x + left.y * right.y + left.z * right.z);
  646. };
  647. Vector3.Cross = function (left, right) {
  648. var result = Vector3.Zero();
  649. Vector3.CrossToRef(left, right, result);
  650. return result;
  651. };
  652. Vector3.CrossToRef = function (left, right, result) {
  653. result.x = left.y * right.z - left.z * right.y;
  654. result.y = left.z * right.x - left.x * right.z;
  655. result.z = left.x * right.y - left.y * right.x;
  656. };
  657. Vector3.Normalize = function (vector) {
  658. var result = Vector3.Zero();
  659. Vector3.NormalizeToRef(vector, result);
  660. return result;
  661. };
  662. Vector3.NormalizeToRef = function (vector, result) {
  663. result.copyFrom(vector);
  664. result.normalize();
  665. };
  666. Vector3.Project = function (vector, world, transform, viewport) {
  667. var cw = viewport.width;
  668. var ch = viewport.height;
  669. var cx = viewport.x;
  670. var cy = viewport.y;
  671. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, 1, 0, cx + cw / 2.0, ch / 2.0 + cy, 0, 1);
  672. var finalMatrix = world.multiply(transform).multiply(viewportMatrix);
  673. return Vector3.TransformCoordinates(vector, finalMatrix);
  674. };
  675. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  676. var matrix = world.multiply(transform);
  677. matrix.invert();
  678. source.x = source.x / viewportWidth * 2 - 1;
  679. source.y = -(source.y / viewportHeight * 2 - 1);
  680. var vector = Vector3.TransformCoordinates(source, matrix);
  681. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  682. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  683. vector = vector.scale(1.0 / num);
  684. }
  685. return vector;
  686. };
  687. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  688. var matrix = world.multiply(view).multiply(projection);
  689. matrix.invert();
  690. source.x = source.x / viewportWidth * 2 - 1;
  691. source.y = -(source.y / viewportHeight * 2 - 1);
  692. var vector = Vector3.TransformCoordinates(source, matrix);
  693. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  694. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  695. vector = vector.scale(1.0 / num);
  696. }
  697. return vector;
  698. };
  699. Vector3.Minimize = function (left, right) {
  700. var min = left.clone();
  701. min.MinimizeInPlace(right);
  702. return min;
  703. };
  704. Vector3.Maximize = function (left, right) {
  705. var max = left.clone();
  706. max.MaximizeInPlace(right);
  707. return max;
  708. };
  709. Vector3.Distance = function (value1, value2) {
  710. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  711. };
  712. Vector3.DistanceSquared = function (value1, value2) {
  713. var x = value1.x - value2.x;
  714. var y = value1.y - value2.y;
  715. var z = value1.z - value2.z;
  716. return (x * x) + (y * y) + (z * z);
  717. };
  718. Vector3.Center = function (value1, value2) {
  719. var center = value1.add(value2);
  720. center.scaleInPlace(0.5);
  721. return center;
  722. };
  723. return Vector3;
  724. })();
  725. BABYLON.Vector3 = Vector3;
  726. //Vector4 class created for EulerAngle class conversion to Quaternion
  727. var Vector4 = (function () {
  728. function Vector4(x, y, z, w) {
  729. this.x = x;
  730. this.y = y;
  731. this.z = z;
  732. this.w = w;
  733. }
  734. Vector4.prototype.toString = function () {
  735. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "W:" + this.w + "}";
  736. };
  737. // Operators
  738. Vector4.prototype.asArray = function () {
  739. var result = [];
  740. this.toArray(result, 0);
  741. return result;
  742. };
  743. Vector4.prototype.toArray = function (array, index) {
  744. if (index === undefined) {
  745. index = 0;
  746. }
  747. array[index] = this.x;
  748. array[index + 1] = this.y;
  749. array[index + 2] = this.z;
  750. array[index + 3] = this.w;
  751. };
  752. Vector4.prototype.addInPlace = function (otherVector) {
  753. this.x += otherVector.x;
  754. this.y += otherVector.y;
  755. this.z += otherVector.z;
  756. this.w += otherVector.w;
  757. };
  758. Vector4.prototype.add = function (otherVector) {
  759. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  760. };
  761. Vector4.prototype.addToRef = function (otherVector, result) {
  762. result.x = this.x + otherVector.x;
  763. result.y = this.y + otherVector.y;
  764. result.z = this.z + otherVector.z;
  765. result.w = this.w + otherVector.w;
  766. };
  767. Vector4.prototype.subtractInPlace = function (otherVector) {
  768. this.x -= otherVector.x;
  769. this.y -= otherVector.y;
  770. this.z -= otherVector.z;
  771. this.w -= otherVector.w;
  772. };
  773. Vector4.prototype.subtract = function (otherVector) {
  774. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  775. };
  776. Vector4.prototype.subtractToRef = function (otherVector, result) {
  777. result.x = this.x - otherVector.x;
  778. result.y = this.y - otherVector.y;
  779. result.z = this.z - otherVector.z;
  780. result.w = this.w - otherVector.w;
  781. };
  782. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  783. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  784. };
  785. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  786. result.x = this.x - x;
  787. result.y = this.y - y;
  788. result.z = this.z - z;
  789. result.w = this.w - w;
  790. };
  791. Vector4.prototype.negate = function () {
  792. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  793. };
  794. Vector4.prototype.scaleInPlace = function (scale) {
  795. this.x *= scale;
  796. this.y *= scale;
  797. this.z *= scale;
  798. this.w *= scale;
  799. return this;
  800. };
  801. Vector4.prototype.scale = function (scale) {
  802. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  803. };
  804. Vector4.prototype.scaleToRef = function (scale, result) {
  805. result.x = this.x * scale;
  806. result.y = this.y * scale;
  807. result.z = this.z * scale;
  808. result.w = this.w * scale;
  809. };
  810. Vector4.prototype.equals = function (otherVector) {
  811. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  812. };
  813. Vector4.prototype.equalsWithEpsilon = function (otherVector) {
  814. return Math.abs(this.x - otherVector.x) < BABYLON.Engine.Epsilon && Math.abs(this.y - otherVector.y) < BABYLON.Engine.Epsilon && Math.abs(this.z - otherVector.z) < BABYLON.Engine.Epsilon && Math.abs(this.w - otherVector.w) < BABYLON.Engine.Epsilon;
  815. };
  816. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  817. return this.x === x && this.y === y && this.z === z && this.w === w;
  818. };
  819. Vector4.prototype.multiplyInPlace = function (otherVector) {
  820. this.x *= otherVector.x;
  821. this.y *= otherVector.y;
  822. this.z *= otherVector.z;
  823. this.w *= otherVector.w;
  824. };
  825. Vector4.prototype.multiply = function (otherVector) {
  826. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  827. };
  828. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  829. result.x = this.x * otherVector.x;
  830. result.y = this.y * otherVector.y;
  831. result.z = this.z * otherVector.z;
  832. result.w = this.w * otherVector.w;
  833. };
  834. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  835. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  836. };
  837. Vector4.prototype.divide = function (otherVector) {
  838. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  839. };
  840. Vector4.prototype.divideToRef = function (otherVector, result) {
  841. result.x = this.x / otherVector.x;
  842. result.y = this.y / otherVector.y;
  843. result.z = this.z / otherVector.z;
  844. result.w = this.w / otherVector.w;
  845. };
  846. Vector4.prototype.MinimizeInPlace = function (other) {
  847. if (other.x < this.x)
  848. this.x = other.x;
  849. if (other.y < this.y)
  850. this.y = other.y;
  851. if (other.z < this.z)
  852. this.z = other.z;
  853. if (other.w < this.w)
  854. this.w = other.w;
  855. };
  856. Vector4.prototype.MaximizeInPlace = function (other) {
  857. if (other.x > this.x)
  858. this.x = other.x;
  859. if (other.y > this.y)
  860. this.y = other.y;
  861. if (other.z > this.z)
  862. this.z = other.z;
  863. if (other.w > this.w)
  864. this.w = other.w;
  865. };
  866. // Properties
  867. Vector4.prototype.length = function () {
  868. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  869. };
  870. Vector4.prototype.lengthSquared = function () {
  871. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  872. };
  873. // Methods
  874. Vector4.prototype.normalize = function () {
  875. var len = this.length();
  876. if (len === 0)
  877. return this;
  878. var num = 1.0 / len;
  879. this.x *= num;
  880. this.y *= num;
  881. this.z *= num;
  882. this.w *= num;
  883. return this;
  884. };
  885. Vector4.prototype.clone = function () {
  886. return new Vector4(this.x, this.y, this.z, this.w);
  887. };
  888. Vector4.prototype.copyFrom = function (source) {
  889. this.x = source.x;
  890. this.y = source.y;
  891. this.z = source.z;
  892. this.w = source.w;
  893. };
  894. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  895. this.x = x;
  896. this.y = y;
  897. this.z = z;
  898. this.w = w;
  899. };
  900. // Statics
  901. Vector4.FromArray = function (array, offset) {
  902. if (!offset) {
  903. offset = 0;
  904. }
  905. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  906. };
  907. Vector4.FromArrayToRef = function (array, offset, result) {
  908. result.x = array[offset];
  909. result.y = array[offset + 1];
  910. result.z = array[offset + 2];
  911. result.w = array[offset + 3];
  912. };
  913. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  914. result.x = array[offset];
  915. result.y = array[offset + 1];
  916. result.z = array[offset + 2];
  917. result.w = array[offset + 3];
  918. };
  919. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  920. result.x = x;
  921. result.y = y;
  922. result.z = z;
  923. result.w = w;
  924. };
  925. Vector4.Zero = function () {
  926. return new Vector4(0, 0, 0, 0);
  927. };
  928. Vector4.Normalize = function (vector) {
  929. var result = Vector4.Zero();
  930. Vector4.NormalizeToRef(vector, result);
  931. return result;
  932. };
  933. Vector4.NormalizeToRef = function (vector, result) {
  934. result.copyFrom(vector);
  935. result.normalize();
  936. };
  937. Vector4.Minimize = function (left, right) {
  938. var min = left.clone();
  939. min.MinimizeInPlace(right);
  940. return min;
  941. };
  942. Vector4.Maximize = function (left, right) {
  943. var max = left.clone();
  944. max.MaximizeInPlace(right);
  945. return max;
  946. };
  947. Vector4.Distance = function (value1, value2) {
  948. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  949. };
  950. Vector4.DistanceSquared = function (value1, value2) {
  951. var x = value1.x - value2.x;
  952. var y = value1.y - value2.y;
  953. var z = value1.z - value2.z;
  954. var w = value1.w - value2.w;
  955. return (x * x) + (y * y) + (z * z) + (w * w);
  956. };
  957. Vector4.Center = function (value1, value2) {
  958. var center = value1.add(value2);
  959. center.scaleInPlace(0.5);
  960. return center;
  961. };
  962. return Vector4;
  963. })();
  964. BABYLON.Vector4 = Vector4;
  965. var Quaternion = (function () {
  966. function Quaternion(x, y, z, w) {
  967. if (typeof x === "undefined") { x = 0; }
  968. if (typeof y === "undefined") { y = 0; }
  969. if (typeof z === "undefined") { z = 0; }
  970. if (typeof w === "undefined") { w = 1; }
  971. this.x = x;
  972. this.y = y;
  973. this.z = z;
  974. this.w = w;
  975. }
  976. Quaternion.prototype.toString = function () {
  977. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  978. };
  979. Quaternion.prototype.asArray = function () {
  980. return [this.x, this.y, this.z, this.w];
  981. };
  982. Quaternion.prototype.equals = function (otherQuaternion) {
  983. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  984. };
  985. Quaternion.prototype.clone = function () {
  986. return new Quaternion(this.x, this.y, this.z, this.w);
  987. };
  988. Quaternion.prototype.copyFrom = function (other) {
  989. this.x = other.x;
  990. this.y = other.y;
  991. this.z = other.z;
  992. this.w = other.w;
  993. };
  994. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  995. this.x = x;
  996. this.y = y;
  997. this.z = z;
  998. this.w = w;
  999. };
  1000. Quaternion.prototype.add = function (other) {
  1001. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  1002. };
  1003. Quaternion.prototype.subtract = function (other) {
  1004. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  1005. };
  1006. Quaternion.prototype.scale = function (value) {
  1007. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  1008. };
  1009. Quaternion.prototype.multiply = function (q1) {
  1010. var result = new Quaternion(0, 0, 0, 1.0);
  1011. this.multiplyToRef(q1, result);
  1012. return result;
  1013. };
  1014. Quaternion.prototype.multiplyToRef = function (q1, result) {
  1015. result.x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  1016. result.y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  1017. result.z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  1018. result.w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  1019. };
  1020. Quaternion.prototype.length = function () {
  1021. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  1022. };
  1023. Quaternion.prototype.normalize = function () {
  1024. var length = 1.0 / this.length();
  1025. this.x *= length;
  1026. this.y *= length;
  1027. this.z *= length;
  1028. this.w *= length;
  1029. };
  1030. Quaternion.prototype.toEulerAngles = function () {
  1031. var result = Vector3.Zero();
  1032. this.toEulerAnglesToRef(result);
  1033. return result;
  1034. };
  1035. Quaternion.prototype.toEulerAnglesToRef = function (result) {
  1036. //result is an EulerAngles in the in the z-x-z convention
  1037. var qx = this.x;
  1038. var qy = this.y;
  1039. var qz = this.z;
  1040. var qw = this.w;
  1041. var qxy = qx * qy;
  1042. var qxz = qx * qz;
  1043. var qwy = qw * qy;
  1044. var qwz = qw * qz;
  1045. var qwx = qw * qx;
  1046. var qyz = qy * qz;
  1047. var sqx = qx * qx;
  1048. var sqy = qy * qy;
  1049. var determinant = sqx + sqy;
  1050. if (determinant !== 0.000 && determinant !== 1.000) {
  1051. result.x = Math.atan2(qxz + qwy, qwx - qyz);
  1052. result.y = Math.acos(1 - 2 * determinant);
  1053. result.z = Math.atan2(qxz - qwy, qwx + qyz);
  1054. } else {
  1055. if (determinant === 0.0) {
  1056. result.x = 0.0;
  1057. result.y = 0.0;
  1058. result.z = Math.atan2(qxy - qwz, 0.5 - sqy - qz * qz); //actually, degeneracy gives us choice with x+z=Math.atan2(qxy-qwz,0.5-sqy-qz*qz)
  1059. } else {
  1060. result.x = Math.atan2(qxy - qwz, 0.5 - sqy - qz * qz); //actually, degeneracy gives us choice with x-z=Math.atan2(qxy-qwz,0.5-sqy-qz*qz)
  1061. result.y = Math.PI;
  1062. result.z = 0.0;
  1063. }
  1064. }
  1065. };
  1066. Quaternion.prototype.toRotationMatrix = function (result) {
  1067. var xx = this.x * this.x;
  1068. var yy = this.y * this.y;
  1069. var zz = this.z * this.z;
  1070. var xy = this.x * this.y;
  1071. var zw = this.z * this.w;
  1072. var zx = this.z * this.x;
  1073. var yw = this.y * this.w;
  1074. var yz = this.y * this.z;
  1075. var xw = this.x * this.w;
  1076. result.m[0] = 1.0 - (2.0 * (yy + zz));
  1077. result.m[1] = 2.0 * (xy + zw);
  1078. result.m[2] = 2.0 * (zx - yw);
  1079. result.m[3] = 0;
  1080. result.m[4] = 2.0 * (xy - zw);
  1081. result.m[5] = 1.0 - (2.0 * (zz + xx));
  1082. result.m[6] = 2.0 * (yz + xw);
  1083. result.m[7] = 0;
  1084. result.m[8] = 2.0 * (zx + yw);
  1085. result.m[9] = 2.0 * (yz - xw);
  1086. result.m[10] = 1.0 - (2.0 * (yy + xx));
  1087. result.m[11] = 0;
  1088. result.m[12] = 0;
  1089. result.m[13] = 0;
  1090. result.m[14] = 0;
  1091. result.m[15] = 1.0;
  1092. };
  1093. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  1094. var data = matrix.m;
  1095. var m11 = data[0], m12 = data[4], m13 = data[8];
  1096. var m21 = data[1], m22 = data[5], m23 = data[9];
  1097. var m31 = data[2], m32 = data[6], m33 = data[10];
  1098. var trace = m11 + m22 + m33;
  1099. var s;
  1100. if (trace > 0) {
  1101. s = 0.5 / Math.sqrt(trace + 1.0);
  1102. this.w = 0.25 / s;
  1103. this.x = (m32 - m23) * s;
  1104. this.y = (m13 - m31) * s;
  1105. this.z = (m21 - m12) * s;
  1106. return;
  1107. }
  1108. if (m11 > m22 && m11 > m33) {
  1109. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1110. this.w = (m32 - m23) / s;
  1111. this.x = 0.25 * s;
  1112. this.y = (m12 + m21) / s;
  1113. this.z = (m13 + m31) / s;
  1114. return;
  1115. }
  1116. if (m22 > m33) {
  1117. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1118. this.w = (m13 - m31) / s;
  1119. this.x = (m12 + m21) / s;
  1120. this.y = 0.25 * s;
  1121. this.z = (m23 + m32) / s;
  1122. return;
  1123. }
  1124. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1125. this.w = (m21 - m12) / s;
  1126. this.x = (m13 + m31) / s;
  1127. this.y = (m23 + m32) / s;
  1128. this.z = 0.25 * s;
  1129. };
  1130. // Statics
  1131. Quaternion.Inverse = function (q) {
  1132. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  1133. };
  1134. Quaternion.RotationAxis = function (axis, angle) {
  1135. var result = new Quaternion();
  1136. var sin = Math.sin(angle / 2);
  1137. result.w = Math.cos(angle / 2);
  1138. result.x = axis.x * sin;
  1139. result.y = axis.y * sin;
  1140. result.z = axis.z * sin;
  1141. return result;
  1142. };
  1143. Quaternion.FromArray = function (array, offset) {
  1144. if (!offset) {
  1145. offset = 0;
  1146. }
  1147. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1148. };
  1149. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1150. var result = new Quaternion();
  1151. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1152. return result;
  1153. };
  1154. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1155. var halfRoll = roll * 0.5;
  1156. var halfPitch = pitch * 0.5;
  1157. var halfYaw = yaw * 0.5;
  1158. var sinRoll = Math.sin(halfRoll);
  1159. var cosRoll = Math.cos(halfRoll);
  1160. var sinPitch = Math.sin(halfPitch);
  1161. var cosPitch = Math.cos(halfPitch);
  1162. var sinYaw = Math.sin(halfYaw);
  1163. var cosYaw = Math.cos(halfYaw);
  1164. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  1165. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  1166. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  1167. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  1168. };
  1169. Quaternion.Slerp = function (left, right, amount) {
  1170. var num2;
  1171. var num3;
  1172. var num = amount;
  1173. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  1174. var flag = false;
  1175. if (num4 < 0) {
  1176. flag = true;
  1177. num4 = -num4;
  1178. }
  1179. if (num4 > 0.999999) {
  1180. num3 = 1 - num;
  1181. num2 = flag ? -num : num;
  1182. } else {
  1183. var num5 = Math.acos(num4);
  1184. var num6 = (1.0 / Math.sin(num5));
  1185. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  1186. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  1187. }
  1188. return new Quaternion((num3 * left.x) + (num2 * right.x), (num3 * left.y) + (num2 * right.y), (num3 * left.z) + (num2 * right.z), (num3 * left.w) + (num2 * right.w));
  1189. };
  1190. return Quaternion;
  1191. })();
  1192. BABYLON.Quaternion = Quaternion;
  1193. var Matrix = (function () {
  1194. function Matrix() {
  1195. this.m = new Float32Array(16);
  1196. }
  1197. // Properties
  1198. Matrix.prototype.isIdentity = function () {
  1199. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  1200. return false;
  1201. if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 || this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 || this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 || this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0)
  1202. return false;
  1203. return true;
  1204. };
  1205. Matrix.prototype.determinant = function () {
  1206. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  1207. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  1208. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  1209. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  1210. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  1211. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  1212. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) - (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) - (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  1213. };
  1214. // Methods
  1215. Matrix.prototype.toArray = function () {
  1216. return this.m;
  1217. };
  1218. Matrix.prototype.asArray = function () {
  1219. return this.toArray();
  1220. };
  1221. Matrix.prototype.invert = function () {
  1222. this.invertToRef(this);
  1223. };
  1224. Matrix.prototype.invertToRef = function (other) {
  1225. var l1 = this.m[0];
  1226. var l2 = this.m[1];
  1227. var l3 = this.m[2];
  1228. var l4 = this.m[3];
  1229. var l5 = this.m[4];
  1230. var l6 = this.m[5];
  1231. var l7 = this.m[6];
  1232. var l8 = this.m[7];
  1233. var l9 = this.m[8];
  1234. var l10 = this.m[9];
  1235. var l11 = this.m[10];
  1236. var l12 = this.m[11];
  1237. var l13 = this.m[12];
  1238. var l14 = this.m[13];
  1239. var l15 = this.m[14];
  1240. var l16 = this.m[15];
  1241. var l17 = (l11 * l16) - (l12 * l15);
  1242. var l18 = (l10 * l16) - (l12 * l14);
  1243. var l19 = (l10 * l15) - (l11 * l14);
  1244. var l20 = (l9 * l16) - (l12 * l13);
  1245. var l21 = (l9 * l15) - (l11 * l13);
  1246. var l22 = (l9 * l14) - (l10 * l13);
  1247. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  1248. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  1249. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  1250. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  1251. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  1252. var l28 = (l7 * l16) - (l8 * l15);
  1253. var l29 = (l6 * l16) - (l8 * l14);
  1254. var l30 = (l6 * l15) - (l7 * l14);
  1255. var l31 = (l5 * l16) - (l8 * l13);
  1256. var l32 = (l5 * l15) - (l7 * l13);
  1257. var l33 = (l5 * l14) - (l6 * l13);
  1258. var l34 = (l7 * l12) - (l8 * l11);
  1259. var l35 = (l6 * l12) - (l8 * l10);
  1260. var l36 = (l6 * l11) - (l7 * l10);
  1261. var l37 = (l5 * l12) - (l8 * l9);
  1262. var l38 = (l5 * l11) - (l7 * l9);
  1263. var l39 = (l5 * l10) - (l6 * l9);
  1264. other.m[0] = l23 * l27;
  1265. other.m[4] = l24 * l27;
  1266. other.m[8] = l25 * l27;
  1267. other.m[12] = l26 * l27;
  1268. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  1269. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  1270. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  1271. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  1272. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  1273. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  1274. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  1275. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  1276. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  1277. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  1278. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  1279. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  1280. };
  1281. Matrix.prototype.setTranslation = function (vector3) {
  1282. this.m[12] = vector3.x;
  1283. this.m[13] = vector3.y;
  1284. this.m[14] = vector3.z;
  1285. };
  1286. Matrix.prototype.multiply = function (other) {
  1287. var result = new Matrix();
  1288. this.multiplyToRef(other, result);
  1289. return result;
  1290. };
  1291. Matrix.prototype.copyFrom = function (other) {
  1292. for (var index = 0; index < 16; index++) {
  1293. this.m[index] = other.m[index];
  1294. }
  1295. };
  1296. Matrix.prototype.copyToArray = function (array, offset) {
  1297. if (typeof offset === "undefined") { offset = 0; }
  1298. for (var index = 0; index < 16; index++) {
  1299. array[offset + index] = this.m[index];
  1300. }
  1301. };
  1302. Matrix.prototype.multiplyToRef = function (other, result) {
  1303. this.multiplyToArray(other, result.m, 0);
  1304. };
  1305. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1306. var tm0 = this.m[0];
  1307. var tm1 = this.m[1];
  1308. var tm2 = this.m[2];
  1309. var tm3 = this.m[3];
  1310. var tm4 = this.m[4];
  1311. var tm5 = this.m[5];
  1312. var tm6 = this.m[6];
  1313. var tm7 = this.m[7];
  1314. var tm8 = this.m[8];
  1315. var tm9 = this.m[9];
  1316. var tm10 = this.m[10];
  1317. var tm11 = this.m[11];
  1318. var tm12 = this.m[12];
  1319. var tm13 = this.m[13];
  1320. var tm14 = this.m[14];
  1321. var tm15 = this.m[15];
  1322. var om0 = other.m[0];
  1323. var om1 = other.m[1];
  1324. var om2 = other.m[2];
  1325. var om3 = other.m[3];
  1326. var om4 = other.m[4];
  1327. var om5 = other.m[5];
  1328. var om6 = other.m[6];
  1329. var om7 = other.m[7];
  1330. var om8 = other.m[8];
  1331. var om9 = other.m[9];
  1332. var om10 = other.m[10];
  1333. var om11 = other.m[11];
  1334. var om12 = other.m[12];
  1335. var om13 = other.m[13];
  1336. var om14 = other.m[14];
  1337. var om15 = other.m[15];
  1338. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1339. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1340. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1341. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1342. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1343. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1344. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1345. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1346. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1347. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1348. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1349. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1350. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1351. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1352. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1353. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1354. };
  1355. Matrix.prototype.equals = function (value) {
  1356. return value && (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] && this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] && this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] && this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  1357. };
  1358. Matrix.prototype.clone = function () {
  1359. return Matrix.FromValues(this.m[0], this.m[1], this.m[2], this.m[3], this.m[4], this.m[5], this.m[6], this.m[7], this.m[8], this.m[9], this.m[10], this.m[11], this.m[12], this.m[13], this.m[14], this.m[15]);
  1360. };
  1361. // Statics
  1362. Matrix.FromArray = function (array, offset) {
  1363. var result = new Matrix();
  1364. if (!offset) {
  1365. offset = 0;
  1366. }
  1367. Matrix.FromArrayToRef(array, offset, result);
  1368. return result;
  1369. };
  1370. Matrix.FromArrayToRef = function (array, offset, result) {
  1371. for (var index = 0; index < 16; index++) {
  1372. result.m[index] = array[index + offset];
  1373. }
  1374. };
  1375. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  1376. result.m[0] = initialM11;
  1377. result.m[1] = initialM12;
  1378. result.m[2] = initialM13;
  1379. result.m[3] = initialM14;
  1380. result.m[4] = initialM21;
  1381. result.m[5] = initialM22;
  1382. result.m[6] = initialM23;
  1383. result.m[7] = initialM24;
  1384. result.m[8] = initialM31;
  1385. result.m[9] = initialM32;
  1386. result.m[10] = initialM33;
  1387. result.m[11] = initialM34;
  1388. result.m[12] = initialM41;
  1389. result.m[13] = initialM42;
  1390. result.m[14] = initialM43;
  1391. result.m[15] = initialM44;
  1392. };
  1393. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  1394. var result = new Matrix();
  1395. result.m[0] = initialM11;
  1396. result.m[1] = initialM12;
  1397. result.m[2] = initialM13;
  1398. result.m[3] = initialM14;
  1399. result.m[4] = initialM21;
  1400. result.m[5] = initialM22;
  1401. result.m[6] = initialM23;
  1402. result.m[7] = initialM24;
  1403. result.m[8] = initialM31;
  1404. result.m[9] = initialM32;
  1405. result.m[10] = initialM33;
  1406. result.m[11] = initialM34;
  1407. result.m[12] = initialM41;
  1408. result.m[13] = initialM42;
  1409. result.m[14] = initialM43;
  1410. result.m[15] = initialM44;
  1411. return result;
  1412. };
  1413. Matrix.Identity = function () {
  1414. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  1415. };
  1416. Matrix.IdentityToRef = function (result) {
  1417. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  1418. };
  1419. Matrix.Zero = function () {
  1420. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  1421. };
  1422. Matrix.RotationX = function (angle) {
  1423. var result = new Matrix();
  1424. Matrix.RotationXToRef(angle, result);
  1425. return result;
  1426. };
  1427. Matrix.Invert = function (source) {
  1428. var result = new Matrix();
  1429. source.invertToRef(result);
  1430. return result;
  1431. };
  1432. Matrix.RotationXToRef = function (angle, result) {
  1433. var s = Math.sin(angle);
  1434. var c = Math.cos(angle);
  1435. result.m[0] = 1.0;
  1436. result.m[15] = 1.0;
  1437. result.m[5] = c;
  1438. result.m[10] = c;
  1439. result.m[9] = -s;
  1440. result.m[6] = s;
  1441. result.m[1] = 0;
  1442. result.m[2] = 0;
  1443. result.m[3] = 0;
  1444. result.m[4] = 0;
  1445. result.m[7] = 0;
  1446. result.m[8] = 0;
  1447. result.m[11] = 0;
  1448. result.m[12] = 0;
  1449. result.m[13] = 0;
  1450. result.m[14] = 0;
  1451. };
  1452. Matrix.RotationY = function (angle) {
  1453. var result = new Matrix();
  1454. Matrix.RotationYToRef(angle, result);
  1455. return result;
  1456. };
  1457. Matrix.RotationYToRef = function (angle, result) {
  1458. var s = Math.sin(angle);
  1459. var c = Math.cos(angle);
  1460. result.m[5] = 1.0;
  1461. result.m[15] = 1.0;
  1462. result.m[0] = c;
  1463. result.m[2] = -s;
  1464. result.m[8] = s;
  1465. result.m[10] = c;
  1466. result.m[1] = 0;
  1467. result.m[3] = 0;
  1468. result.m[4] = 0;
  1469. result.m[6] = 0;
  1470. result.m[7] = 0;
  1471. result.m[9] = 0;
  1472. result.m[11] = 0;
  1473. result.m[12] = 0;
  1474. result.m[13] = 0;
  1475. result.m[14] = 0;
  1476. };
  1477. Matrix.RotationZ = function (angle) {
  1478. var result = new Matrix();
  1479. Matrix.RotationZToRef(angle, result);
  1480. return result;
  1481. };
  1482. Matrix.RotationZToRef = function (angle, result) {
  1483. var s = Math.sin(angle);
  1484. var c = Math.cos(angle);
  1485. result.m[10] = 1.0;
  1486. result.m[15] = 1.0;
  1487. result.m[0] = c;
  1488. result.m[1] = s;
  1489. result.m[4] = -s;
  1490. result.m[5] = c;
  1491. result.m[2] = 0;
  1492. result.m[3] = 0;
  1493. result.m[6] = 0;
  1494. result.m[7] = 0;
  1495. result.m[8] = 0;
  1496. result.m[9] = 0;
  1497. result.m[11] = 0;
  1498. result.m[12] = 0;
  1499. result.m[13] = 0;
  1500. result.m[14] = 0;
  1501. };
  1502. Matrix.RotationAxis = function (axis, angle) {
  1503. var s = Math.sin(-angle);
  1504. var c = Math.cos(-angle);
  1505. var c1 = 1 - c;
  1506. axis.normalize();
  1507. var result = Matrix.Zero();
  1508. result.m[0] = (axis.x * axis.x) * c1 + c;
  1509. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  1510. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  1511. result.m[3] = 0.0;
  1512. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  1513. result.m[5] = (axis.y * axis.y) * c1 + c;
  1514. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  1515. result.m[7] = 0.0;
  1516. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  1517. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  1518. result.m[10] = (axis.z * axis.z) * c1 + c;
  1519. result.m[11] = 0.0;
  1520. result.m[15] = 1.0;
  1521. return result;
  1522. };
  1523. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1524. var result = new Matrix();
  1525. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1526. return result;
  1527. };
  1528. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1529. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  1530. this._tempQuaternion.toRotationMatrix(result);
  1531. };
  1532. Matrix.Scaling = function (x, y, z) {
  1533. var result = Matrix.Zero();
  1534. Matrix.ScalingToRef(x, y, z, result);
  1535. return result;
  1536. };
  1537. Matrix.ScalingToRef = function (x, y, z, result) {
  1538. result.m[0] = x;
  1539. result.m[1] = 0;
  1540. result.m[2] = 0;
  1541. result.m[3] = 0;
  1542. result.m[4] = 0;
  1543. result.m[5] = y;
  1544. result.m[6] = 0;
  1545. result.m[7] = 0;
  1546. result.m[8] = 0;
  1547. result.m[9] = 0;
  1548. result.m[10] = z;
  1549. result.m[11] = 0;
  1550. result.m[12] = 0;
  1551. result.m[13] = 0;
  1552. result.m[14] = 0;
  1553. result.m[15] = 1.0;
  1554. };
  1555. Matrix.Translation = function (x, y, z) {
  1556. var result = Matrix.Identity();
  1557. Matrix.TranslationToRef(x, y, z, result);
  1558. return result;
  1559. };
  1560. Matrix.TranslationToRef = function (x, y, z, result) {
  1561. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  1562. };
  1563. Matrix.LookAtLH = function (eye, target, up) {
  1564. var result = Matrix.Zero();
  1565. Matrix.LookAtLHToRef(eye, target, up, result);
  1566. return result;
  1567. };
  1568. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  1569. // Z axis
  1570. target.subtractToRef(eye, this._zAxis);
  1571. this._zAxis.normalize();
  1572. // X axis
  1573. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  1574. this._xAxis.normalize();
  1575. // Y axis
  1576. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  1577. this._yAxis.normalize();
  1578. // Eye angles
  1579. var ex = -Vector3.Dot(this._xAxis, eye);
  1580. var ey = -Vector3.Dot(this._yAxis, eye);
  1581. var ez = -Vector3.Dot(this._zAxis, eye);
  1582. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  1583. };
  1584. Matrix.OrthoLH = function (width, height, znear, zfar) {
  1585. var hw = 2.0 / width;
  1586. var hh = 2.0 / height;
  1587. var id = 1.0 / (zfar - znear);
  1588. var nid = znear / (znear - zfar);
  1589. return Matrix.FromValues(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1);
  1590. };
  1591. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  1592. var matrix = Matrix.Zero();
  1593. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  1594. return matrix;
  1595. };
  1596. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  1597. result.m[0] = 2.0 / (right - left);
  1598. result.m[1] = result.m[2] = result.m[3] = 0;
  1599. result.m[5] = 2.0 / (top - bottom);
  1600. result.m[4] = result.m[6] = result.m[7] = 0;
  1601. result.m[10] = -1.0 / (znear - zfar);
  1602. result.m[8] = result.m[9] = result.m[11] = 0;
  1603. result.m[12] = (left + right) / (left - right);
  1604. result.m[13] = (top + bottom) / (bottom - top);
  1605. result.m[14] = znear / (znear - zfar);
  1606. result.m[15] = 1.0;
  1607. };
  1608. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  1609. var matrix = Matrix.Zero();
  1610. matrix.m[0] = (2.0 * znear) / width;
  1611. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  1612. matrix.m[5] = (2.0 * znear) / height;
  1613. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  1614. matrix.m[10] = -zfar / (znear - zfar);
  1615. matrix.m[8] = matrix.m[9] = 0.0;
  1616. matrix.m[11] = 1.0;
  1617. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  1618. matrix.m[14] = (znear * zfar) / (znear - zfar);
  1619. return matrix;
  1620. };
  1621. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  1622. var matrix = Matrix.Zero();
  1623. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  1624. return matrix;
  1625. };
  1626. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result) {
  1627. var tan = 1.0 / (Math.tan(fov * 0.5));
  1628. result.m[0] = tan / aspect;
  1629. result.m[1] = result.m[2] = result.m[3] = 0.0;
  1630. result.m[5] = tan;
  1631. result.m[4] = result.m[6] = result.m[7] = 0.0;
  1632. result.m[8] = result.m[9] = 0.0;
  1633. result.m[10] = -zfar / (znear - zfar);
  1634. result.m[11] = 1.0;
  1635. result.m[12] = result.m[13] = result.m[15] = 0.0;
  1636. result.m[14] = (znear * zfar) / (znear - zfar);
  1637. };
  1638. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  1639. var cw = viewport.width;
  1640. var ch = viewport.height;
  1641. var cx = viewport.x;
  1642. var cy = viewport.y;
  1643. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, zmax - zmin, 0, cx + cw / 2.0, ch / 2.0 + cy, zmin, 1);
  1644. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  1645. };
  1646. Matrix.Transpose = function (matrix) {
  1647. var result = new Matrix();
  1648. result.m[0] = matrix.m[0];
  1649. result.m[1] = matrix.m[4];
  1650. result.m[2] = matrix.m[8];
  1651. result.m[3] = matrix.m[12];
  1652. result.m[4] = matrix.m[1];
  1653. result.m[5] = matrix.m[5];
  1654. result.m[6] = matrix.m[9];
  1655. result.m[7] = matrix.m[13];
  1656. result.m[8] = matrix.m[2];
  1657. result.m[9] = matrix.m[6];
  1658. result.m[10] = matrix.m[10];
  1659. result.m[11] = matrix.m[14];
  1660. result.m[12] = matrix.m[3];
  1661. result.m[13] = matrix.m[7];
  1662. result.m[14] = matrix.m[11];
  1663. result.m[15] = matrix.m[15];
  1664. return result;
  1665. };
  1666. Matrix.Reflection = function (plane) {
  1667. var matrix = new Matrix();
  1668. Matrix.ReflectionToRef(plane, matrix);
  1669. return matrix;
  1670. };
  1671. Matrix.ReflectionToRef = function (plane, result) {
  1672. plane.normalize();
  1673. var x = plane.normal.x;
  1674. var y = plane.normal.y;
  1675. var z = plane.normal.z;
  1676. var temp = -2 * x;
  1677. var temp2 = -2 * y;
  1678. var temp3 = -2 * z;
  1679. result.m[0] = (temp * x) + 1;
  1680. result.m[1] = temp2 * x;
  1681. result.m[2] = temp3 * x;
  1682. result.m[3] = 0.0;
  1683. result.m[4] = temp * y;
  1684. result.m[5] = (temp2 * y) + 1;
  1685. result.m[6] = temp3 * y;
  1686. result.m[7] = 0.0;
  1687. result.m[8] = temp * z;
  1688. result.m[9] = temp2 * z;
  1689. result.m[10] = (temp3 * z) + 1;
  1690. result.m[11] = 0.0;
  1691. result.m[12] = temp * plane.d;
  1692. result.m[13] = temp2 * plane.d;
  1693. result.m[14] = temp3 * plane.d;
  1694. result.m[15] = 1.0;
  1695. };
  1696. Matrix._tempQuaternion = new Quaternion();
  1697. Matrix._xAxis = Vector3.Zero();
  1698. Matrix._yAxis = Vector3.Zero();
  1699. Matrix._zAxis = Vector3.Zero();
  1700. return Matrix;
  1701. })();
  1702. BABYLON.Matrix = Matrix;
  1703. var Plane = (function () {
  1704. function Plane(a, b, c, d) {
  1705. this.normal = new Vector3(a, b, c);
  1706. this.d = d;
  1707. }
  1708. Plane.prototype.asArray = function () {
  1709. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  1710. };
  1711. // Methods
  1712. Plane.prototype.clone = function () {
  1713. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  1714. };
  1715. Plane.prototype.normalize = function () {
  1716. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  1717. var magnitude = 0;
  1718. if (norm !== 0) {
  1719. magnitude = 1.0 / norm;
  1720. }
  1721. this.normal.x *= magnitude;
  1722. this.normal.y *= magnitude;
  1723. this.normal.z *= magnitude;
  1724. this.d *= magnitude;
  1725. };
  1726. Plane.prototype.transform = function (transformation) {
  1727. var transposedMatrix = Matrix.Transpose(transformation);
  1728. var x = this.normal.x;
  1729. var y = this.normal.y;
  1730. var z = this.normal.z;
  1731. var d = this.d;
  1732. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  1733. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  1734. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  1735. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  1736. return new Plane(normalX, normalY, normalZ, finalD);
  1737. };
  1738. Plane.prototype.dotCoordinate = function (point) {
  1739. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  1740. };
  1741. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  1742. var x1 = point2.x - point1.x;
  1743. var y1 = point2.y - point1.y;
  1744. var z1 = point2.z - point1.z;
  1745. var x2 = point3.x - point1.x;
  1746. var y2 = point3.y - point1.y;
  1747. var z2 = point3.z - point1.z;
  1748. var yz = (y1 * z2) - (z1 * y2);
  1749. var xz = (z1 * x2) - (x1 * z2);
  1750. var xy = (x1 * y2) - (y1 * x2);
  1751. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  1752. var invPyth;
  1753. if (pyth !== 0) {
  1754. invPyth = 1.0 / pyth;
  1755. } else {
  1756. invPyth = 0;
  1757. }
  1758. this.normal.x = yz * invPyth;
  1759. this.normal.y = xz * invPyth;
  1760. this.normal.z = xy * invPyth;
  1761. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  1762. };
  1763. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  1764. var dot = Vector3.Dot(this.normal, direction);
  1765. return (dot <= epsilon);
  1766. };
  1767. Plane.prototype.signedDistanceTo = function (point) {
  1768. return Vector3.Dot(point, this.normal) + this.d;
  1769. };
  1770. // Statics
  1771. Plane.FromArray = function (array) {
  1772. return new Plane(array[0], array[1], array[2], array[3]);
  1773. };
  1774. Plane.FromPoints = function (point1, point2, point3) {
  1775. var result = new Plane(0, 0, 0, 0);
  1776. result.copyFromPoints(point1, point2, point3);
  1777. return result;
  1778. };
  1779. Plane.FromPositionAndNormal = function (origin, normal) {
  1780. var result = new Plane(0, 0, 0, 0);
  1781. normal.normalize();
  1782. result.normal = normal;
  1783. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  1784. return result;
  1785. };
  1786. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  1787. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  1788. return Vector3.Dot(point, normal) + d;
  1789. };
  1790. return Plane;
  1791. })();
  1792. BABYLON.Plane = Plane;
  1793. var Viewport = (function () {
  1794. function Viewport(x, y, width, height) {
  1795. this.x = x;
  1796. this.y = y;
  1797. this.width = width;
  1798. this.height = height;
  1799. }
  1800. Viewport.prototype.toGlobal = function (engine) {
  1801. var width = engine.getRenderWidth();
  1802. var height = engine.getRenderHeight();
  1803. return new Viewport(this.x * width, this.y * height, this.width * width, this.height * height);
  1804. };
  1805. return Viewport;
  1806. })();
  1807. BABYLON.Viewport = Viewport;
  1808. var Frustum = (function () {
  1809. function Frustum() {
  1810. }
  1811. Frustum.GetPlanes = function (transform) {
  1812. var frustumPlanes = [];
  1813. for (var index = 0; index < 6; index++) {
  1814. frustumPlanes.push(new Plane(0, 0, 0, 0));
  1815. }
  1816. Frustum.GetPlanesToRef(transform, frustumPlanes);
  1817. return frustumPlanes;
  1818. };
  1819. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  1820. // Near
  1821. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  1822. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  1823. frustumPlanes[0].normal.z = transform.m[10] + transform.m[10];
  1824. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  1825. frustumPlanes[0].normalize();
  1826. // Far
  1827. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  1828. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  1829. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  1830. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  1831. frustumPlanes[1].normalize();
  1832. // Left
  1833. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  1834. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  1835. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  1836. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  1837. frustumPlanes[2].normalize();
  1838. // Right
  1839. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  1840. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  1841. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  1842. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  1843. frustumPlanes[3].normalize();
  1844. // Top
  1845. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  1846. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  1847. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  1848. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  1849. frustumPlanes[4].normalize();
  1850. // Bottom
  1851. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  1852. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  1853. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  1854. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  1855. frustumPlanes[5].normalize();
  1856. };
  1857. return Frustum;
  1858. })();
  1859. BABYLON.Frustum = Frustum;
  1860. var Ray = (function () {
  1861. function Ray(origin, direction, length) {
  1862. if (typeof length === "undefined") { length = Number.MAX_VALUE; }
  1863. this.origin = origin;
  1864. this.direction = direction;
  1865. this.length = length;
  1866. }
  1867. // Methods
  1868. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  1869. var d = 0.0;
  1870. var maxValue = Number.MAX_VALUE;
  1871. if (Math.abs(this.direction.x) < 0.0000001) {
  1872. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  1873. return false;
  1874. }
  1875. } else {
  1876. var inv = 1.0 / this.direction.x;
  1877. var min = (minimum.x - this.origin.x) * inv;
  1878. var max = (maximum.x - this.origin.x) * inv;
  1879. if (max === -Infinity) {
  1880. max = Infinity;
  1881. }
  1882. if (min > max) {
  1883. var temp = min;
  1884. min = max;
  1885. max = temp;
  1886. }
  1887. d = Math.max(min, d);
  1888. maxValue = Math.min(max, maxValue);
  1889. if (d > maxValue) {
  1890. return false;
  1891. }
  1892. }
  1893. if (Math.abs(this.direction.y) < 0.0000001) {
  1894. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  1895. return false;
  1896. }
  1897. } else {
  1898. inv = 1.0 / this.direction.y;
  1899. min = (minimum.y - this.origin.y) * inv;
  1900. max = (maximum.y - this.origin.y) * inv;
  1901. if (max === -Infinity) {
  1902. max = Infinity;
  1903. }
  1904. if (min > max) {
  1905. temp = min;
  1906. min = max;
  1907. max = temp;
  1908. }
  1909. d = Math.max(min, d);
  1910. maxValue = Math.min(max, maxValue);
  1911. if (d > maxValue) {
  1912. return false;
  1913. }
  1914. }
  1915. if (Math.abs(this.direction.z) < 0.0000001) {
  1916. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  1917. return false;
  1918. }
  1919. } else {
  1920. inv = 1.0 / this.direction.z;
  1921. min = (minimum.z - this.origin.z) * inv;
  1922. max = (maximum.z - this.origin.z) * inv;
  1923. if (max === -Infinity) {
  1924. max = Infinity;
  1925. }
  1926. if (min > max) {
  1927. temp = min;
  1928. min = max;
  1929. max = temp;
  1930. }
  1931. d = Math.max(min, d);
  1932. maxValue = Math.min(max, maxValue);
  1933. if (d > maxValue) {
  1934. return false;
  1935. }
  1936. }
  1937. return true;
  1938. };
  1939. Ray.prototype.intersectsBox = function (box) {
  1940. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  1941. };
  1942. Ray.prototype.intersectsSphere = function (sphere) {
  1943. var x = sphere.center.x - this.origin.x;
  1944. var y = sphere.center.y - this.origin.y;
  1945. var z = sphere.center.z - this.origin.z;
  1946. var pyth = (x * x) + (y * y) + (z * z);
  1947. var rr = sphere.radius * sphere.radius;
  1948. if (pyth <= rr) {
  1949. return true;
  1950. }
  1951. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  1952. if (dot < 0.0) {
  1953. return false;
  1954. }
  1955. var temp = pyth - (dot * dot);
  1956. return temp <= rr;
  1957. };
  1958. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  1959. if (!this._edge1) {
  1960. this._edge1 = Vector3.Zero();
  1961. this._edge2 = Vector3.Zero();
  1962. this._pvec = Vector3.Zero();
  1963. this._tvec = Vector3.Zero();
  1964. this._qvec = Vector3.Zero();
  1965. }
  1966. vertex1.subtractToRef(vertex0, this._edge1);
  1967. vertex2.subtractToRef(vertex0, this._edge2);
  1968. Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  1969. var det = Vector3.Dot(this._edge1, this._pvec);
  1970. if (det === 0) {
  1971. return null;
  1972. }
  1973. var invdet = 1 / det;
  1974. this.origin.subtractToRef(vertex0, this._tvec);
  1975. var bu = Vector3.Dot(this._tvec, this._pvec) * invdet;
  1976. if (bu < 0 || bu > 1.0) {
  1977. return null;
  1978. }
  1979. Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  1980. var bv = Vector3.Dot(this.direction, this._qvec) * invdet;
  1981. if (bv < 0 || bu + bv > 1.0) {
  1982. return null;
  1983. }
  1984. //check if the distance is longer than the predefined length.
  1985. var distance = Vector3.Dot(this._edge2, this._qvec) * invdet;
  1986. if (distance > this.length) {
  1987. return null;
  1988. }
  1989. return new BABYLON.IntersectionInfo(bu, bv, distance);
  1990. };
  1991. // Statics
  1992. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  1993. var start = Vector3.Unproject(new Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  1994. var end = Vector3.Unproject(new Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  1995. var direction = end.subtract(start);
  1996. direction.normalize();
  1997. return new Ray(start, direction);
  1998. };
  1999. /**
  2000. * Function will create a new transformed ray starting from origin and ending at the end point. Ray's length will be set, and ray will be
  2001. * transformed to the given world matrix.
  2002. * @param origin The origin point
  2003. * @param end The end point
  2004. * @param world a matrix to transform the ray to. Default is the identity matrix.
  2005. */
  2006. Ray.CreateNewFromTo = function (origin, end, world) {
  2007. if (typeof world === "undefined") { world = Matrix.Identity(); }
  2008. var direction = end.subtract(origin);
  2009. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  2010. direction.normalize();
  2011. return Ray.Transform(new Ray(origin, direction, length), world);
  2012. };
  2013. Ray.Transform = function (ray, matrix) {
  2014. var newOrigin = Vector3.TransformCoordinates(ray.origin, matrix);
  2015. var newDirection = Vector3.TransformNormal(ray.direction, matrix);
  2016. return new Ray(newOrigin, newDirection, ray.length);
  2017. };
  2018. return Ray;
  2019. })();
  2020. BABYLON.Ray = Ray;
  2021. (function (Space) {
  2022. Space[Space["LOCAL"] = 0] = "LOCAL";
  2023. Space[Space["WORLD"] = 1] = "WORLD";
  2024. })(BABYLON.Space || (BABYLON.Space = {}));
  2025. var Space = BABYLON.Space;
  2026. var Axis = (function () {
  2027. function Axis() {
  2028. }
  2029. Axis.X = new Vector3(1, 0, 0);
  2030. Axis.Y = new Vector3(0, 1, 0);
  2031. Axis.Z = new Vector3(0, 0, 1);
  2032. return Axis;
  2033. })();
  2034. BABYLON.Axis = Axis;
  2035. ;
  2036. var BezierCurve = (function () {
  2037. function BezierCurve() {
  2038. }
  2039. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  2040. // Extract X (which is equal to time here)
  2041. var f0 = 1 - 3 * x2 + 3 * x1;
  2042. var f1 = 3 * x2 - 6 * x1;
  2043. var f2 = 3 * x1;
  2044. var refinedT = t;
  2045. for (var i = 0; i < 5; i++) {
  2046. var refinedT2 = refinedT * refinedT;
  2047. var refinedT3 = refinedT2 * refinedT;
  2048. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  2049. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  2050. refinedT -= (x - t) * slope;
  2051. refinedT = Math.min(1, Math.max(0, refinedT));
  2052. }
  2053. // Resolve cubic bezier for the given x
  2054. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 + 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 + Math.pow(refinedT, 3);
  2055. };
  2056. return BezierCurve;
  2057. })();
  2058. BABYLON.BezierCurve = BezierCurve;
  2059. (function (Orientation) {
  2060. Orientation[Orientation["CW"] = 0] = "CW";
  2061. Orientation[Orientation["CCW"] = 1] = "CCW";
  2062. })(BABYLON.Orientation || (BABYLON.Orientation = {}));
  2063. var Orientation = BABYLON.Orientation;
  2064. var Angle = (function () {
  2065. function Angle(radians) {
  2066. var _this = this;
  2067. this.degrees = function () {
  2068. return _this._radians * 180 / Math.PI;
  2069. };
  2070. this.radians = function () {
  2071. return _this._radians;
  2072. };
  2073. this._radians = radians;
  2074. if (this._radians < 0)
  2075. this._radians += (2 * Math.PI);
  2076. }
  2077. Angle.BetweenTwoPoints = function (a, b) {
  2078. var delta = b.subtract(a);
  2079. var theta = Math.atan2(delta.y, delta.x);
  2080. return new Angle(theta);
  2081. };
  2082. Angle.FromRadians = function (radians) {
  2083. return new Angle(radians);
  2084. };
  2085. Angle.FromDegrees = function (degrees) {
  2086. return new Angle(degrees * Math.PI / 180);
  2087. };
  2088. return Angle;
  2089. })();
  2090. BABYLON.Angle = Angle;
  2091. var Arc2 = (function () {
  2092. function Arc2(startPoint, midPoint, endPoint) {
  2093. this.startPoint = startPoint;
  2094. this.midPoint = midPoint;
  2095. this.endPoint = endPoint;
  2096. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  2097. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  2098. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  2099. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  2100. this.centerPoint = new Vector2((startToMid * (midPoint.y - endPoint.y) - midToEnd * (startPoint.y - midPoint.y)) / det, ((startPoint.x - midPoint.x) * midToEnd - (midPoint.x - endPoint.x) * startToMid) / det);
  2101. this.radius = this.centerPoint.subtract(this.startPoint).length();
  2102. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  2103. var a1 = this.startAngle.degrees();
  2104. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  2105. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  2106. // angles correction
  2107. if (a2 - a1 > +180.0)
  2108. a2 -= 360.0;
  2109. if (a2 - a1 < -180.0)
  2110. a2 += 360.0;
  2111. if (a3 - a2 > +180.0)
  2112. a3 -= 360.0;
  2113. if (a3 - a2 < -180.0)
  2114. a3 += 360.0;
  2115. this.orientation = (a2 - a1) < 0 ? 0 /* CW */ : 1 /* CCW */;
  2116. this.angle = Angle.FromDegrees(this.orientation === 0 /* CW */ ? a1 - a3 : a3 - a1);
  2117. }
  2118. return Arc2;
  2119. })();
  2120. BABYLON.Arc2 = Arc2;
  2121. var PathCursor = (function () {
  2122. function PathCursor(path) {
  2123. this.path = path;
  2124. this._onchange = new Array();
  2125. this.value = 0;
  2126. this.animations = new Array();
  2127. }
  2128. PathCursor.prototype.getPoint = function () {
  2129. var point = this.path.getPointAtLengthPosition(this.value);
  2130. return new Vector3(point.x, 0, point.y);
  2131. };
  2132. PathCursor.prototype.moveAhead = function (step) {
  2133. if (typeof step === "undefined") { step = 0.002; }
  2134. this.move(step);
  2135. };
  2136. PathCursor.prototype.moveBack = function (step) {
  2137. if (typeof step === "undefined") { step = 0.002; }
  2138. this.move(-step);
  2139. };
  2140. PathCursor.prototype.move = function (step) {
  2141. if (Math.abs(step) > 1) {
  2142. throw "step size should be less than 1.";
  2143. }
  2144. this.value += step;
  2145. this.ensureLimits();
  2146. this.raiseOnChange();
  2147. };
  2148. PathCursor.prototype.ensureLimits = function () {
  2149. while (this.value > 1) {
  2150. this.value -= 1;
  2151. }
  2152. while (this.value < 0) {
  2153. this.value += 1;
  2154. }
  2155. };
  2156. // used by animation engine
  2157. PathCursor.prototype.markAsDirty = function (propertyName) {
  2158. this.ensureLimits();
  2159. this.raiseOnChange();
  2160. };
  2161. PathCursor.prototype.raiseOnChange = function () {
  2162. var _this = this;
  2163. this._onchange.forEach(function (f) {
  2164. return f(_this);
  2165. });
  2166. };
  2167. PathCursor.prototype.onchange = function (f) {
  2168. this._onchange.push(f);
  2169. };
  2170. return PathCursor;
  2171. })();
  2172. BABYLON.PathCursor = PathCursor;
  2173. var Path2 = (function () {
  2174. function Path2(x, y) {
  2175. this._points = [];
  2176. this._length = 0;
  2177. this.closed = false;
  2178. this._points.push(new Vector2(x, y));
  2179. }
  2180. Path2.prototype.addLineTo = function (x, y) {
  2181. if (closed) {
  2182. BABYLON.Tools.Error("cannot add lines to closed paths");
  2183. return this;
  2184. }
  2185. var newPoint = new Vector2(x, y);
  2186. var previousPoint = this._points[this._points.length - 1];
  2187. this._points.push(newPoint);
  2188. this._length += newPoint.subtract(previousPoint).length();
  2189. return this;
  2190. };
  2191. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  2192. if (typeof numberOfSegments === "undefined") { numberOfSegments = 36; }
  2193. if (closed) {
  2194. BABYLON.Tools.Error("cannot add arcs to closed paths");
  2195. return this;
  2196. }
  2197. var startPoint = this._points[this._points.length - 1];
  2198. var midPoint = new Vector2(midX, midY);
  2199. var endPoint = new Vector2(endX, endY);
  2200. var arc = new Arc2(startPoint, midPoint, endPoint);
  2201. var increment = arc.angle.radians() / numberOfSegments;
  2202. if (arc.orientation === 0 /* CW */)
  2203. increment *= -1;
  2204. var currentAngle = arc.startAngle.radians() + increment;
  2205. for (var i = 0; i < numberOfSegments; i++) {
  2206. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  2207. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  2208. this.addLineTo(x, y);
  2209. currentAngle += increment;
  2210. }
  2211. return this;
  2212. };
  2213. Path2.prototype.close = function () {
  2214. this.closed = true;
  2215. return this;
  2216. };
  2217. Path2.prototype.length = function () {
  2218. var result = this._length;
  2219. if (!this.closed) {
  2220. var lastPoint = this._points[this._points.length - 1];
  2221. var firstPoint = this._points[0];
  2222. result += (firstPoint.subtract(lastPoint).length());
  2223. }
  2224. return result;
  2225. };
  2226. Path2.prototype.getPoints = function () {
  2227. return this._points;
  2228. };
  2229. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  2230. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  2231. BABYLON.Tools.Error("normalized length position should be between 0 and 1.");
  2232. return;
  2233. }
  2234. var lengthPosition = normalizedLengthPosition * this.length();
  2235. var previousOffset = 0;
  2236. for (var i = 0; i < this._points.length; i++) {
  2237. var j = (i + 1) % this._points.length;
  2238. var a = this._points[i];
  2239. var b = this._points[j];
  2240. var bToA = b.subtract(a);
  2241. var nextOffset = (bToA.length() + previousOffset);
  2242. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  2243. var dir = bToA.normalize();
  2244. var localOffset = lengthPosition - previousOffset;
  2245. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  2246. }
  2247. previousOffset = nextOffset;
  2248. }
  2249. BABYLON.Tools.Error("internal error");
  2250. };
  2251. Path2.StartingAt = function (x, y) {
  2252. return new Path2(x, y);
  2253. };
  2254. return Path2;
  2255. })();
  2256. BABYLON.Path2 = Path2;
  2257. })(BABYLON || (BABYLON = {}));
  2258. //# sourceMappingURL=babylon.math.js.map
  2259. var BABYLON;
  2260. (function (BABYLON) {
  2261. // Screenshots
  2262. var screenshotCanvas;
  2263. var cloneValue = function (source, destinationObject) {
  2264. if (!source)
  2265. return null;
  2266. if (source instanceof BABYLON.Mesh) {
  2267. return null;
  2268. }
  2269. if (source instanceof BABYLON.SubMesh) {
  2270. return source.clone(destinationObject);
  2271. } else if (source.clone) {
  2272. return source.clone();
  2273. }
  2274. return null;
  2275. };
  2276. var Tools = (function () {
  2277. function Tools() {
  2278. }
  2279. Tools.GetFilename = function (path) {
  2280. var index = path.lastIndexOf("/");
  2281. if (index < 0)
  2282. return path;
  2283. return path.substring(index + 1);
  2284. };
  2285. Tools.GetDOMTextContent = function (element) {
  2286. var result = "";
  2287. var child = element.firstChild;
  2288. while (child) {
  2289. if (child.nodeType == 3) {
  2290. result += child.textContent;
  2291. }
  2292. child = child.nextSibling;
  2293. }
  2294. return result;
  2295. };
  2296. Tools.ToDegrees = function (angle) {
  2297. return angle * 180 / Math.PI;
  2298. };
  2299. Tools.ToRadians = function (angle) {
  2300. return angle * Math.PI / 180;
  2301. };
  2302. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount) {
  2303. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  2304. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  2305. for (var index = indexStart; index < indexStart + indexCount; index++) {
  2306. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  2307. minimum = BABYLON.Vector3.Minimize(current, minimum);
  2308. maximum = BABYLON.Vector3.Maximize(current, maximum);
  2309. }
  2310. return {
  2311. minimum: minimum,
  2312. maximum: maximum
  2313. };
  2314. };
  2315. Tools.ExtractMinAndMax = function (positions, start, count) {
  2316. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  2317. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  2318. for (var index = start; index < start + count; index++) {
  2319. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  2320. minimum = BABYLON.Vector3.Minimize(current, minimum);
  2321. maximum = BABYLON.Vector3.Maximize(current, maximum);
  2322. }
  2323. return {
  2324. minimum: minimum,
  2325. maximum: maximum
  2326. };
  2327. };
  2328. Tools.MakeArray = function (obj, allowsNullUndefined) {
  2329. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  2330. return undefined;
  2331. return Array.isArray(obj) ? obj : [obj];
  2332. };
  2333. // Misc.
  2334. Tools.GetPointerPrefix = function () {
  2335. var eventPrefix = "pointer";
  2336. // Check if hand.js is referenced or if the browser natively supports pointer events
  2337. if (!navigator.pointerEnabled) {
  2338. eventPrefix = "mouse";
  2339. }
  2340. return eventPrefix;
  2341. };
  2342. Tools.QueueNewFrame = function (func) {
  2343. if (window.requestAnimationFrame)
  2344. window.requestAnimationFrame(func);
  2345. else if (window.msRequestAnimationFrame)
  2346. window.msRequestAnimationFrame(func);
  2347. else if (window.webkitRequestAnimationFrame)
  2348. window.webkitRequestAnimationFrame(func);
  2349. else if (window.mozRequestAnimationFrame)
  2350. window.mozRequestAnimationFrame(func);
  2351. else if (window.oRequestAnimationFrame)
  2352. window.oRequestAnimationFrame(func);
  2353. else {
  2354. window.setTimeout(func, 16);
  2355. }
  2356. };
  2357. Tools.RequestFullscreen = function (element) {
  2358. if (element.requestFullscreen)
  2359. element.requestFullscreen();
  2360. else if (element.msRequestFullscreen)
  2361. element.msRequestFullscreen();
  2362. else if (element.webkitRequestFullscreen)
  2363. element.webkitRequestFullscreen();
  2364. else if (element.mozRequestFullScreen)
  2365. element.mozRequestFullScreen();
  2366. };
  2367. Tools.ExitFullscreen = function () {
  2368. if (document.exitFullscreen) {
  2369. document.exitFullscreen();
  2370. } else if (document.mozCancelFullScreen) {
  2371. document.mozCancelFullScreen();
  2372. } else if (document.webkitCancelFullScreen) {
  2373. document.webkitCancelFullScreen();
  2374. } else if (document.msCancelFullScreen) {
  2375. document.msCancelFullScreen();
  2376. }
  2377. };
  2378. // External files
  2379. Tools.CleanUrl = function (url) {
  2380. url = url.replace(/#/mg, "%23");
  2381. return url;
  2382. };
  2383. Tools.LoadImage = function (url, onload, onerror, database) {
  2384. url = Tools.CleanUrl(url);
  2385. var img = new Image();
  2386. if (url.substr(0, 5) != "data:")
  2387. img.crossOrigin = 'anonymous';
  2388. img.onload = function () {
  2389. onload(img);
  2390. };
  2391. img.onerror = function (err) {
  2392. onerror(img, err);
  2393. };
  2394. var noIndexedDB = function () {
  2395. img.src = url;
  2396. };
  2397. var loadFromIndexedDB = function () {
  2398. database.loadImageFromDB(url, img);
  2399. };
  2400. //ANY database to do!
  2401. if (database && database.enableTexturesOffline && BABYLON.Database.isUASupportingBlobStorage) {
  2402. database.openAsync(loadFromIndexedDB, noIndexedDB);
  2403. } else {
  2404. if (url.indexOf("file:") === -1) {
  2405. noIndexedDB();
  2406. } else {
  2407. try {
  2408. var textureName = url.substring(5);
  2409. var blobURL;
  2410. try {
  2411. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  2412. } catch (ex) {
  2413. // Chrome doesn't support oneTimeOnly parameter
  2414. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  2415. }
  2416. img.src = blobURL;
  2417. } catch (e) {
  2418. Tools.Log("Error while trying to load texture: " + textureName);
  2419. img.src = null;
  2420. }
  2421. }
  2422. }
  2423. return img;
  2424. };
  2425. //ANY
  2426. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  2427. url = Tools.CleanUrl(url);
  2428. var noIndexedDB = function () {
  2429. var request = new XMLHttpRequest();
  2430. var loadUrl = Tools.BaseUrl + url;
  2431. request.open('GET', loadUrl, true);
  2432. if (useArrayBuffer) {
  2433. request.responseType = "arraybuffer";
  2434. }
  2435. request.onprogress = progressCallBack;
  2436. request.onreadystatechange = function () {
  2437. if (request.readyState == 4) {
  2438. if (request.status == 200 || BABYLON.Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  2439. callback(!useArrayBuffer ? request.responseText : request.response);
  2440. } else {
  2441. if (onError) {
  2442. onError();
  2443. } else {
  2444. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  2445. }
  2446. }
  2447. }
  2448. };
  2449. request.send(null);
  2450. };
  2451. var loadFromIndexedDB = function () {
  2452. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  2453. };
  2454. if (url.indexOf("file:") !== -1) {
  2455. var fileName = url.substring(5);
  2456. BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, true);
  2457. } else {
  2458. // Caching all files
  2459. if (database && database.enableSceneOffline) {
  2460. database.openAsync(loadFromIndexedDB, noIndexedDB);
  2461. } else {
  2462. noIndexedDB();
  2463. }
  2464. }
  2465. };
  2466. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  2467. var reader = new FileReader();
  2468. reader.onload = function (e) {
  2469. callback(e.target.result);
  2470. };
  2471. reader.onprogress = progressCallback;
  2472. reader.readAsDataURL(fileToLoad);
  2473. };
  2474. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  2475. var reader = new FileReader();
  2476. reader.onload = function (e) {
  2477. callback(e.target.result);
  2478. };
  2479. reader.onprogress = progressCallBack;
  2480. if (!useArrayBuffer) {
  2481. // Asynchronous read
  2482. reader.readAsText(fileToLoad);
  2483. } else {
  2484. reader.readAsArrayBuffer(fileToLoad);
  2485. }
  2486. };
  2487. // Misc.
  2488. Tools.Clamp = function (value, min, max) {
  2489. if (typeof min === "undefined") { min = 0; }
  2490. if (typeof max === "undefined") { max = 1; }
  2491. return Math.min(max, Math.max(min, value));
  2492. };
  2493. Tools.Format = function (value, decimals) {
  2494. if (typeof decimals === "undefined") { decimals = 2; }
  2495. return value.toFixed(decimals);
  2496. };
  2497. Tools.CheckExtends = function (v, min, max) {
  2498. if (v.x < min.x)
  2499. min.x = v.x;
  2500. if (v.y < min.y)
  2501. min.y = v.y;
  2502. if (v.z < min.z)
  2503. min.z = v.z;
  2504. if (v.x > max.x)
  2505. max.x = v.x;
  2506. if (v.y > max.y)
  2507. max.y = v.y;
  2508. if (v.z > max.z)
  2509. max.z = v.z;
  2510. };
  2511. Tools.WithinEpsilon = function (a, b, epsilon) {
  2512. if (typeof epsilon === "undefined") { epsilon = 1.401298E-45; }
  2513. var num = a - b;
  2514. return -epsilon <= num && num <= epsilon;
  2515. };
  2516. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  2517. for (var prop in source) {
  2518. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  2519. continue;
  2520. }
  2521. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  2522. continue;
  2523. }
  2524. var sourceValue = source[prop];
  2525. var typeOfSourceValue = typeof sourceValue;
  2526. if (typeOfSourceValue == "function") {
  2527. continue;
  2528. }
  2529. if (typeOfSourceValue == "object") {
  2530. if (sourceValue instanceof Array) {
  2531. destination[prop] = [];
  2532. if (sourceValue.length > 0) {
  2533. if (typeof sourceValue[0] == "object") {
  2534. for (var index = 0; index < sourceValue.length; index++) {
  2535. var clonedValue = cloneValue(sourceValue[index], destination);
  2536. if (destination[prop].indexOf(clonedValue) === -1) {
  2537. destination[prop].push(clonedValue);
  2538. }
  2539. }
  2540. } else {
  2541. destination[prop] = sourceValue.slice(0);
  2542. }
  2543. }
  2544. } else {
  2545. destination[prop] = cloneValue(sourceValue, destination);
  2546. }
  2547. } else {
  2548. destination[prop] = sourceValue;
  2549. }
  2550. }
  2551. };
  2552. Tools.IsEmpty = function (obj) {
  2553. for (var i in obj) {
  2554. return false;
  2555. }
  2556. return true;
  2557. };
  2558. Tools.RegisterTopRootEvents = function (events) {
  2559. for (var index = 0; index < events.length; index++) {
  2560. var event = events[index];
  2561. window.addEventListener(event.name, event.handler, false);
  2562. try {
  2563. if (window.parent) {
  2564. window.parent.addEventListener(event.name, event.handler, false);
  2565. }
  2566. } catch (e) {
  2567. // Silently fails...
  2568. }
  2569. }
  2570. };
  2571. Tools.UnregisterTopRootEvents = function (events) {
  2572. for (var index = 0; index < events.length; index++) {
  2573. var event = events[index];
  2574. window.removeEventListener(event.name, event.handler);
  2575. try {
  2576. if (window.parent) {
  2577. window.parent.removeEventListener(event.name, event.handler);
  2578. }
  2579. } catch (e) {
  2580. // Silently fails...
  2581. }
  2582. }
  2583. };
  2584. Tools.CreateScreenshot = function (engine, camera, size) {
  2585. var width;
  2586. var height;
  2587. var scene = camera.getScene();
  2588. var previousCamera = null;
  2589. if (scene.activeCamera !== camera) {
  2590. previousCamera = scene.activeCamera;
  2591. scene.activeCamera = camera;
  2592. }
  2593. //If a precision value is specified
  2594. if (size.precision) {
  2595. width = Math.round(engine.getRenderWidth() * size.precision);
  2596. height = Math.round(width / engine.getAspectRatio(camera));
  2597. size = { width: width, height: height };
  2598. } else if (size.width && size.height) {
  2599. width = size.width;
  2600. height = size.height;
  2601. } else if (size.width && !size.height) {
  2602. width = size.width;
  2603. height = Math.round(width / engine.getAspectRatio(camera));
  2604. size = { width: width, height: height };
  2605. } else if (size.height && !size.width) {
  2606. height = size.height;
  2607. width = Math.round(height * engine.getAspectRatio(camera));
  2608. size = { width: width, height: height };
  2609. } else if (!isNaN(size)) {
  2610. height = size;
  2611. width = size;
  2612. } else {
  2613. Tools.Error("Invalid 'size' parameter !");
  2614. return;
  2615. }
  2616. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  2617. var texture = new BABYLON.RenderTargetTexture("screenShot", size, engine.scenes[0], false, false);
  2618. texture.renderList = engine.scenes[0].meshes;
  2619. texture.onAfterRender = function () {
  2620. // Read the contents of the framebuffer
  2621. var numberOfChannelsByLine = width * 4;
  2622. var halfHeight = height / 2;
  2623. //Reading datas from WebGL
  2624. var data = engine.readPixels(0, 0, width, height);
  2625. for (var i = 0; i < halfHeight; i++) {
  2626. for (var j = 0; j < numberOfChannelsByLine; j++) {
  2627. var currentCell = j + i * numberOfChannelsByLine;
  2628. var targetLine = height - i - 1;
  2629. var targetCell = j + targetLine * numberOfChannelsByLine;
  2630. var temp = data[currentCell];
  2631. data[currentCell] = data[targetCell];
  2632. data[targetCell] = temp;
  2633. }
  2634. }
  2635. // Create a 2D canvas to store the result
  2636. if (!screenshotCanvas) {
  2637. screenshotCanvas = document.createElement('canvas');
  2638. }
  2639. screenshotCanvas.width = width;
  2640. screenshotCanvas.height = height;
  2641. var context = screenshotCanvas.getContext('2d');
  2642. // Copy the pixels to a 2D canvas
  2643. var imageData = context.createImageData(width, height);
  2644. imageData.data.set(data);
  2645. context.putImageData(imageData, 0, 0);
  2646. var base64Image = screenshotCanvas.toDataURL();
  2647. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  2648. if (("download" in document.createElement("a"))) {
  2649. var a = window.document.createElement("a");
  2650. a.href = base64Image;
  2651. var date = new Date();
  2652. var stringDate = date.getFullYear() + "/" + date.getMonth() + "/" + date.getDate() + "-" + date.getHours() + ":" + date.getMinutes();
  2653. a.setAttribute("download", "screenshot-" + stringDate + ".png");
  2654. window.document.body.appendChild(a);
  2655. a.addEventListener("click", function () {
  2656. a.parentElement.removeChild(a);
  2657. });
  2658. a.click();
  2659. //Or opening a new tab with the image if it is not possible to automatically start download.
  2660. } else {
  2661. var newWindow = window.open("");
  2662. var img = newWindow.document.createElement("img");
  2663. img.src = base64Image;
  2664. newWindow.document.body.appendChild(img);
  2665. }
  2666. };
  2667. texture.render(true);
  2668. texture.dispose();
  2669. if (previousCamera) {
  2670. scene.activeCamera = previousCamera;
  2671. }
  2672. };
  2673. // XHR response validator for local file scenario
  2674. Tools.ValidateXHRData = function (xhr, dataType) {
  2675. if (typeof dataType === "undefined") { dataType = 7; }
  2676. try {
  2677. if (dataType & 1) {
  2678. if (xhr.responseText && xhr.responseText.length > 0) {
  2679. return true;
  2680. } else if (dataType === 1) {
  2681. return false;
  2682. }
  2683. }
  2684. if (dataType & 2) {
  2685. // Check header width and height since there is no "TGA" magic number
  2686. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  2687. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  2688. return true;
  2689. } else if (dataType === 2) {
  2690. return false;
  2691. }
  2692. }
  2693. if (dataType & 4) {
  2694. // Check for the "DDS" magic number
  2695. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  2696. if (ddsHeader[0] == 68 && ddsHeader[1] == 68 && ddsHeader[2] == 83) {
  2697. return true;
  2698. } else {
  2699. return false;
  2700. }
  2701. }
  2702. } catch (e) {
  2703. // Global protection
  2704. }
  2705. return false;
  2706. };
  2707. Object.defineProperty(Tools, "NoneLogLevel", {
  2708. get: function () {
  2709. return Tools._NoneLogLevel;
  2710. },
  2711. enumerable: true,
  2712. configurable: true
  2713. });
  2714. Object.defineProperty(Tools, "MessageLogLevel", {
  2715. get: function () {
  2716. return Tools._MessageLogLevel;
  2717. },
  2718. enumerable: true,
  2719. configurable: true
  2720. });
  2721. Object.defineProperty(Tools, "WarningLogLevel", {
  2722. get: function () {
  2723. return Tools._WarningLogLevel;
  2724. },
  2725. enumerable: true,
  2726. configurable: true
  2727. });
  2728. Object.defineProperty(Tools, "ErrorLogLevel", {
  2729. get: function () {
  2730. return Tools._ErrorLogLevel;
  2731. },
  2732. enumerable: true,
  2733. configurable: true
  2734. });
  2735. Object.defineProperty(Tools, "AllLogLevel", {
  2736. get: function () {
  2737. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  2738. },
  2739. enumerable: true,
  2740. configurable: true
  2741. });
  2742. Tools._AddLogEntry = function (entry) {
  2743. Tools._LogCache = entry + Tools._LogCache;
  2744. if (Tools.OnNewCacheEntry) {
  2745. Tools.OnNewCacheEntry(entry);
  2746. }
  2747. };
  2748. Tools._FormatMessage = function (message) {
  2749. var padStr = function (i) {
  2750. return (i < 10) ? "0" + i : "" + i;
  2751. };
  2752. var date = new Date();
  2753. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  2754. };
  2755. Tools._LogDisabled = function (message) {
  2756. // nothing to do
  2757. };
  2758. Tools._LogEnabled = function (message) {
  2759. var formattedMessage = Tools._FormatMessage(message);
  2760. console.log("BJS - " + formattedMessage);
  2761. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  2762. Tools._AddLogEntry(entry);
  2763. };
  2764. Tools._WarnDisabled = function (message) {
  2765. // nothing to do
  2766. };
  2767. Tools._WarnEnabled = function (message) {
  2768. var formattedMessage = Tools._FormatMessage(message);
  2769. console.warn("BJS - " + formattedMessage);
  2770. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  2771. Tools._AddLogEntry(entry);
  2772. };
  2773. Tools._ErrorDisabled = function (message) {
  2774. // nothing to do
  2775. };
  2776. Tools._ErrorEnabled = function (message) {
  2777. var formattedMessage = Tools._FormatMessage(message);
  2778. console.error("BJS - " + formattedMessage);
  2779. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  2780. Tools._AddLogEntry(entry);
  2781. };
  2782. Object.defineProperty(Tools, "LogCache", {
  2783. get: function () {
  2784. return Tools._LogCache;
  2785. },
  2786. enumerable: true,
  2787. configurable: true
  2788. });
  2789. Object.defineProperty(Tools, "LogLevels", {
  2790. set: function (level) {
  2791. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  2792. Tools.Log = Tools._LogEnabled;
  2793. } else {
  2794. Tools.Log = Tools._LogDisabled;
  2795. }
  2796. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  2797. Tools.Warn = Tools._WarnEnabled;
  2798. } else {
  2799. Tools.Warn = Tools._WarnDisabled;
  2800. }
  2801. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  2802. Tools.Error = Tools._ErrorEnabled;
  2803. } else {
  2804. Tools.Error = Tools._ErrorDisabled;
  2805. }
  2806. },
  2807. enumerable: true,
  2808. configurable: true
  2809. });
  2810. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  2811. get: function () {
  2812. return Tools._PerformanceNoneLogLevel;
  2813. },
  2814. enumerable: true,
  2815. configurable: true
  2816. });
  2817. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  2818. get: function () {
  2819. return Tools._PerformanceUserMarkLogLevel;
  2820. },
  2821. enumerable: true,
  2822. configurable: true
  2823. });
  2824. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  2825. get: function () {
  2826. return Tools._PerformanceConsoleLogLevel;
  2827. },
  2828. enumerable: true,
  2829. configurable: true
  2830. });
  2831. Object.defineProperty(Tools, "PerformanceLogLevel", {
  2832. set: function (level) {
  2833. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  2834. Tools.StartPerformanceCounter = Tools._StartUserMark;
  2835. Tools.EndPerformanceCounter = Tools._EndUserMark;
  2836. return;
  2837. }
  2838. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  2839. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  2840. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  2841. return;
  2842. }
  2843. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  2844. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  2845. },
  2846. enumerable: true,
  2847. configurable: true
  2848. });
  2849. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  2850. };
  2851. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  2852. };
  2853. Tools._StartUserMark = function (counterName, condition) {
  2854. if (typeof condition === "undefined") { condition = true; }
  2855. if (!condition || !Tools._performance.mark) {
  2856. return;
  2857. }
  2858. Tools._performance.mark(counterName + "-Begin");
  2859. };
  2860. Tools._EndUserMark = function (counterName, condition) {
  2861. if (typeof condition === "undefined") { condition = true; }
  2862. if (!condition || !Tools._performance.mark) {
  2863. return;
  2864. }
  2865. Tools._performance.mark(counterName + "-End");
  2866. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  2867. };
  2868. Tools._StartPerformanceConsole = function (counterName, condition) {
  2869. if (typeof condition === "undefined") { condition = true; }
  2870. if (!condition) {
  2871. return;
  2872. }
  2873. Tools._StartUserMark(counterName, condition);
  2874. if (console.time) {
  2875. console.time(counterName);
  2876. }
  2877. };
  2878. Tools._EndPerformanceConsole = function (counterName, condition) {
  2879. if (typeof condition === "undefined") { condition = true; }
  2880. if (!condition) {
  2881. return;
  2882. }
  2883. Tools._EndUserMark(counterName, condition);
  2884. if (console.time) {
  2885. console.timeEnd(counterName);
  2886. }
  2887. };
  2888. Object.defineProperty(Tools, "Now", {
  2889. get: function () {
  2890. if (window.performance && window.performance.now) {
  2891. return window.performance.now();
  2892. }
  2893. return new Date().getTime();
  2894. },
  2895. enumerable: true,
  2896. configurable: true
  2897. });
  2898. // Deprecated
  2899. Tools.GetFps = function () {
  2900. Tools.Warn("Tools.GetFps() is deprecated. Please use engine.getFps() instead");
  2901. return 0;
  2902. };
  2903. Tools.BaseUrl = "";
  2904. Tools.GetExponantOfTwo = function (value, max) {
  2905. var count = 1;
  2906. do {
  2907. count *= 2;
  2908. } while(count < value);
  2909. if (count > max)
  2910. count = max;
  2911. return count;
  2912. };
  2913. Tools._NoneLogLevel = 0;
  2914. Tools._MessageLogLevel = 1;
  2915. Tools._WarningLogLevel = 2;
  2916. Tools._ErrorLogLevel = 4;
  2917. Tools._LogCache = "";
  2918. Tools.Log = Tools._LogEnabled;
  2919. Tools.Warn = Tools._WarnEnabled;
  2920. Tools.Error = Tools._ErrorEnabled;
  2921. Tools._PerformanceNoneLogLevel = 0;
  2922. Tools._PerformanceUserMarkLogLevel = 1;
  2923. Tools._PerformanceConsoleLogLevel = 2;
  2924. Tools._performance = window.performance;
  2925. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  2926. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  2927. return Tools;
  2928. })();
  2929. BABYLON.Tools = Tools;
  2930. })(BABYLON || (BABYLON = {}));
  2931. //# sourceMappingURL=babylon.tools.js.map
  2932. var BABYLON;
  2933. (function (BABYLON) {
  2934. var _DepthCullingState = (function () {
  2935. function _DepthCullingState() {
  2936. this._isDepthTestDirty = false;
  2937. this._isDepthMaskDirty = false;
  2938. this._isDepthFuncDirty = false;
  2939. this._isCullFaceDirty = false;
  2940. this._isCullDirty = false;
  2941. }
  2942. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  2943. get: function () {
  2944. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty;
  2945. },
  2946. enumerable: true,
  2947. configurable: true
  2948. });
  2949. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  2950. get: function () {
  2951. return this._cullFace;
  2952. },
  2953. set: function (value) {
  2954. if (this._cullFace === value) {
  2955. return;
  2956. }
  2957. this._cullFace = value;
  2958. this._isCullFaceDirty = true;
  2959. },
  2960. enumerable: true,
  2961. configurable: true
  2962. });
  2963. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  2964. get: function () {
  2965. return this._cull;
  2966. },
  2967. set: function (value) {
  2968. if (this._cull === value) {
  2969. return;
  2970. }
  2971. this._cull = value;
  2972. this._isCullDirty = true;
  2973. },
  2974. enumerable: true,
  2975. configurable: true
  2976. });
  2977. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  2978. get: function () {
  2979. return this._depthFunc;
  2980. },
  2981. set: function (value) {
  2982. if (this._depthFunc === value) {
  2983. return;
  2984. }
  2985. this._depthFunc = value;
  2986. this._isDepthFuncDirty = true;
  2987. },
  2988. enumerable: true,
  2989. configurable: true
  2990. });
  2991. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  2992. get: function () {
  2993. return this._depthMask;
  2994. },
  2995. set: function (value) {
  2996. if (this._depthMask === value) {
  2997. return;
  2998. }
  2999. this._depthMask = value;
  3000. this._isDepthMaskDirty = true;
  3001. },
  3002. enumerable: true,
  3003. configurable: true
  3004. });
  3005. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  3006. get: function () {
  3007. return this._depthTest;
  3008. },
  3009. set: function (value) {
  3010. if (this._depthTest === value) {
  3011. return;
  3012. }
  3013. this._depthTest = value;
  3014. this._isDepthTestDirty = true;
  3015. },
  3016. enumerable: true,
  3017. configurable: true
  3018. });
  3019. _DepthCullingState.prototype.reset = function () {
  3020. this._depthMask = true;
  3021. this._depthTest = true;
  3022. this._depthFunc = null;
  3023. this._cull = null;
  3024. this._cullFace = null;
  3025. this._isDepthTestDirty = true;
  3026. this._isDepthMaskDirty = true;
  3027. this._isDepthFuncDirty = false;
  3028. this._isCullFaceDirty = false;
  3029. this._isCullDirty = false;
  3030. };
  3031. _DepthCullingState.prototype.apply = function (gl) {
  3032. if (!this.isDirty) {
  3033. return;
  3034. }
  3035. // Cull
  3036. if (this._isCullDirty) {
  3037. if (this.cull === true) {
  3038. gl.enable(gl.CULL_FACE);
  3039. } else if (this.cull === false) {
  3040. gl.disable(gl.CULL_FACE);
  3041. }
  3042. this._isCullDirty = false;
  3043. }
  3044. // Cull face
  3045. if (this._isCullFaceDirty) {
  3046. gl.cullFace(this.cullFace);
  3047. this._isCullFaceDirty = false;
  3048. }
  3049. // Depth mask
  3050. if (this._isDepthMaskDirty) {
  3051. gl.depthMask(this.depthMask);
  3052. this._isDepthMaskDirty = false;
  3053. }
  3054. // Depth test
  3055. if (this._isDepthTestDirty) {
  3056. if (this.depthTest === true) {
  3057. gl.enable(gl.DEPTH_TEST);
  3058. } else if (this.depthTest === false) {
  3059. gl.disable(gl.DEPTH_TEST);
  3060. }
  3061. this._isDepthTestDirty = false;
  3062. }
  3063. // Depth func
  3064. if (this._isDepthFuncDirty) {
  3065. gl.depthFunc(this.depthFunc);
  3066. this._isDepthFuncDirty = false;
  3067. }
  3068. };
  3069. return _DepthCullingState;
  3070. })();
  3071. BABYLON._DepthCullingState = _DepthCullingState;
  3072. var _AlphaState = (function () {
  3073. function _AlphaState() {
  3074. this._isAlphaBlendDirty = false;
  3075. this._isBlendFunctionParametersDirty = false;
  3076. this._alphaBlend = false;
  3077. this._blendFunctionParameters = new Array(4);
  3078. }
  3079. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  3080. get: function () {
  3081. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  3082. },
  3083. enumerable: true,
  3084. configurable: true
  3085. });
  3086. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  3087. get: function () {
  3088. return this._alphaBlend;
  3089. },
  3090. set: function (value) {
  3091. if (this._alphaBlend === value) {
  3092. return;
  3093. }
  3094. this._alphaBlend = value;
  3095. this._isAlphaBlendDirty = true;
  3096. },
  3097. enumerable: true,
  3098. configurable: true
  3099. });
  3100. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  3101. if (this._blendFunctionParameters[0] === value0 && this._blendFunctionParameters[1] === value1 && this._blendFunctionParameters[2] === value2 && this._blendFunctionParameters[3] === value3) {
  3102. return;
  3103. }
  3104. this._blendFunctionParameters[0] = value0;
  3105. this._blendFunctionParameters[1] = value1;
  3106. this._blendFunctionParameters[2] = value2;
  3107. this._blendFunctionParameters[3] = value3;
  3108. this._isBlendFunctionParametersDirty = true;
  3109. };
  3110. _AlphaState.prototype.reset = function () {
  3111. this._alphaBlend = false;
  3112. this._blendFunctionParameters[0] = null;
  3113. this._blendFunctionParameters[1] = null;
  3114. this._blendFunctionParameters[2] = null;
  3115. this._blendFunctionParameters[3] = null;
  3116. this._isAlphaBlendDirty = true;
  3117. this._isBlendFunctionParametersDirty = false;
  3118. };
  3119. _AlphaState.prototype.apply = function (gl) {
  3120. if (!this.isDirty) {
  3121. return;
  3122. }
  3123. // Alpha blend
  3124. if (this._isAlphaBlendDirty) {
  3125. if (this._alphaBlend === true) {
  3126. gl.enable(gl.BLEND);
  3127. } else if (this._alphaBlend === false) {
  3128. gl.disable(gl.BLEND);
  3129. }
  3130. this._isAlphaBlendDirty = false;
  3131. }
  3132. // Alpha function
  3133. if (this._isBlendFunctionParametersDirty) {
  3134. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  3135. this._isBlendFunctionParametersDirty = false;
  3136. }
  3137. };
  3138. return _AlphaState;
  3139. })();
  3140. BABYLON._AlphaState = _AlphaState;
  3141. var compileShader = function (gl, source, type, defines) {
  3142. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  3143. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  3144. gl.compileShader(shader);
  3145. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  3146. throw new Error(gl.getShaderInfoLog(shader));
  3147. }
  3148. return shader;
  3149. };
  3150. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  3151. var magFilter = gl.NEAREST;
  3152. var minFilter = gl.NEAREST;
  3153. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  3154. magFilter = gl.LINEAR;
  3155. if (generateMipMaps) {
  3156. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  3157. } else {
  3158. minFilter = gl.LINEAR;
  3159. }
  3160. } else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  3161. magFilter = gl.LINEAR;
  3162. if (generateMipMaps) {
  3163. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  3164. } else {
  3165. minFilter = gl.LINEAR;
  3166. }
  3167. } else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  3168. magFilter = gl.NEAREST;
  3169. if (generateMipMaps) {
  3170. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  3171. } else {
  3172. minFilter = gl.NEAREST;
  3173. }
  3174. }
  3175. return {
  3176. min: minFilter,
  3177. mag: magFilter
  3178. };
  3179. };
  3180. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  3181. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  3182. var engine = scene.getEngine();
  3183. var potWidth = BABYLON.Tools.GetExponantOfTwo(width, engine.getCaps().maxTextureSize);
  3184. var potHeight = BABYLON.Tools.GetExponantOfTwo(height, engine.getCaps().maxTextureSize);
  3185. gl.bindTexture(gl.TEXTURE_2D, texture);
  3186. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  3187. processFunction(potWidth, potHeight);
  3188. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  3189. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  3190. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  3191. if (!noMipmap && !isCompressed) {
  3192. gl.generateMipmap(gl.TEXTURE_2D);
  3193. }
  3194. gl.bindTexture(gl.TEXTURE_2D, null);
  3195. engine._activeTexturesCache = [];
  3196. texture._baseWidth = width;
  3197. texture._baseHeight = height;
  3198. texture._width = potWidth;
  3199. texture._height = potHeight;
  3200. texture.isReady = true;
  3201. texture.samplingMode = samplingMode;
  3202. scene._removePendingData(texture);
  3203. };
  3204. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  3205. var img;
  3206. var onload = function () {
  3207. loadedImages[index] = img;
  3208. loadedImages._internalCount++;
  3209. scene._removePendingData(img);
  3210. if (loadedImages._internalCount == 6) {
  3211. onfinish(loadedImages);
  3212. }
  3213. };
  3214. var onerror = function () {
  3215. scene._removePendingData(img);
  3216. };
  3217. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  3218. scene._addPendingData(img);
  3219. };
  3220. var cascadeLoad = function (rootUrl, scene, onfinish, extensions) {
  3221. var loadedImages = [];
  3222. loadedImages._internalCount = 0;
  3223. for (var index = 0; index < 6; index++) {
  3224. partialLoad(rootUrl + extensions[index], index, loadedImages, scene, onfinish);
  3225. }
  3226. };
  3227. var EngineCapabilities = (function () {
  3228. function EngineCapabilities() {
  3229. }
  3230. return EngineCapabilities;
  3231. })();
  3232. BABYLON.EngineCapabilities = EngineCapabilities;
  3233. var Engine = (function () {
  3234. function Engine(canvas, antialias, options) {
  3235. var _this = this;
  3236. // Public members
  3237. this.isFullscreen = false;
  3238. this.isPointerLock = false;
  3239. this.cullBackFaces = true;
  3240. this.renderEvenInBackground = true;
  3241. this.scenes = new Array();
  3242. this._windowIsBackground = false;
  3243. this._loadingDivBackgroundColor = "black";
  3244. this._drawCalls = 0;
  3245. this._renderingQueueLaunched = false;
  3246. this._activeRenderLoops = [];
  3247. // FPS
  3248. this.fpsRange = 60;
  3249. this.previousFramesDuration = [];
  3250. this.fps = 60;
  3251. this.deltaTime = 0;
  3252. // States
  3253. this._depthCullingState = new _DepthCullingState();
  3254. this._alphaState = new _AlphaState();
  3255. this._alphaMode = Engine.ALPHA_DISABLE;
  3256. // Cache
  3257. this._loadedTexturesCache = new Array();
  3258. this._activeTexturesCache = new Array();
  3259. this._compiledEffects = {};
  3260. this._uintIndicesCurrentlySet = false;
  3261. this._renderingCanvas = canvas;
  3262. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  3263. options = options || {};
  3264. options.antialias = antialias;
  3265. try {
  3266. this._gl = canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options);
  3267. } catch (e) {
  3268. throw new Error("WebGL not supported");
  3269. }
  3270. if (!this._gl) {
  3271. throw new Error("WebGL not supported");
  3272. }
  3273. this._onBlur = function () {
  3274. _this._windowIsBackground = true;
  3275. };
  3276. this._onFocus = function () {
  3277. _this._windowIsBackground = false;
  3278. };
  3279. window.addEventListener("blur", this._onBlur);
  3280. window.addEventListener("focus", this._onFocus);
  3281. // Textures
  3282. this._workingCanvas = document.createElement("canvas");
  3283. this._workingContext = this._workingCanvas.getContext("2d");
  3284. // Viewport
  3285. this._hardwareScalingLevel = 1.0 / (window.devicePixelRatio || 1.0);
  3286. this.resize();
  3287. // Caps
  3288. this._caps = new EngineCapabilities();
  3289. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  3290. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  3291. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  3292. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  3293. // Extensions
  3294. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  3295. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  3296. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  3297. 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');
  3298. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  3299. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  3300. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  3301. // Depth buffer
  3302. this.setDepthBuffer(true);
  3303. this.setDepthFunctionToLessOrEqual();
  3304. this.setDepthWrite(true);
  3305. // Fullscreen
  3306. this._onFullscreenChange = function () {
  3307. if (document.fullscreen !== undefined) {
  3308. _this.isFullscreen = document.fullscreen;
  3309. } else if (document.mozFullScreen !== undefined) {
  3310. _this.isFullscreen = document.mozFullScreen;
  3311. } else if (document.webkitIsFullScreen !== undefined) {
  3312. _this.isFullscreen = document.webkitIsFullScreen;
  3313. } else if (document.msIsFullScreen !== undefined) {
  3314. _this.isFullscreen = document.msIsFullScreen;
  3315. }
  3316. // Pointer lock
  3317. if (_this.isFullscreen && _this._pointerLockRequested) {
  3318. canvas.requestPointerLock = canvas.requestPointerLock || canvas.msRequestPointerLock || canvas.mozRequestPointerLock || canvas.webkitRequestPointerLock;
  3319. if (canvas.requestPointerLock) {
  3320. canvas.requestPointerLock();
  3321. }
  3322. }
  3323. };
  3324. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  3325. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  3326. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  3327. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  3328. // Pointer lock
  3329. this._onPointerLockChange = function () {
  3330. _this.isPointerLock = (document.mozPointerLockElement === canvas || document.webkitPointerLockElement === canvas || document.msPointerLockElement === canvas || document.pointerLockElement === canvas);
  3331. };
  3332. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  3333. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  3334. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  3335. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  3336. this._audioEngine = new BABYLON.AudioEngine();
  3337. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  3338. }
  3339. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  3340. get: function () {
  3341. return Engine._ALPHA_DISABLE;
  3342. },
  3343. enumerable: true,
  3344. configurable: true
  3345. });
  3346. Object.defineProperty(Engine, "ALPHA_ADD", {
  3347. get: function () {
  3348. return Engine._ALPHA_ADD;
  3349. },
  3350. enumerable: true,
  3351. configurable: true
  3352. });
  3353. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  3354. get: function () {
  3355. return Engine._ALPHA_COMBINE;
  3356. },
  3357. enumerable: true,
  3358. configurable: true
  3359. });
  3360. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  3361. get: function () {
  3362. return Engine._DELAYLOADSTATE_NONE;
  3363. },
  3364. enumerable: true,
  3365. configurable: true
  3366. });
  3367. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  3368. get: function () {
  3369. return Engine._DELAYLOADSTATE_LOADED;
  3370. },
  3371. enumerable: true,
  3372. configurable: true
  3373. });
  3374. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  3375. get: function () {
  3376. return Engine._DELAYLOADSTATE_LOADING;
  3377. },
  3378. enumerable: true,
  3379. configurable: true
  3380. });
  3381. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  3382. get: function () {
  3383. return Engine._DELAYLOADSTATE_NOTLOADED;
  3384. },
  3385. enumerable: true,
  3386. configurable: true
  3387. });
  3388. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  3389. get: function () {
  3390. return Engine._TEXTUREFORMAT_ALPHA;
  3391. },
  3392. enumerable: true,
  3393. configurable: true
  3394. });
  3395. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  3396. get: function () {
  3397. return Engine._TEXTUREFORMAT_LUMINANCE;
  3398. },
  3399. enumerable: true,
  3400. configurable: true
  3401. });
  3402. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  3403. get: function () {
  3404. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  3405. },
  3406. enumerable: true,
  3407. configurable: true
  3408. });
  3409. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  3410. get: function () {
  3411. return Engine._TEXTUREFORMAT_RGB;
  3412. },
  3413. enumerable: true,
  3414. configurable: true
  3415. });
  3416. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  3417. get: function () {
  3418. return Engine._TEXTUREFORMAT_RGBA;
  3419. },
  3420. enumerable: true,
  3421. configurable: true
  3422. });
  3423. Object.defineProperty(Engine, "Version", {
  3424. get: function () {
  3425. return "2.0.0";
  3426. },
  3427. enumerable: true,
  3428. configurable: true
  3429. });
  3430. Engine.prototype.getAudioEngine = function () {
  3431. return this._audioEngine;
  3432. };
  3433. Engine.prototype.getAspectRatio = function (camera) {
  3434. var viewport = camera.viewport;
  3435. return (this.getRenderWidth() * viewport.width) / (this.getRenderHeight() * viewport.height);
  3436. };
  3437. Engine.prototype.getRenderWidth = function () {
  3438. if (this._currentRenderTarget) {
  3439. return this._currentRenderTarget._width;
  3440. }
  3441. return this._renderingCanvas.width;
  3442. };
  3443. Engine.prototype.getRenderHeight = function () {
  3444. if (this._currentRenderTarget) {
  3445. return this._currentRenderTarget._height;
  3446. }
  3447. return this._renderingCanvas.height;
  3448. };
  3449. Engine.prototype.getRenderingCanvas = function () {
  3450. return this._renderingCanvas;
  3451. };
  3452. Engine.prototype.getRenderingCanvasClientRect = function () {
  3453. return this._renderingCanvas.getBoundingClientRect();
  3454. };
  3455. Engine.prototype.setHardwareScalingLevel = function (level) {
  3456. this._hardwareScalingLevel = level;
  3457. this.resize();
  3458. };
  3459. Engine.prototype.getHardwareScalingLevel = function () {
  3460. return this._hardwareScalingLevel;
  3461. };
  3462. Engine.prototype.getLoadedTexturesCache = function () {
  3463. return this._loadedTexturesCache;
  3464. };
  3465. Engine.prototype.getCaps = function () {
  3466. return this._caps;
  3467. };
  3468. Object.defineProperty(Engine.prototype, "drawCalls", {
  3469. get: function () {
  3470. return this._drawCalls;
  3471. },
  3472. enumerable: true,
  3473. configurable: true
  3474. });
  3475. // Methods
  3476. Engine.prototype.resetDrawCalls = function () {
  3477. this._drawCalls = 0;
  3478. };
  3479. Engine.prototype.setDepthFunctionToGreater = function () {
  3480. this._depthCullingState.depthFunc = this._gl.GREATER;
  3481. };
  3482. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  3483. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  3484. };
  3485. Engine.prototype.setDepthFunctionToLess = function () {
  3486. this._depthCullingState.depthFunc = this._gl.LESS;
  3487. };
  3488. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  3489. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  3490. };
  3491. Engine.prototype.stopRenderLoop = function (renderFunction) {
  3492. if (!renderFunction) {
  3493. this._activeRenderLoops = [];
  3494. return;
  3495. }
  3496. var index = this._activeRenderLoops.indexOf(renderFunction);
  3497. if (index >= 0) {
  3498. this._activeRenderLoops.splice(index, 1);
  3499. }
  3500. };
  3501. Engine.prototype._renderLoop = function () {
  3502. var _this = this;
  3503. var shouldRender = true;
  3504. if (!this.renderEvenInBackground && this._windowIsBackground) {
  3505. shouldRender = false;
  3506. }
  3507. if (shouldRender) {
  3508. // Start new frame
  3509. this.beginFrame();
  3510. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  3511. var renderFunction = this._activeRenderLoops[index];
  3512. renderFunction();
  3513. }
  3514. // Present
  3515. this.endFrame();
  3516. }
  3517. if (this._activeRenderLoops.length > 0) {
  3518. // Register new frame
  3519. BABYLON.Tools.QueueNewFrame(function () {
  3520. _this._renderLoop();
  3521. });
  3522. } else {
  3523. this._renderingQueueLaunched = false;
  3524. }
  3525. };
  3526. Engine.prototype.runRenderLoop = function (renderFunction) {
  3527. var _this = this;
  3528. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  3529. return;
  3530. }
  3531. this._activeRenderLoops.push(renderFunction);
  3532. if (!this._renderingQueueLaunched) {
  3533. this._renderingQueueLaunched = true;
  3534. BABYLON.Tools.QueueNewFrame(function () {
  3535. _this._renderLoop();
  3536. });
  3537. }
  3538. };
  3539. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  3540. if (this.isFullscreen) {
  3541. BABYLON.Tools.ExitFullscreen();
  3542. } else {
  3543. this._pointerLockRequested = requestPointerLock;
  3544. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  3545. }
  3546. };
  3547. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  3548. this.applyStates();
  3549. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  3550. if (this._depthCullingState.depthMask) {
  3551. this._gl.clearDepth(1.0);
  3552. }
  3553. var mode = 0;
  3554. if (backBuffer)
  3555. mode |= this._gl.COLOR_BUFFER_BIT;
  3556. if (depthStencil && this._depthCullingState.depthMask)
  3557. mode |= this._gl.DEPTH_BUFFER_BIT;
  3558. this._gl.clear(mode);
  3559. };
  3560. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  3561. var width = requiredWidth || this._renderingCanvas.width;
  3562. var height = requiredHeight || this._renderingCanvas.height;
  3563. var x = viewport.x || 0;
  3564. var y = viewport.y || 0;
  3565. this._cachedViewport = viewport;
  3566. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  3567. };
  3568. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  3569. this._cachedViewport = null;
  3570. this._gl.viewport(x, y, width, height);
  3571. };
  3572. Engine.prototype.beginFrame = function () {
  3573. this._measureFps();
  3574. };
  3575. Engine.prototype.endFrame = function () {
  3576. this.flushFramebuffer();
  3577. };
  3578. Engine.prototype.resize = function () {
  3579. this.setSize(this._renderingCanvas.clientWidth / this._hardwareScalingLevel, this._renderingCanvas.clientHeight / this._hardwareScalingLevel);
  3580. };
  3581. Engine.prototype.setSize = function (width, height) {
  3582. this._renderingCanvas.width = width;
  3583. this._renderingCanvas.height = height;
  3584. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  3585. };
  3586. Engine.prototype.bindFramebuffer = function (texture) {
  3587. this._currentRenderTarget = texture;
  3588. var gl = this._gl;
  3589. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  3590. this._gl.viewport(0, 0, texture._width, texture._height);
  3591. this.wipeCaches();
  3592. };
  3593. Engine.prototype.unBindFramebuffer = function (texture) {
  3594. this._currentRenderTarget = null;
  3595. if (texture.generateMipMaps) {
  3596. var gl = this._gl;
  3597. gl.bindTexture(gl.TEXTURE_2D, texture);
  3598. gl.generateMipmap(gl.TEXTURE_2D);
  3599. gl.bindTexture(gl.TEXTURE_2D, null);
  3600. }
  3601. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  3602. };
  3603. Engine.prototype.flushFramebuffer = function () {
  3604. // this._gl.flush();
  3605. };
  3606. Engine.prototype.restoreDefaultFramebuffer = function () {
  3607. this._currentRenderTarget = null;
  3608. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  3609. this.setViewport(this._cachedViewport);
  3610. this.wipeCaches();
  3611. };
  3612. // VBOs
  3613. Engine.prototype._resetVertexBufferBinding = function () {
  3614. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  3615. this._cachedVertexBuffers = null;
  3616. };
  3617. Engine.prototype.createVertexBuffer = function (vertices) {
  3618. var vbo = this._gl.createBuffer();
  3619. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  3620. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  3621. this._resetVertexBufferBinding();
  3622. vbo.references = 1;
  3623. return vbo;
  3624. };
  3625. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  3626. var vbo = this._gl.createBuffer();
  3627. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  3628. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  3629. this._resetVertexBufferBinding();
  3630. vbo.references = 1;
  3631. return vbo;
  3632. };
  3633. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset) {
  3634. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  3635. if (offset === undefined) {
  3636. offset = 0;
  3637. }
  3638. if (vertices instanceof Float32Array) {
  3639. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  3640. } else {
  3641. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  3642. }
  3643. this._resetVertexBufferBinding();
  3644. };
  3645. Engine.prototype._resetIndexBufferBinding = function () {
  3646. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  3647. this._cachedIndexBuffer = null;
  3648. };
  3649. Engine.prototype.createIndexBuffer = function (indices) {
  3650. var vbo = this._gl.createBuffer();
  3651. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  3652. // Check for 32 bits indices
  3653. var arrayBuffer;
  3654. var need32Bits = false;
  3655. if (this._caps.uintIndices) {
  3656. for (var index = 0; index < indices.length; index++) {
  3657. if (indices[index] > 65535) {
  3658. need32Bits = true;
  3659. break;
  3660. }
  3661. }
  3662. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  3663. } else {
  3664. arrayBuffer = new Uint16Array(indices);
  3665. }
  3666. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  3667. this._resetIndexBufferBinding();
  3668. vbo.references = 1;
  3669. vbo.is32Bits = need32Bits;
  3670. return vbo;
  3671. };
  3672. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  3673. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  3674. this._cachedVertexBuffers = vertexBuffer;
  3675. this._cachedEffectForVertexBuffers = effect;
  3676. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  3677. var offset = 0;
  3678. for (var index = 0; index < vertexDeclaration.length; index++) {
  3679. var order = effect.getAttributeLocation(index);
  3680. if (order >= 0) {
  3681. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  3682. }
  3683. offset += vertexDeclaration[index] * 4;
  3684. }
  3685. }
  3686. if (this._cachedIndexBuffer !== indexBuffer) {
  3687. this._cachedIndexBuffer = indexBuffer;
  3688. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  3689. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  3690. }
  3691. };
  3692. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  3693. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  3694. this._cachedVertexBuffers = vertexBuffers;
  3695. this._cachedEffectForVertexBuffers = effect;
  3696. var attributes = effect.getAttributesNames();
  3697. for (var index = 0; index < attributes.length; index++) {
  3698. var order = effect.getAttributeLocation(index);
  3699. if (order >= 0) {
  3700. var vertexBuffer = vertexBuffers[attributes[index]];
  3701. if (!vertexBuffer) {
  3702. continue;
  3703. }
  3704. var stride = vertexBuffer.getStrideSize();
  3705. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  3706. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  3707. }
  3708. }
  3709. }
  3710. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  3711. this._cachedIndexBuffer = indexBuffer;
  3712. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  3713. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  3714. }
  3715. };
  3716. Engine.prototype._releaseBuffer = function (buffer) {
  3717. buffer.references--;
  3718. if (buffer.references === 0) {
  3719. this._gl.deleteBuffer(buffer);
  3720. return true;
  3721. }
  3722. return false;
  3723. };
  3724. Engine.prototype.createInstancesBuffer = function (capacity) {
  3725. var buffer = this._gl.createBuffer();
  3726. buffer.capacity = capacity;
  3727. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  3728. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  3729. return buffer;
  3730. };
  3731. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  3732. this._gl.deleteBuffer(buffer);
  3733. };
  3734. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  3735. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  3736. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  3737. for (var index = 0; index < 4; index++) {
  3738. var offsetLocation = offsetLocations[index];
  3739. this._gl.enableVertexAttribArray(offsetLocation);
  3740. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  3741. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  3742. }
  3743. };
  3744. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  3745. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  3746. for (var index = 0; index < 4; index++) {
  3747. var offsetLocation = offsetLocations[index];
  3748. this._gl.disableVertexAttribArray(offsetLocation);
  3749. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  3750. }
  3751. };
  3752. Engine.prototype.applyStates = function () {
  3753. this._depthCullingState.apply(this._gl);
  3754. this._alphaState.apply(this._gl);
  3755. };
  3756. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  3757. // Apply states
  3758. this.applyStates();
  3759. this._drawCalls++;
  3760. // Render
  3761. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  3762. if (instancesCount) {
  3763. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * 2, instancesCount);
  3764. return;
  3765. }
  3766. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * 2);
  3767. };
  3768. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  3769. // Apply states
  3770. this.applyStates();
  3771. this._drawCalls++;
  3772. if (instancesCount) {
  3773. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  3774. return;
  3775. }
  3776. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  3777. };
  3778. // Shaders
  3779. Engine.prototype._releaseEffect = function (effect) {
  3780. if (this._compiledEffects[effect._key]) {
  3781. delete this._compiledEffects[effect._key];
  3782. if (effect.getProgram()) {
  3783. this._gl.deleteProgram(effect.getProgram());
  3784. }
  3785. }
  3786. };
  3787. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  3788. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  3789. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  3790. var name = vertex + "+" + fragment + "@" + defines;
  3791. if (this._compiledEffects[name]) {
  3792. return this._compiledEffects[name];
  3793. }
  3794. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  3795. effect._key = name;
  3796. this._compiledEffects[name] = effect;
  3797. return effect;
  3798. };
  3799. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  3800. if (typeof uniformsNames === "undefined") { uniformsNames = []; }
  3801. if (typeof samplers === "undefined") { samplers = []; }
  3802. if (typeof defines === "undefined") { defines = ""; }
  3803. return this.createEffect({
  3804. vertex: "particles",
  3805. fragmentElement: fragmentName
  3806. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  3807. };
  3808. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  3809. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  3810. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  3811. var shaderProgram = this._gl.createProgram();
  3812. this._gl.attachShader(shaderProgram, vertexShader);
  3813. this._gl.attachShader(shaderProgram, fragmentShader);
  3814. this._gl.linkProgram(shaderProgram);
  3815. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  3816. if (!linked) {
  3817. var error = this._gl.getProgramInfoLog(shaderProgram);
  3818. if (error) {
  3819. throw new Error(error);
  3820. }
  3821. }
  3822. this._gl.deleteShader(vertexShader);
  3823. this._gl.deleteShader(fragmentShader);
  3824. return shaderProgram;
  3825. };
  3826. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  3827. var results = [];
  3828. for (var index = 0; index < uniformsNames.length; index++) {
  3829. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  3830. }
  3831. return results;
  3832. };
  3833. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  3834. var results = [];
  3835. for (var index = 0; index < attributesNames.length; index++) {
  3836. try {
  3837. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  3838. } catch (e) {
  3839. results.push(-1);
  3840. }
  3841. }
  3842. return results;
  3843. };
  3844. Engine.prototype.enableEffect = function (effect) {
  3845. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  3846. if (effect && effect.onBind) {
  3847. effect.onBind(effect);
  3848. }
  3849. return;
  3850. }
  3851. this._vertexAttribArrays = this._vertexAttribArrays || [];
  3852. // Use program
  3853. this._gl.useProgram(effect.getProgram());
  3854. for (var i in this._vertexAttribArrays) {
  3855. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  3856. continue;
  3857. }
  3858. this._vertexAttribArrays[i] = false;
  3859. this._gl.disableVertexAttribArray(i);
  3860. }
  3861. var attributesCount = effect.getAttributesCount();
  3862. for (var index = 0; index < attributesCount; index++) {
  3863. // Attributes
  3864. var order = effect.getAttributeLocation(index);
  3865. if (order >= 0) {
  3866. this._vertexAttribArrays[order] = true;
  3867. this._gl.enableVertexAttribArray(order);
  3868. }
  3869. }
  3870. this._currentEffect = effect;
  3871. if (effect.onBind) {
  3872. effect.onBind(effect);
  3873. }
  3874. };
  3875. Engine.prototype.setArray = function (uniform, array) {
  3876. if (!uniform)
  3877. return;
  3878. this._gl.uniform1fv(uniform, array);
  3879. };
  3880. Engine.prototype.setMatrices = function (uniform, matrices) {
  3881. if (!uniform)
  3882. return;
  3883. this._gl.uniformMatrix4fv(uniform, false, matrices);
  3884. };
  3885. Engine.prototype.setMatrix = function (uniform, matrix) {
  3886. if (!uniform)
  3887. return;
  3888. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  3889. };
  3890. Engine.prototype.setFloat = function (uniform, value) {
  3891. if (!uniform)
  3892. return;
  3893. this._gl.uniform1f(uniform, value);
  3894. };
  3895. Engine.prototype.setFloat2 = function (uniform, x, y) {
  3896. if (!uniform)
  3897. return;
  3898. this._gl.uniform2f(uniform, x, y);
  3899. };
  3900. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  3901. if (!uniform)
  3902. return;
  3903. this._gl.uniform3f(uniform, x, y, z);
  3904. };
  3905. Engine.prototype.setBool = function (uniform, bool) {
  3906. if (!uniform)
  3907. return;
  3908. this._gl.uniform1i(uniform, bool);
  3909. };
  3910. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  3911. if (!uniform)
  3912. return;
  3913. this._gl.uniform4f(uniform, x, y, z, w);
  3914. };
  3915. Engine.prototype.setColor3 = function (uniform, color3) {
  3916. if (!uniform)
  3917. return;
  3918. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  3919. };
  3920. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  3921. if (!uniform)
  3922. return;
  3923. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  3924. };
  3925. // States
  3926. Engine.prototype.setState = function (culling, force) {
  3927. // Culling
  3928. if (this._depthCullingState.cull !== culling || force) {
  3929. if (culling) {
  3930. this._depthCullingState.cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  3931. this._depthCullingState.cull = true;
  3932. } else {
  3933. this._depthCullingState.cull = false;
  3934. }
  3935. }
  3936. };
  3937. Engine.prototype.setDepthBuffer = function (enable) {
  3938. this._depthCullingState.depthTest = enable;
  3939. };
  3940. Engine.prototype.getDepthWrite = function () {
  3941. return this._depthCullingState.depthMask;
  3942. };
  3943. Engine.prototype.setDepthWrite = function (enable) {
  3944. this._depthCullingState.depthMask = enable;
  3945. };
  3946. Engine.prototype.setColorWrite = function (enable) {
  3947. this._gl.colorMask(enable, enable, enable, enable);
  3948. };
  3949. Engine.prototype.setAlphaMode = function (mode) {
  3950. switch (mode) {
  3951. case BABYLON.Engine.ALPHA_DISABLE:
  3952. this.setDepthWrite(true);
  3953. this._alphaState.alphaBlend = false;
  3954. break;
  3955. case BABYLON.Engine.ALPHA_COMBINE:
  3956. this.setDepthWrite(false);
  3957. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  3958. this._alphaState.alphaBlend = true;
  3959. break;
  3960. case BABYLON.Engine.ALPHA_ADD:
  3961. this.setDepthWrite(false);
  3962. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  3963. this._alphaState.alphaBlend = true;
  3964. break;
  3965. }
  3966. this._alphaMode = mode;
  3967. };
  3968. Engine.prototype.getAlphaMode = function () {
  3969. return this._alphaMode;
  3970. };
  3971. Engine.prototype.setAlphaTesting = function (enable) {
  3972. this._alphaTest = enable;
  3973. };
  3974. Engine.prototype.getAlphaTesting = function () {
  3975. return this._alphaTest;
  3976. };
  3977. // Textures
  3978. Engine.prototype.wipeCaches = function () {
  3979. this._activeTexturesCache = [];
  3980. this._currentEffect = null;
  3981. this._depthCullingState.reset();
  3982. this._alphaState.reset();
  3983. this._cachedVertexBuffers = null;
  3984. this._cachedIndexBuffer = null;
  3985. this._cachedEffectForVertexBuffers = null;
  3986. };
  3987. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  3988. var gl = this._gl;
  3989. gl.bindTexture(gl.TEXTURE_2D, texture);
  3990. var magFilter = gl.NEAREST;
  3991. var minFilter = gl.NEAREST;
  3992. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  3993. magFilter = gl.LINEAR;
  3994. minFilter = gl.LINEAR;
  3995. } else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  3996. magFilter = gl.LINEAR;
  3997. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  3998. }
  3999. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  4000. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  4001. gl.bindTexture(gl.TEXTURE_2D, null);
  4002. texture.samplingMode = samplingMode;
  4003. };
  4004. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  4005. var _this = this;
  4006. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  4007. if (typeof onLoad === "undefined") { onLoad = null; }
  4008. if (typeof onError === "undefined") { onError = null; }
  4009. if (typeof buffer === "undefined") { buffer = null; }
  4010. var texture = this._gl.createTexture();
  4011. var extension;
  4012. var fromData = false;
  4013. if (url.substr(0, 5) === "data:") {
  4014. fromData = true;
  4015. }
  4016. if (!fromData)
  4017. extension = url.substr(url.length - 4, 4).toLowerCase();
  4018. else {
  4019. var oldUrl = url;
  4020. fromData = oldUrl.split(':');
  4021. url = oldUrl;
  4022. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  4023. }
  4024. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  4025. var isTGA = (extension === ".tga");
  4026. scene._addPendingData(texture);
  4027. texture.url = url;
  4028. texture.noMipmap = noMipmap;
  4029. texture.references = 1;
  4030. this._loadedTexturesCache.push(texture);
  4031. var onerror = function () {
  4032. scene._removePendingData(texture);
  4033. if (onError) {
  4034. onError();
  4035. }
  4036. };
  4037. if (isTGA) {
  4038. var callback = function (arrayBuffer) {
  4039. var data = new Uint8Array(arrayBuffer);
  4040. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  4041. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  4042. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  4043. if (onLoad) {
  4044. onLoad();
  4045. }
  4046. }, samplingMode);
  4047. };
  4048. if (!(fromData instanceof Array))
  4049. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  4050. callback(arrayBuffer);
  4051. }, onerror, scene.database, true);
  4052. else
  4053. callback(buffer);
  4054. } else if (isDDS) {
  4055. callback = function (data) {
  4056. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  4057. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) == 1);
  4058. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  4059. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  4060. if (onLoad) {
  4061. onLoad();
  4062. }
  4063. }, samplingMode);
  4064. };
  4065. if (!(fromData instanceof Array))
  4066. BABYLON.Tools.LoadFile(url, function (data) {
  4067. callback(data);
  4068. }, onerror, scene.database, true);
  4069. else
  4070. callback(buffer);
  4071. } else {
  4072. var onload = function (img) {
  4073. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  4074. var isPot = (img.width == potWidth && img.height == potHeight);
  4075. if (!isPot) {
  4076. _this._workingCanvas.width = potWidth;
  4077. _this._workingCanvas.height = potHeight;
  4078. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  4079. }
  4080. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  4081. if (onLoad) {
  4082. onLoad();
  4083. }
  4084. }, samplingMode);
  4085. };
  4086. if (!(fromData instanceof Array))
  4087. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  4088. else
  4089. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  4090. }
  4091. return texture;
  4092. };
  4093. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode) {
  4094. var texture = this._gl.createTexture();
  4095. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4096. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  4097. // Format
  4098. var internalFormat = this._gl.RGBA;
  4099. switch (format) {
  4100. case Engine.TEXTUREFORMAT_ALPHA:
  4101. internalFormat = this._gl.ALPHA;
  4102. break;
  4103. case Engine.TEXTUREFORMAT_LUMINANCE:
  4104. internalFormat = this._gl.LUMINANCE;
  4105. break;
  4106. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  4107. internalFormat = this._gl.LUMINANCE_ALPHA;
  4108. break;
  4109. case Engine.TEXTUREFORMAT_RGB:
  4110. internalFormat = this._gl.RGB;
  4111. break;
  4112. case Engine.TEXTUREFORMAT_RGBA:
  4113. internalFormat = this._gl.RGBA;
  4114. break;
  4115. }
  4116. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, width, height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  4117. if (generateMipMaps) {
  4118. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  4119. }
  4120. // Filters
  4121. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  4122. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  4123. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  4124. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4125. this._activeTexturesCache = [];
  4126. texture._baseWidth = width;
  4127. texture._baseHeight = height;
  4128. texture._width = width;
  4129. texture._height = height;
  4130. texture.isReady = true;
  4131. texture.references = 1;
  4132. texture.samplingMode = samplingMode;
  4133. this._loadedTexturesCache.push(texture);
  4134. return texture;
  4135. };
  4136. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  4137. var texture = this._gl.createTexture();
  4138. width = BABYLON.Tools.GetExponantOfTwo(width, this._caps.maxTextureSize);
  4139. height = BABYLON.Tools.GetExponantOfTwo(height, this._caps.maxTextureSize);
  4140. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4141. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  4142. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  4143. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  4144. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4145. this._activeTexturesCache = [];
  4146. texture._baseWidth = width;
  4147. texture._baseHeight = height;
  4148. texture._width = width;
  4149. texture._height = height;
  4150. texture.isReady = false;
  4151. texture.generateMipMaps = generateMipMaps;
  4152. texture.references = 1;
  4153. texture.samplingMode = samplingMode;
  4154. this._loadedTexturesCache.push(texture);
  4155. return texture;
  4156. };
  4157. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  4158. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4159. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  4160. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  4161. if (texture.generateMipMaps) {
  4162. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  4163. }
  4164. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4165. this._activeTexturesCache = [];
  4166. texture.isReady = true;
  4167. };
  4168. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  4169. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4170. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  4171. // Scale the video if it is a NPOT using the current working canvas
  4172. if (video.videoWidth !== texture._width || video.videoHeight !== texture._height) {
  4173. if (!texture._workingCanvas) {
  4174. texture._workingCanvas = document.createElement("canvas");
  4175. texture._workingContext = texture._workingCanvas.getContext("2d");
  4176. texture._workingCanvas.width = texture._width;
  4177. texture._workingCanvas.height = texture._height;
  4178. }
  4179. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  4180. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  4181. } else {
  4182. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  4183. }
  4184. if (texture.generateMipMaps) {
  4185. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  4186. }
  4187. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4188. this._activeTexturesCache = [];
  4189. texture.isReady = true;
  4190. };
  4191. Engine.prototype.createRenderTargetTexture = function (size, options) {
  4192. // old version had a "generateMipMaps" arg instead of options.
  4193. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  4194. // in the same way, generateDepthBuffer is defaulted to true
  4195. var generateMipMaps = false;
  4196. var generateDepthBuffer = true;
  4197. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  4198. if (options !== undefined) {
  4199. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipmaps;
  4200. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  4201. if (options.samplingMode !== undefined) {
  4202. samplingMode = options.samplingMode;
  4203. }
  4204. }
  4205. var gl = this._gl;
  4206. var texture = gl.createTexture();
  4207. gl.bindTexture(gl.TEXTURE_2D, texture);
  4208. var width = size.width || size;
  4209. var height = size.height || size;
  4210. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  4211. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  4212. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  4213. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4214. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4215. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  4216. var depthBuffer;
  4217. // Create the depth buffer
  4218. if (generateDepthBuffer) {
  4219. depthBuffer = gl.createRenderbuffer();
  4220. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  4221. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  4222. }
  4223. // Create the framebuffer
  4224. var framebuffer = gl.createFramebuffer();
  4225. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  4226. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  4227. if (generateDepthBuffer) {
  4228. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  4229. }
  4230. // Unbind
  4231. gl.bindTexture(gl.TEXTURE_2D, null);
  4232. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  4233. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  4234. texture._framebuffer = framebuffer;
  4235. if (generateDepthBuffer) {
  4236. texture._depthBuffer = depthBuffer;
  4237. }
  4238. texture._width = width;
  4239. texture._height = height;
  4240. texture.isReady = true;
  4241. texture.generateMipMaps = generateMipMaps;
  4242. texture.references = 1;
  4243. texture.samplingMode = samplingMode;
  4244. this._activeTexturesCache = [];
  4245. this._loadedTexturesCache.push(texture);
  4246. return texture;
  4247. };
  4248. Engine.prototype.createCubeTexture = function (rootUrl, scene, extensions, noMipmap) {
  4249. var _this = this;
  4250. var gl = this._gl;
  4251. var texture = gl.createTexture();
  4252. texture.isCube = true;
  4253. texture.url = rootUrl;
  4254. texture.references = 1;
  4255. this._loadedTexturesCache.push(texture);
  4256. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  4257. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  4258. if (isDDS) {
  4259. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  4260. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  4261. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  4262. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  4263. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  4264. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  4265. if (!noMipmap && !info.isFourCC && info.mipmapCount == 1) {
  4266. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  4267. }
  4268. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  4269. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  4270. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4271. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4272. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  4273. _this._activeTexturesCache = [];
  4274. texture._width = info.width;
  4275. texture._height = info.height;
  4276. texture.isReady = true;
  4277. }, null, null, true);
  4278. } else {
  4279. cascadeLoad(rootUrl, scene, function (imgs) {
  4280. var width = BABYLON.Tools.GetExponantOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  4281. var height = width;
  4282. _this._workingCanvas.width = width;
  4283. _this._workingCanvas.height = height;
  4284. var faces = [
  4285. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  4286. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  4287. ];
  4288. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  4289. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  4290. for (var index = 0; index < faces.length; index++) {
  4291. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  4292. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  4293. }
  4294. if (!noMipmap) {
  4295. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  4296. }
  4297. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  4298. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  4299. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4300. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4301. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  4302. _this._activeTexturesCache = [];
  4303. texture._width = width;
  4304. texture._height = height;
  4305. texture.isReady = true;
  4306. }, extensions);
  4307. }
  4308. return texture;
  4309. };
  4310. Engine.prototype._releaseTexture = function (texture) {
  4311. var gl = this._gl;
  4312. if (texture._framebuffer) {
  4313. gl.deleteFramebuffer(texture._framebuffer);
  4314. }
  4315. if (texture._depthBuffer) {
  4316. gl.deleteRenderbuffer(texture._depthBuffer);
  4317. }
  4318. gl.deleteTexture(texture);
  4319. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  4320. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  4321. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4322. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  4323. this._activeTexturesCache[channel] = null;
  4324. }
  4325. var index = this._loadedTexturesCache.indexOf(texture);
  4326. if (index !== -1) {
  4327. this._loadedTexturesCache.splice(index, 1);
  4328. }
  4329. };
  4330. Engine.prototype.bindSamplers = function (effect) {
  4331. this._gl.useProgram(effect.getProgram());
  4332. var samplers = effect.getSamplers();
  4333. for (var index = 0; index < samplers.length; index++) {
  4334. var uniform = effect.getUniform(samplers[index]);
  4335. this._gl.uniform1i(uniform, index);
  4336. }
  4337. this._currentEffect = null;
  4338. };
  4339. Engine.prototype._bindTexture = function (channel, texture) {
  4340. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  4341. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4342. this._activeTexturesCache[channel] = null;
  4343. };
  4344. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  4345. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  4346. };
  4347. Engine.prototype.setTexture = function (channel, texture) {
  4348. if (channel < 0) {
  4349. return;
  4350. }
  4351. // Not ready?
  4352. if (!texture || !texture.isReady()) {
  4353. if (this._activeTexturesCache[channel] != null) {
  4354. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  4355. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4356. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  4357. this._activeTexturesCache[channel] = null;
  4358. }
  4359. return;
  4360. }
  4361. // Video
  4362. if (texture instanceof BABYLON.VideoTexture) {
  4363. if (texture.update()) {
  4364. this._activeTexturesCache[channel] = null;
  4365. }
  4366. } else if (texture.delayLoadState == BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  4367. texture.delayLoad();
  4368. return;
  4369. }
  4370. if (this._activeTexturesCache[channel] == texture) {
  4371. return;
  4372. }
  4373. this._activeTexturesCache[channel] = texture;
  4374. var internalTexture = texture.getInternalTexture();
  4375. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  4376. if (internalTexture.isCube) {
  4377. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  4378. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  4379. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  4380. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  4381. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  4382. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  4383. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  4384. }
  4385. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  4386. } else {
  4387. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  4388. if (internalTexture._cachedWrapU !== texture.wrapU) {
  4389. internalTexture._cachedWrapU = texture.wrapU;
  4390. switch (texture.wrapU) {
  4391. case BABYLON.Texture.WRAP_ADDRESSMODE:
  4392. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  4393. break;
  4394. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  4395. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  4396. break;
  4397. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  4398. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  4399. break;
  4400. }
  4401. }
  4402. if (internalTexture._cachedWrapV !== texture.wrapV) {
  4403. internalTexture._cachedWrapV = texture.wrapV;
  4404. switch (texture.wrapV) {
  4405. case BABYLON.Texture.WRAP_ADDRESSMODE:
  4406. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  4407. break;
  4408. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  4409. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  4410. break;
  4411. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  4412. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  4413. break;
  4414. }
  4415. }
  4416. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  4417. }
  4418. };
  4419. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  4420. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  4421. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== texture.anisotropicFilteringLevel) {
  4422. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(texture.anisotropicFilteringLevel, this._caps.maxAnisotropy));
  4423. texture._cachedAnisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  4424. }
  4425. };
  4426. Engine.prototype.readPixels = function (x, y, width, height) {
  4427. var data = new Uint8Array(height * width * 4);
  4428. this._gl.readPixels(0, 0, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  4429. return data;
  4430. };
  4431. // Dispose
  4432. Engine.prototype.dispose = function () {
  4433. this.hideLoadingUI();
  4434. this.stopRenderLoop();
  4435. while (this.scenes.length) {
  4436. this.scenes[0].dispose();
  4437. }
  4438. for (var name in this._compiledEffects) {
  4439. this._gl.deleteProgram(this._compiledEffects[name]._program);
  4440. }
  4441. for (var i in this._vertexAttribArrays) {
  4442. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  4443. continue;
  4444. }
  4445. this._gl.disableVertexAttribArray(i);
  4446. }
  4447. // Events
  4448. window.removeEventListener("blur", this._onBlur);
  4449. window.removeEventListener("focus", this._onFocus);
  4450. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  4451. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  4452. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  4453. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  4454. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  4455. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  4456. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  4457. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  4458. };
  4459. // Loading screen
  4460. Engine.prototype.displayLoadingUI = function () {
  4461. var _this = this;
  4462. this._loadingDiv = document.createElement("div");
  4463. this._loadingDiv.style.opacity = "0";
  4464. this._loadingDiv.style.transition = "opacity 1.5s ease";
  4465. // Loading text
  4466. this._loadingTextDiv = document.createElement("div");
  4467. this._loadingTextDiv.style.position = "absolute";
  4468. this._loadingTextDiv.style.left = "0";
  4469. this._loadingTextDiv.style.top = "50%";
  4470. this._loadingTextDiv.style.marginTop = "80px";
  4471. this._loadingTextDiv.style.width = "100%";
  4472. this._loadingTextDiv.style.height = "20px";
  4473. this._loadingTextDiv.style.fontFamily = "Arial";
  4474. this._loadingTextDiv.style.fontSize = "14px";
  4475. this._loadingTextDiv.style.color = "white";
  4476. this._loadingTextDiv.style.textAlign = "center";
  4477. this._loadingTextDiv.innerHTML = "Loading";
  4478. this._loadingDiv.appendChild(this._loadingTextDiv);
  4479. // Loading img
  4480. var imgBack = new Image();
  4481. 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==";
  4482. imgBack.style.position = "absolute";
  4483. imgBack.style.left = "50%";
  4484. imgBack.style.top = "50%";
  4485. imgBack.style.marginLeft = "-50px";
  4486. imgBack.style.marginTop = "-50px";
  4487. imgBack.style.transition = "transform 1.0s ease";
  4488. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  4489. var deg = 360;
  4490. var onTransitionEnd = function () {
  4491. deg += 360;
  4492. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  4493. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  4494. };
  4495. imgBack.addEventListener("transitionend", onTransitionEnd);
  4496. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  4497. this._loadingDiv.appendChild(imgBack);
  4498. // front image
  4499. var imgFront = new Image();
  4500. 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=";
  4501. imgFront.style.position = "absolute";
  4502. imgFront.style.left = "50%";
  4503. imgFront.style.top = "50%";
  4504. imgFront.style.marginLeft = "-50px";
  4505. imgFront.style.marginTop = "-50px";
  4506. this._loadingDiv.appendChild(imgFront);
  4507. // Resize
  4508. this._resizeLoadingUI = function () {
  4509. var canvasRect = _this.getRenderingCanvasClientRect();
  4510. _this._loadingDiv.style.position = "absolute";
  4511. _this._loadingDiv.style.left = canvasRect.left + "px";
  4512. _this._loadingDiv.style.top = canvasRect.top + "px";
  4513. _this._loadingDiv.style.width = canvasRect.width + "px";
  4514. _this._loadingDiv.style.height = canvasRect.height + "px";
  4515. };
  4516. this._resizeLoadingUI();
  4517. window.addEventListener("resize", this._resizeLoadingUI);
  4518. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  4519. document.body.appendChild(this._loadingDiv);
  4520. setTimeout(function () {
  4521. _this._loadingDiv.style.opacity = "1";
  4522. imgBack.style.transform = "rotateZ(360deg)";
  4523. imgBack.style.webkitTransform = "rotateZ(360deg)";
  4524. }, 0);
  4525. };
  4526. Object.defineProperty(Engine.prototype, "loadingUIText", {
  4527. set: function (text) {
  4528. if (!this._loadingDiv) {
  4529. return;
  4530. }
  4531. this._loadingTextDiv.innerHTML = text;
  4532. },
  4533. enumerable: true,
  4534. configurable: true
  4535. });
  4536. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  4537. get: function () {
  4538. return this._loadingDivBackgroundColor;
  4539. },
  4540. set: function (color) {
  4541. this._loadingDivBackgroundColor = color;
  4542. if (!this._loadingDiv) {
  4543. return;
  4544. }
  4545. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  4546. },
  4547. enumerable: true,
  4548. configurable: true
  4549. });
  4550. Engine.prototype.hideLoadingUI = function () {
  4551. var _this = this;
  4552. if (!this._loadingDiv) {
  4553. return;
  4554. }
  4555. var onTransitionEnd = function () {
  4556. if (!_this._loadingDiv) {
  4557. return;
  4558. }
  4559. document.body.removeChild(_this._loadingDiv);
  4560. window.removeEventListener("resize", _this._resizeLoadingUI);
  4561. _this._loadingDiv = null;
  4562. };
  4563. this._loadingDiv.style.opacity = "0";
  4564. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  4565. };
  4566. // FPS
  4567. Engine.prototype.getFps = function () {
  4568. return this.fps;
  4569. };
  4570. Engine.prototype.getDeltaTime = function () {
  4571. return this.deltaTime;
  4572. };
  4573. Engine.prototype._measureFps = function () {
  4574. this.previousFramesDuration.push(BABYLON.Tools.Now);
  4575. var length = this.previousFramesDuration.length;
  4576. if (length >= 2) {
  4577. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  4578. }
  4579. if (length >= this.fpsRange) {
  4580. if (length > this.fpsRange) {
  4581. this.previousFramesDuration.splice(0, 1);
  4582. length = this.previousFramesDuration.length;
  4583. }
  4584. var sum = 0;
  4585. for (var id = 0; id < length - 1; id++) {
  4586. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  4587. }
  4588. this.fps = 1000.0 / (sum / (length - 1));
  4589. }
  4590. };
  4591. // Statics
  4592. Engine.isSupported = function () {
  4593. try {
  4594. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  4595. if (navigator.isCocoonJS) {
  4596. return true;
  4597. }
  4598. var tempcanvas = document.createElement("canvas");
  4599. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  4600. return gl != null && !!window.WebGLRenderingContext;
  4601. } catch (e) {
  4602. return false;
  4603. }
  4604. };
  4605. Engine._ALPHA_DISABLE = 0;
  4606. Engine._ALPHA_ADD = 1;
  4607. Engine._ALPHA_COMBINE = 2;
  4608. Engine._DELAYLOADSTATE_NONE = 0;
  4609. Engine._DELAYLOADSTATE_LOADED = 1;
  4610. Engine._DELAYLOADSTATE_LOADING = 2;
  4611. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  4612. Engine._TEXTUREFORMAT_ALPHA = 0;
  4613. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  4614. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  4615. Engine._TEXTUREFORMAT_RGB = 4;
  4616. Engine._TEXTUREFORMAT_RGBA = 4;
  4617. Engine.Epsilon = 0.001;
  4618. Engine.CollisionsEpsilon = 0.001;
  4619. Engine.ShadersRepository = "Babylon/Shaders/";
  4620. return Engine;
  4621. })();
  4622. BABYLON.Engine = Engine;
  4623. })(BABYLON || (BABYLON = {}));
  4624. //# sourceMappingURL=babylon.engine.js.map
  4625. var BABYLON;
  4626. (function (BABYLON) {
  4627. var Node = (function () {
  4628. function Node(name, scene) {
  4629. this.state = "";
  4630. this.animations = new Array();
  4631. this._childrenFlag = -1;
  4632. this._isEnabled = true;
  4633. this._isReady = true;
  4634. this._currentRenderId = -1;
  4635. this.name = name;
  4636. this.id = name;
  4637. this._scene = scene;
  4638. this._initCache();
  4639. }
  4640. Node.prototype.getScene = function () {
  4641. return this._scene;
  4642. };
  4643. Node.prototype.getEngine = function () {
  4644. return this._scene.getEngine();
  4645. };
  4646. // override it in derived class
  4647. Node.prototype.getWorldMatrix = function () {
  4648. return BABYLON.Matrix.Identity();
  4649. };
  4650. // override it in derived class if you add new variables to the cache
  4651. // and call the parent class method
  4652. Node.prototype._initCache = function () {
  4653. this._cache = {};
  4654. this._cache.parent = undefined;
  4655. };
  4656. Node.prototype.updateCache = function (force) {
  4657. if (!force && this.isSynchronized())
  4658. return;
  4659. this._cache.parent = this.parent;
  4660. this._updateCache();
  4661. };
  4662. // override it in derived class if you add new variables to the cache
  4663. // and call the parent class method if !ignoreParentClass
  4664. Node.prototype._updateCache = function (ignoreParentClass) {
  4665. };
  4666. // override it in derived class if you add new variables to the cache
  4667. Node.prototype._isSynchronized = function () {
  4668. return true;
  4669. };
  4670. Node.prototype.isSynchronizedWithParent = function () {
  4671. return this.parent ? this.parent._currentRenderId <= this._currentRenderId : true;
  4672. };
  4673. Node.prototype.isSynchronized = function (updateCache) {
  4674. var check = this.hasNewParent();
  4675. check = check || !this.isSynchronizedWithParent();
  4676. check = check || !this._isSynchronized();
  4677. if (updateCache)
  4678. this.updateCache(true);
  4679. return !check;
  4680. };
  4681. Node.prototype.hasNewParent = function (update) {
  4682. if (this._cache.parent === this.parent)
  4683. return false;
  4684. if (update)
  4685. this._cache.parent = this.parent;
  4686. return true;
  4687. };
  4688. Node.prototype.isReady = function () {
  4689. return this._isReady;
  4690. };
  4691. Node.prototype.isEnabled = function () {
  4692. if (!this._isEnabled) {
  4693. return false;
  4694. }
  4695. if (this.parent) {
  4696. return this.parent.isEnabled();
  4697. }
  4698. return true;
  4699. };
  4700. Node.prototype.setEnabled = function (value) {
  4701. this._isEnabled = value;
  4702. };
  4703. Node.prototype.isDescendantOf = function (ancestor) {
  4704. if (this.parent) {
  4705. if (this.parent === ancestor) {
  4706. return true;
  4707. }
  4708. return this.parent.isDescendantOf(ancestor);
  4709. }
  4710. return false;
  4711. };
  4712. Node.prototype._getDescendants = function (list, results) {
  4713. for (var index = 0; index < list.length; index++) {
  4714. var item = list[index];
  4715. if (item.isDescendantOf(this)) {
  4716. results.push(item);
  4717. }
  4718. }
  4719. };
  4720. Node.prototype.getDescendants = function () {
  4721. var results = [];
  4722. this._getDescendants(this._scene.meshes, results);
  4723. this._getDescendants(this._scene.lights, results);
  4724. this._getDescendants(this._scene.cameras, results);
  4725. return results;
  4726. };
  4727. Node.prototype._setReady = function (state) {
  4728. if (state == this._isReady) {
  4729. return;
  4730. }
  4731. if (!state) {
  4732. this._isReady = false;
  4733. return;
  4734. }
  4735. this._isReady = true;
  4736. if (this.onReady) {
  4737. this.onReady(this);
  4738. }
  4739. };
  4740. return Node;
  4741. })();
  4742. BABYLON.Node = Node;
  4743. })(BABYLON || (BABYLON = {}));
  4744. //# sourceMappingURL=babylon.node.js.map
  4745. var BABYLON;
  4746. (function (BABYLON) {
  4747. var BoundingSphere = (function () {
  4748. function BoundingSphere(minimum, maximum) {
  4749. this.minimum = minimum;
  4750. this.maximum = maximum;
  4751. this._tempRadiusVector = BABYLON.Vector3.Zero();
  4752. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  4753. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  4754. this.radius = distance * 0.5;
  4755. this.centerWorld = BABYLON.Vector3.Zero();
  4756. this._update(BABYLON.Matrix.Identity());
  4757. }
  4758. // Methods
  4759. BoundingSphere.prototype._update = function (world) {
  4760. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  4761. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  4762. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  4763. };
  4764. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  4765. for (var i = 0; i < 6; i++) {
  4766. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  4767. return false;
  4768. }
  4769. return true;
  4770. };
  4771. BoundingSphere.prototype.intersectsPoint = function (point) {
  4772. var x = this.centerWorld.x - point.x;
  4773. var y = this.centerWorld.y - point.y;
  4774. var z = this.centerWorld.z - point.z;
  4775. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  4776. if (Math.abs(this.radiusWorld - distance) < BABYLON.Engine.Epsilon)
  4777. return false;
  4778. return true;
  4779. };
  4780. // Statics
  4781. BoundingSphere.Intersects = function (sphere0, sphere1) {
  4782. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  4783. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  4784. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  4785. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  4786. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  4787. return false;
  4788. return true;
  4789. };
  4790. return BoundingSphere;
  4791. })();
  4792. BABYLON.BoundingSphere = BoundingSphere;
  4793. })(BABYLON || (BABYLON = {}));
  4794. //# sourceMappingURL=babylon.boundingSphere.js.map
  4795. var BABYLON;
  4796. (function (BABYLON) {
  4797. var BoundingBox = (function () {
  4798. function BoundingBox(minimum, maximum) {
  4799. this.minimum = minimum;
  4800. this.maximum = maximum;
  4801. this.vectors = new Array();
  4802. this.vectorsWorld = new Array();
  4803. // Bounding vectors
  4804. this.vectors.push(this.minimum.clone());
  4805. this.vectors.push(this.maximum.clone());
  4806. this.vectors.push(this.minimum.clone());
  4807. this.vectors[2].x = this.maximum.x;
  4808. this.vectors.push(this.minimum.clone());
  4809. this.vectors[3].y = this.maximum.y;
  4810. this.vectors.push(this.minimum.clone());
  4811. this.vectors[4].z = this.maximum.z;
  4812. this.vectors.push(this.maximum.clone());
  4813. this.vectors[5].z = this.minimum.z;
  4814. this.vectors.push(this.maximum.clone());
  4815. this.vectors[6].x = this.minimum.x;
  4816. this.vectors.push(this.maximum.clone());
  4817. this.vectors[7].y = this.minimum.y;
  4818. // OBB
  4819. this.center = this.maximum.add(this.minimum).scale(0.5);
  4820. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  4821. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  4822. for (var index = 0; index < this.vectors.length; index++) {
  4823. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  4824. }
  4825. this.minimumWorld = BABYLON.Vector3.Zero();
  4826. this.maximumWorld = BABYLON.Vector3.Zero();
  4827. this._update(BABYLON.Matrix.Identity());
  4828. }
  4829. // Methods
  4830. BoundingBox.prototype.getWorldMatrix = function () {
  4831. return this._worldMatrix;
  4832. };
  4833. BoundingBox.prototype._update = function (world) {
  4834. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  4835. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  4836. for (var index = 0; index < this.vectors.length; index++) {
  4837. var v = this.vectorsWorld[index];
  4838. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  4839. if (v.x < this.minimumWorld.x)
  4840. this.minimumWorld.x = v.x;
  4841. if (v.y < this.minimumWorld.y)
  4842. this.minimumWorld.y = v.y;
  4843. if (v.z < this.minimumWorld.z)
  4844. this.minimumWorld.z = v.z;
  4845. if (v.x > this.maximumWorld.x)
  4846. this.maximumWorld.x = v.x;
  4847. if (v.y > this.maximumWorld.y)
  4848. this.maximumWorld.y = v.y;
  4849. if (v.z > this.maximumWorld.z)
  4850. this.maximumWorld.z = v.z;
  4851. }
  4852. // OBB
  4853. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  4854. this.center.scaleInPlace(0.5);
  4855. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  4856. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  4857. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  4858. this._worldMatrix = world;
  4859. };
  4860. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  4861. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  4862. };
  4863. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  4864. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  4865. };
  4866. BoundingBox.prototype.intersectsPoint = function (point) {
  4867. var delta = BABYLON.Engine.Epsilon;
  4868. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  4869. return false;
  4870. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  4871. return false;
  4872. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  4873. return false;
  4874. return true;
  4875. };
  4876. BoundingBox.prototype.intersectsSphere = function (sphere) {
  4877. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  4878. };
  4879. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  4880. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  4881. return false;
  4882. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  4883. return false;
  4884. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  4885. return false;
  4886. return true;
  4887. };
  4888. // Statics
  4889. BoundingBox.Intersects = function (box0, box1) {
  4890. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  4891. return false;
  4892. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  4893. return false;
  4894. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  4895. return false;
  4896. return true;
  4897. };
  4898. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  4899. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  4900. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  4901. return (num <= (sphereRadius * sphereRadius));
  4902. };
  4903. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  4904. for (var p = 0; p < 6; p++) {
  4905. for (var i = 0; i < 8; i++) {
  4906. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  4907. return false;
  4908. }
  4909. }
  4910. }
  4911. return true;
  4912. };
  4913. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  4914. for (var p = 0; p < 6; p++) {
  4915. var inCount = 8;
  4916. for (var i = 0; i < 8; i++) {
  4917. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  4918. --inCount;
  4919. } else {
  4920. break;
  4921. }
  4922. }
  4923. if (inCount == 0)
  4924. return false;
  4925. }
  4926. return true;
  4927. };
  4928. return BoundingBox;
  4929. })();
  4930. BABYLON.BoundingBox = BoundingBox;
  4931. })(BABYLON || (BABYLON = {}));
  4932. //# sourceMappingURL=babylon.boundingBox.js.map
  4933. var BABYLON;
  4934. (function (BABYLON) {
  4935. var computeBoxExtents = function (axis, box) {
  4936. var p = BABYLON.Vector3.Dot(box.center, axis);
  4937. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  4938. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  4939. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  4940. var r = r0 + r1 + r2;
  4941. return {
  4942. min: p - r,
  4943. max: p + r
  4944. };
  4945. };
  4946. var extentsOverlap = function (min0, max0, min1, max1) {
  4947. return !(min0 > max1 || min1 > max0);
  4948. };
  4949. var axisOverlap = function (axis, box0, box1) {
  4950. var result0 = computeBoxExtents(axis, box0);
  4951. var result1 = computeBoxExtents(axis, box1);
  4952. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  4953. };
  4954. var BoundingInfo = (function () {
  4955. function BoundingInfo(minimum, maximum) {
  4956. this.minimum = minimum;
  4957. this.maximum = maximum;
  4958. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  4959. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  4960. }
  4961. // Methods
  4962. BoundingInfo.prototype._update = function (world) {
  4963. this.boundingBox._update(world);
  4964. this.boundingSphere._update(world);
  4965. };
  4966. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  4967. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  4968. return false;
  4969. return this.boundingBox.isInFrustum(frustumPlanes);
  4970. };
  4971. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  4972. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  4973. };
  4974. BoundingInfo.prototype._checkCollision = function (collider) {
  4975. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  4976. };
  4977. BoundingInfo.prototype.intersectsPoint = function (point) {
  4978. if (!this.boundingSphere.centerWorld) {
  4979. return false;
  4980. }
  4981. if (!this.boundingSphere.intersectsPoint(point)) {
  4982. return false;
  4983. }
  4984. if (!this.boundingBox.intersectsPoint(point)) {
  4985. return false;
  4986. }
  4987. return true;
  4988. };
  4989. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  4990. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  4991. return false;
  4992. }
  4993. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  4994. return false;
  4995. }
  4996. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  4997. return false;
  4998. }
  4999. if (!precise) {
  5000. return true;
  5001. }
  5002. var box0 = this.boundingBox;
  5003. var box1 = boundingInfo.boundingBox;
  5004. if (!axisOverlap(box0.directions[0], box0, box1))
  5005. return false;
  5006. if (!axisOverlap(box0.directions[1], box0, box1))
  5007. return false;
  5008. if (!axisOverlap(box0.directions[2], box0, box1))
  5009. return false;
  5010. if (!axisOverlap(box1.directions[0], box0, box1))
  5011. return false;
  5012. if (!axisOverlap(box1.directions[1], box0, box1))
  5013. return false;
  5014. if (!axisOverlap(box1.directions[2], box0, box1))
  5015. return false;
  5016. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  5017. return false;
  5018. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  5019. return false;
  5020. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  5021. return false;
  5022. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  5023. return false;
  5024. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  5025. return false;
  5026. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  5027. return false;
  5028. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  5029. return false;
  5030. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  5031. return false;
  5032. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  5033. return false;
  5034. return true;
  5035. };
  5036. return BoundingInfo;
  5037. })();
  5038. BABYLON.BoundingInfo = BoundingInfo;
  5039. })(BABYLON || (BABYLON = {}));
  5040. //# sourceMappingURL=babylon.boundingInfo.js.map
  5041. var BABYLON;
  5042. (function (BABYLON) {
  5043. var Light = (function (_super) {
  5044. __extends(Light, _super);
  5045. function Light(name, scene) {
  5046. _super.call(this, name, scene);
  5047. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  5048. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  5049. this.intensity = 1.0;
  5050. this.range = Number.MAX_VALUE;
  5051. this.includedOnlyMeshes = new Array();
  5052. this.excludedMeshes = new Array();
  5053. this._excludedMeshesIds = new Array();
  5054. this._includedOnlyMeshesIds = new Array();
  5055. scene.lights.push(this);
  5056. }
  5057. Light.prototype.getShadowGenerator = function () {
  5058. return this._shadowGenerator;
  5059. };
  5060. Light.prototype.getAbsolutePosition = function () {
  5061. return BABYLON.Vector3.Zero();
  5062. };
  5063. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  5064. };
  5065. Light.prototype._getWorldMatrix = function () {
  5066. return BABYLON.Matrix.Identity();
  5067. };
  5068. Light.prototype.canAffectMesh = function (mesh) {
  5069. if (!mesh) {
  5070. return true;
  5071. }
  5072. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  5073. return false;
  5074. }
  5075. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  5076. return false;
  5077. }
  5078. return true;
  5079. };
  5080. Light.prototype.getWorldMatrix = function () {
  5081. this._currentRenderId = this.getScene().getRenderId();
  5082. var worldMatrix = this._getWorldMatrix();
  5083. if (this.parent && this.parent.getWorldMatrix) {
  5084. if (!this._parentedWorldMatrix) {
  5085. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  5086. }
  5087. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  5088. return this._parentedWorldMatrix;
  5089. }
  5090. return worldMatrix;
  5091. };
  5092. Light.prototype.dispose = function () {
  5093. if (this._shadowGenerator) {
  5094. this._shadowGenerator.dispose();
  5095. this._shadowGenerator = null;
  5096. }
  5097. // Remove from scene
  5098. var index = this.getScene().lights.indexOf(this);
  5099. this.getScene().lights.splice(index, 1);
  5100. };
  5101. return Light;
  5102. })(BABYLON.Node);
  5103. BABYLON.Light = Light;
  5104. })(BABYLON || (BABYLON = {}));
  5105. //# sourceMappingURL=babylon.light.js.map
  5106. var BABYLON;
  5107. (function (BABYLON) {
  5108. var PointLight = (function (_super) {
  5109. __extends(PointLight, _super);
  5110. function PointLight(name, position, scene) {
  5111. _super.call(this, name, scene);
  5112. this.position = position;
  5113. }
  5114. PointLight.prototype.getAbsolutePosition = function () {
  5115. return this._transformedPosition ? this._transformedPosition : this.position;
  5116. };
  5117. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  5118. if (this.parent && this.parent.getWorldMatrix) {
  5119. if (!this._transformedPosition) {
  5120. this._transformedPosition = BABYLON.Vector3.Zero();
  5121. }
  5122. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this._transformedPosition);
  5123. effect.setFloat4(positionUniformName, this._transformedPosition.x, this._transformedPosition.y, this._transformedPosition.z, 0);
  5124. return;
  5125. }
  5126. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  5127. };
  5128. PointLight.prototype.getShadowGenerator = function () {
  5129. return null;
  5130. };
  5131. PointLight.prototype._getWorldMatrix = function () {
  5132. if (!this._worldMatrix) {
  5133. this._worldMatrix = BABYLON.Matrix.Identity();
  5134. }
  5135. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  5136. return this._worldMatrix;
  5137. };
  5138. return PointLight;
  5139. })(BABYLON.Light);
  5140. BABYLON.PointLight = PointLight;
  5141. })(BABYLON || (BABYLON = {}));
  5142. //# sourceMappingURL=babylon.pointLight.js.map
  5143. var BABYLON;
  5144. (function (BABYLON) {
  5145. var SpotLight = (function (_super) {
  5146. __extends(SpotLight, _super);
  5147. function SpotLight(name, position, direction, angle, exponent, scene) {
  5148. _super.call(this, name, scene);
  5149. this.position = position;
  5150. this.direction = direction;
  5151. this.angle = angle;
  5152. this.exponent = exponent;
  5153. }
  5154. SpotLight.prototype.getAbsolutePosition = function () {
  5155. return this._transformedPosition ? this._transformedPosition : this.position;
  5156. };
  5157. SpotLight.prototype.setDirectionToTarget = function (target) {
  5158. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  5159. return this.direction;
  5160. };
  5161. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  5162. var normalizeDirection;
  5163. if (this.parent && this.parent.getWorldMatrix) {
  5164. if (!this._transformedDirection) {
  5165. this._transformedDirection = BABYLON.Vector3.Zero();
  5166. }
  5167. if (!this._transformedPosition) {
  5168. this._transformedPosition = BABYLON.Vector3.Zero();
  5169. }
  5170. var parentWorldMatrix = this.parent.getWorldMatrix();
  5171. BABYLON.Vector3.TransformCoordinatesToRef(this.position, parentWorldMatrix, this._transformedPosition);
  5172. BABYLON.Vector3.TransformNormalToRef(this.direction, parentWorldMatrix, this._transformedDirection);
  5173. effect.setFloat4(positionUniformName, this._transformedPosition.x, this._transformedPosition.y, this._transformedPosition.z, this.exponent);
  5174. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  5175. } else {
  5176. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  5177. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  5178. }
  5179. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  5180. };
  5181. SpotLight.prototype._getWorldMatrix = function () {
  5182. if (!this._worldMatrix) {
  5183. this._worldMatrix = BABYLON.Matrix.Identity();
  5184. }
  5185. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  5186. return this._worldMatrix;
  5187. };
  5188. return SpotLight;
  5189. })(BABYLON.Light);
  5190. BABYLON.SpotLight = SpotLight;
  5191. })(BABYLON || (BABYLON = {}));
  5192. //# sourceMappingURL=babylon.spotLight.js.map
  5193. var BABYLON;
  5194. (function (BABYLON) {
  5195. var DirectionalLight = (function (_super) {
  5196. __extends(DirectionalLight, _super);
  5197. function DirectionalLight(name, direction, scene) {
  5198. _super.call(this, name, scene);
  5199. this.direction = direction;
  5200. this.position = direction.scale(-1);
  5201. }
  5202. DirectionalLight.prototype.getAbsolutePosition = function () {
  5203. return this._transformedPosition ? this._transformedPosition : this.position;
  5204. };
  5205. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  5206. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  5207. return this.direction;
  5208. };
  5209. DirectionalLight.prototype._computeTransformedPosition = function () {
  5210. if (this.parent && this.parent.getWorldMatrix) {
  5211. if (!this._transformedPosition) {
  5212. this._transformedPosition = BABYLON.Vector3.Zero();
  5213. }
  5214. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this._transformedPosition);
  5215. return true;
  5216. }
  5217. return false;
  5218. };
  5219. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  5220. if (this.parent && this.parent.getWorldMatrix) {
  5221. if (!this._transformedDirection) {
  5222. this._transformedDirection = BABYLON.Vector3.Zero();
  5223. }
  5224. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  5225. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  5226. return;
  5227. }
  5228. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  5229. };
  5230. DirectionalLight.prototype._getWorldMatrix = function () {
  5231. if (!this._worldMatrix) {
  5232. this._worldMatrix = BABYLON.Matrix.Identity();
  5233. }
  5234. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  5235. return this._worldMatrix;
  5236. };
  5237. return DirectionalLight;
  5238. })(BABYLON.Light);
  5239. BABYLON.DirectionalLight = DirectionalLight;
  5240. })(BABYLON || (BABYLON = {}));
  5241. //# sourceMappingURL=babylon.directionalLight.js.map
  5242. var BABYLON;
  5243. (function (BABYLON) {
  5244. var ShadowGenerator = (function () {
  5245. function ShadowGenerator(mapSize, light) {
  5246. var _this = this;
  5247. // Members
  5248. this.filter = ShadowGenerator.FILTER_VARIANCESHADOWMAP;
  5249. this._darkness = 0;
  5250. this._transparencyShadow = false;
  5251. this._viewMatrix = BABYLON.Matrix.Zero();
  5252. this._projectionMatrix = BABYLON.Matrix.Zero();
  5253. this._transformMatrix = BABYLON.Matrix.Zero();
  5254. this._worldViewProjection = BABYLON.Matrix.Zero();
  5255. this._light = light;
  5256. this._scene = light.getScene();
  5257. light._shadowGenerator = this;
  5258. // Render target
  5259. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false);
  5260. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  5261. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  5262. this._shadowMap.renderParticles = false;
  5263. // Custom render function
  5264. var renderSubMesh = function (subMesh) {
  5265. var mesh = subMesh.getRenderingMesh();
  5266. var scene = _this._scene;
  5267. var engine = scene.getEngine();
  5268. // Culling
  5269. engine.setState(subMesh.getMaterial().backFaceCulling);
  5270. // Managing instances
  5271. var batch = mesh._getInstancesRenderList(subMesh._id);
  5272. if (batch.mustReturn) {
  5273. return;
  5274. }
  5275. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  5276. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  5277. engine.enableEffect(_this._effect);
  5278. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  5279. var material = subMesh.getMaterial();
  5280. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  5281. // Alpha test
  5282. if (material && material.needAlphaTesting()) {
  5283. var alphaTexture = material.getAlphaTestTexture();
  5284. _this._effect.setTexture("diffuseSampler", alphaTexture);
  5285. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  5286. }
  5287. // Bones
  5288. var useBones = mesh.skeleton && scene.skeletonsEnabled && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  5289. if (useBones) {
  5290. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  5291. }
  5292. if (hardwareInstancedRendering) {
  5293. mesh._renderWithInstances(subMesh, BABYLON.Material.TriangleFillMode, batch, _this._effect, engine);
  5294. } else {
  5295. if (batch.renderSelf[subMesh._id]) {
  5296. _this._effect.setMatrix("world", mesh.getWorldMatrix());
  5297. // Draw
  5298. mesh._draw(subMesh, BABYLON.Material.TriangleFillMode);
  5299. }
  5300. if (batch.visibleInstances[subMesh._id]) {
  5301. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  5302. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  5303. _this._effect.setMatrix("world", instance.getWorldMatrix());
  5304. // Draw
  5305. mesh._draw(subMesh, BABYLON.Material.TriangleFillMode);
  5306. }
  5307. }
  5308. }
  5309. } else {
  5310. // Need to reset refresh rate of the shadowMap
  5311. _this._shadowMap.resetRefreshCounter();
  5312. }
  5313. };
  5314. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  5315. var index;
  5316. for (index = 0; index < opaqueSubMeshes.length; index++) {
  5317. renderSubMesh(opaqueSubMeshes.data[index]);
  5318. }
  5319. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  5320. renderSubMesh(alphaTestSubMeshes.data[index]);
  5321. }
  5322. if (_this._transparencyShadow) {
  5323. for (index = 0; index < transparentSubMeshes.length; index++) {
  5324. renderSubMesh(transparentSubMeshes.data[index]);
  5325. }
  5326. }
  5327. };
  5328. }
  5329. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  5330. // Static
  5331. get: function () {
  5332. return ShadowGenerator._FILTER_NONE;
  5333. },
  5334. enumerable: true,
  5335. configurable: true
  5336. });
  5337. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  5338. get: function () {
  5339. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  5340. },
  5341. enumerable: true,
  5342. configurable: true
  5343. });
  5344. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  5345. get: function () {
  5346. return ShadowGenerator._FILTER_POISSONSAMPLING;
  5347. },
  5348. enumerable: true,
  5349. configurable: true
  5350. });
  5351. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  5352. get: function () {
  5353. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP;
  5354. },
  5355. set: function (value) {
  5356. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  5357. },
  5358. enumerable: true,
  5359. configurable: true
  5360. });
  5361. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  5362. get: function () {
  5363. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  5364. },
  5365. set: function (value) {
  5366. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  5367. },
  5368. enumerable: true,
  5369. configurable: true
  5370. });
  5371. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  5372. var defines = [];
  5373. if (this.useVarianceShadowMap) {
  5374. defines.push("#define VSM");
  5375. }
  5376. var attribs = [BABYLON.VertexBuffer.PositionKind];
  5377. var mesh = subMesh.getMesh();
  5378. var scene = mesh.getScene();
  5379. var material = subMesh.getMaterial();
  5380. // Alpha test
  5381. if (material && material.needAlphaTesting()) {
  5382. defines.push("#define ALPHATEST");
  5383. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  5384. attribs.push(BABYLON.VertexBuffer.UVKind);
  5385. defines.push("#define UV1");
  5386. }
  5387. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  5388. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  5389. defines.push("#define UV2");
  5390. }
  5391. }
  5392. // Bones
  5393. if (mesh.skeleton && scene.skeletonsEnabled && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  5394. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  5395. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  5396. defines.push("#define BONES");
  5397. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  5398. }
  5399. // Instances
  5400. if (useInstances) {
  5401. defines.push("#define INSTANCES");
  5402. attribs.push("world0");
  5403. attribs.push("world1");
  5404. attribs.push("world2");
  5405. attribs.push("world3");
  5406. }
  5407. // Get correct effect
  5408. var join = defines.join("\n");
  5409. if (this._cachedDefines != join) {
  5410. this._cachedDefines = join;
  5411. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  5412. }
  5413. return this._effect.isReady();
  5414. };
  5415. ShadowGenerator.prototype.getShadowMap = function () {
  5416. return this._shadowMap;
  5417. };
  5418. ShadowGenerator.prototype.getLight = function () {
  5419. return this._light;
  5420. };
  5421. // Methods
  5422. ShadowGenerator.prototype.getTransformMatrix = function () {
  5423. var lightPosition = this._light.position;
  5424. var lightDirection = this._light.direction;
  5425. if (this._light._computeTransformedPosition()) {
  5426. lightPosition = this._light._transformedPosition;
  5427. }
  5428. if (!this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !lightDirection.equals(this._cachedDirection)) {
  5429. this._cachedPosition = lightPosition.clone();
  5430. this._cachedDirection = lightDirection.clone();
  5431. var activeCamera = this._scene.activeCamera;
  5432. BABYLON.Matrix.LookAtLHToRef(lightPosition, this._light.position.add(lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  5433. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2.0, 1.0, activeCamera.minZ, activeCamera.maxZ, this._projectionMatrix);
  5434. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  5435. }
  5436. return this._transformMatrix;
  5437. };
  5438. ShadowGenerator.prototype.getDarkness = function () {
  5439. return this._darkness;
  5440. };
  5441. ShadowGenerator.prototype.setDarkness = function (darkness) {
  5442. if (darkness >= 1.0)
  5443. this._darkness = 1.0;
  5444. else if (darkness <= 0.0)
  5445. this._darkness = 0.0;
  5446. else
  5447. this._darkness = darkness;
  5448. };
  5449. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  5450. this._transparencyShadow = hasShadow;
  5451. };
  5452. ShadowGenerator.prototype.dispose = function () {
  5453. this._shadowMap.dispose();
  5454. };
  5455. ShadowGenerator._FILTER_NONE = 0;
  5456. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  5457. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  5458. return ShadowGenerator;
  5459. })();
  5460. BABYLON.ShadowGenerator = ShadowGenerator;
  5461. })(BABYLON || (BABYLON = {}));
  5462. //# sourceMappingURL=babylon.shadowGenerator.js.map
  5463. var BABYLON;
  5464. (function (BABYLON) {
  5465. var HemisphericLight = (function (_super) {
  5466. __extends(HemisphericLight, _super);
  5467. function HemisphericLight(name, direction, scene) {
  5468. _super.call(this, name, scene);
  5469. this.direction = direction;
  5470. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  5471. }
  5472. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  5473. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  5474. return this.direction;
  5475. };
  5476. HemisphericLight.prototype.getShadowGenerator = function () {
  5477. return null;
  5478. };
  5479. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  5480. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  5481. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  5482. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  5483. };
  5484. HemisphericLight.prototype._getWorldMatrix = function () {
  5485. if (!this._worldMatrix) {
  5486. this._worldMatrix = BABYLON.Matrix.Identity();
  5487. }
  5488. return this._worldMatrix;
  5489. };
  5490. return HemisphericLight;
  5491. })(BABYLON.Light);
  5492. BABYLON.HemisphericLight = HemisphericLight;
  5493. })(BABYLON || (BABYLON = {}));
  5494. //# sourceMappingURL=babylon.hemisphericLight.js.map
  5495. var BABYLON;
  5496. (function (BABYLON) {
  5497. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  5498. if (boxMin.x > sphereCenter.x + sphereRadius)
  5499. return false;
  5500. if (sphereCenter.x - sphereRadius > boxMax.x)
  5501. return false;
  5502. if (boxMin.y > sphereCenter.y + sphereRadius)
  5503. return false;
  5504. if (sphereCenter.y - sphereRadius > boxMax.y)
  5505. return false;
  5506. if (boxMin.z > sphereCenter.z + sphereRadius)
  5507. return false;
  5508. if (sphereCenter.z - sphereRadius > boxMax.z)
  5509. return false;
  5510. return true;
  5511. };
  5512. var getLowestRoot = function (a, b, c, maxR) {
  5513. var determinant = b * b - 4.0 * a * c;
  5514. var result = { root: 0, found: false };
  5515. if (determinant < 0)
  5516. return result;
  5517. var sqrtD = Math.sqrt(determinant);
  5518. var r1 = (-b - sqrtD) / (2.0 * a);
  5519. var r2 = (-b + sqrtD) / (2.0 * a);
  5520. if (r1 > r2) {
  5521. var temp = r2;
  5522. r2 = r1;
  5523. r1 = temp;
  5524. }
  5525. if (r1 > 0 && r1 < maxR) {
  5526. result.root = r1;
  5527. result.found = true;
  5528. return result;
  5529. }
  5530. if (r2 > 0 && r2 < maxR) {
  5531. result.root = r2;
  5532. result.found = true;
  5533. return result;
  5534. }
  5535. return result;
  5536. };
  5537. var Collider = (function () {
  5538. function Collider() {
  5539. this.radius = new BABYLON.Vector3(1, 1, 1);
  5540. this.retry = 0;
  5541. this.basePointWorld = BABYLON.Vector3.Zero();
  5542. this.velocityWorld = BABYLON.Vector3.Zero();
  5543. this.normalizedVelocity = BABYLON.Vector3.Zero();
  5544. this._collisionPoint = BABYLON.Vector3.Zero();
  5545. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  5546. this._tempVector = BABYLON.Vector3.Zero();
  5547. this._tempVector2 = BABYLON.Vector3.Zero();
  5548. this._tempVector3 = BABYLON.Vector3.Zero();
  5549. this._tempVector4 = BABYLON.Vector3.Zero();
  5550. this._edge = BABYLON.Vector3.Zero();
  5551. this._baseToVertex = BABYLON.Vector3.Zero();
  5552. this._destinationPoint = BABYLON.Vector3.Zero();
  5553. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  5554. this._displacementVector = BABYLON.Vector3.Zero();
  5555. }
  5556. // Methods
  5557. Collider.prototype._initialize = function (source, dir, e) {
  5558. this.velocity = dir;
  5559. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  5560. this.basePoint = source;
  5561. source.multiplyToRef(this.radius, this.basePointWorld);
  5562. dir.multiplyToRef(this.radius, this.velocityWorld);
  5563. this.velocityWorldLength = this.velocityWorld.length();
  5564. this.epsilon = e;
  5565. this.collisionFound = false;
  5566. };
  5567. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  5568. pa.subtractToRef(point, this._tempVector);
  5569. pb.subtractToRef(point, this._tempVector2);
  5570. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  5571. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  5572. if (d < 0)
  5573. return false;
  5574. pc.subtractToRef(point, this._tempVector3);
  5575. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  5576. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  5577. if (d < 0)
  5578. return false;
  5579. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  5580. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  5581. return d >= 0;
  5582. };
  5583. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  5584. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  5585. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  5586. if (distance > this.velocityWorldLength + max + sphereRadius) {
  5587. return false;
  5588. }
  5589. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  5590. return false;
  5591. return true;
  5592. };
  5593. Collider.prototype._testTriangle = function (faceIndex, subMesh, p1, p2, p3) {
  5594. var t0;
  5595. var embeddedInPlane = false;
  5596. if (!subMesh._trianglePlanes) {
  5597. subMesh._trianglePlanes = [];
  5598. }
  5599. if (!subMesh._trianglePlanes[faceIndex]) {
  5600. subMesh._trianglePlanes[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  5601. subMesh._trianglePlanes[faceIndex].copyFromPoints(p1, p2, p3);
  5602. }
  5603. var trianglePlane = subMesh._trianglePlanes[faceIndex];
  5604. if ((!subMesh.getMaterial()) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  5605. return;
  5606. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  5607. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  5608. if (normalDotVelocity == 0) {
  5609. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  5610. return;
  5611. embeddedInPlane = true;
  5612. t0 = 0;
  5613. } else {
  5614. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  5615. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  5616. if (t0 > t1) {
  5617. var temp = t1;
  5618. t1 = t0;
  5619. t0 = temp;
  5620. }
  5621. if (t0 > 1.0 || t1 < 0.0)
  5622. return;
  5623. if (t0 < 0)
  5624. t0 = 0;
  5625. if (t0 > 1.0)
  5626. t0 = 1.0;
  5627. }
  5628. this._collisionPoint.copyFromFloats(0, 0, 0);
  5629. var found = false;
  5630. var t = 1.0;
  5631. if (!embeddedInPlane) {
  5632. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  5633. this.velocity.scaleToRef(t0, this._tempVector);
  5634. this._planeIntersectionPoint.addInPlace(this._tempVector);
  5635. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  5636. found = true;
  5637. t = t0;
  5638. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  5639. }
  5640. }
  5641. if (!found) {
  5642. var velocitySquaredLength = this.velocity.lengthSquared();
  5643. var a = velocitySquaredLength;
  5644. this.basePoint.subtractToRef(p1, this._tempVector);
  5645. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  5646. var c = this._tempVector.lengthSquared() - 1.0;
  5647. var lowestRoot = getLowestRoot(a, b, c, t);
  5648. if (lowestRoot.found) {
  5649. t = lowestRoot.root;
  5650. found = true;
  5651. this._collisionPoint.copyFrom(p1);
  5652. }
  5653. this.basePoint.subtractToRef(p2, this._tempVector);
  5654. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  5655. c = this._tempVector.lengthSquared() - 1.0;
  5656. lowestRoot = getLowestRoot(a, b, c, t);
  5657. if (lowestRoot.found) {
  5658. t = lowestRoot.root;
  5659. found = true;
  5660. this._collisionPoint.copyFrom(p2);
  5661. }
  5662. this.basePoint.subtractToRef(p3, this._tempVector);
  5663. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  5664. c = this._tempVector.lengthSquared() - 1.0;
  5665. lowestRoot = getLowestRoot(a, b, c, t);
  5666. if (lowestRoot.found) {
  5667. t = lowestRoot.root;
  5668. found = true;
  5669. this._collisionPoint.copyFrom(p3);
  5670. }
  5671. p2.subtractToRef(p1, this._edge);
  5672. p1.subtractToRef(this.basePoint, this._baseToVertex);
  5673. var edgeSquaredLength = this._edge.lengthSquared();
  5674. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  5675. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  5676. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  5677. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  5678. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  5679. lowestRoot = getLowestRoot(a, b, c, t);
  5680. if (lowestRoot.found) {
  5681. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  5682. if (f >= 0.0 && f <= 1.0) {
  5683. t = lowestRoot.root;
  5684. found = true;
  5685. this._edge.scaleInPlace(f);
  5686. p1.addToRef(this._edge, this._collisionPoint);
  5687. }
  5688. }
  5689. p3.subtractToRef(p2, this._edge);
  5690. p2.subtractToRef(this.basePoint, this._baseToVertex);
  5691. edgeSquaredLength = this._edge.lengthSquared();
  5692. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  5693. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  5694. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  5695. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  5696. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  5697. lowestRoot = getLowestRoot(a, b, c, t);
  5698. if (lowestRoot.found) {
  5699. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  5700. if (f >= 0.0 && f <= 1.0) {
  5701. t = lowestRoot.root;
  5702. found = true;
  5703. this._edge.scaleInPlace(f);
  5704. p2.addToRef(this._edge, this._collisionPoint);
  5705. }
  5706. }
  5707. p1.subtractToRef(p3, this._edge);
  5708. p3.subtractToRef(this.basePoint, this._baseToVertex);
  5709. edgeSquaredLength = this._edge.lengthSquared();
  5710. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  5711. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  5712. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  5713. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  5714. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  5715. lowestRoot = getLowestRoot(a, b, c, t);
  5716. if (lowestRoot.found) {
  5717. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  5718. if (f >= 0.0 && f <= 1.0) {
  5719. t = lowestRoot.root;
  5720. found = true;
  5721. this._edge.scaleInPlace(f);
  5722. p3.addToRef(this._edge, this._collisionPoint);
  5723. }
  5724. }
  5725. }
  5726. if (found) {
  5727. var distToCollision = t * this.velocity.length();
  5728. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  5729. if (!this.intersectionPoint) {
  5730. this.intersectionPoint = this._collisionPoint.clone();
  5731. } else {
  5732. this.intersectionPoint.copyFrom(this._collisionPoint);
  5733. }
  5734. this.nearestDistance = distToCollision;
  5735. this.collisionFound = true;
  5736. this.collidedMesh = subMesh.getMesh();
  5737. }
  5738. }
  5739. };
  5740. Collider.prototype._collide = function (subMesh, pts, indices, indexStart, indexEnd, decal) {
  5741. for (var i = indexStart; i < indexEnd; i += 3) {
  5742. var p1 = pts[indices[i] - decal];
  5743. var p2 = pts[indices[i + 1] - decal];
  5744. var p3 = pts[indices[i + 2] - decal];
  5745. this._testTriangle(i, subMesh, p3, p2, p1);
  5746. }
  5747. };
  5748. Collider.prototype._getResponse = function (pos, vel) {
  5749. pos.addToRef(vel, this._destinationPoint);
  5750. vel.scaleInPlace((this.nearestDistance / vel.length()));
  5751. this.basePoint.addToRef(vel, pos);
  5752. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  5753. this._slidePlaneNormal.normalize();
  5754. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  5755. pos.addInPlace(this._displacementVector);
  5756. this.intersectionPoint.addInPlace(this._displacementVector);
  5757. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  5758. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  5759. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  5760. };
  5761. return Collider;
  5762. })();
  5763. BABYLON.Collider = Collider;
  5764. })(BABYLON || (BABYLON = {}));
  5765. //# sourceMappingURL=babylon.collider.js.map
  5766. var BABYLON;
  5767. (function (BABYLON) {
  5768. var Camera = (function (_super) {
  5769. __extends(Camera, _super);
  5770. function Camera(name, position, scene) {
  5771. _super.call(this, name, scene);
  5772. this.position = position;
  5773. // Members
  5774. this.upVector = BABYLON.Vector3.Up();
  5775. this.orthoLeft = null;
  5776. this.orthoRight = null;
  5777. this.orthoBottom = null;
  5778. this.orthoTop = null;
  5779. this.fov = 0.8;
  5780. this.minZ = 1.0;
  5781. this.maxZ = 10000.0;
  5782. this.inertia = 0.9;
  5783. this.mode = Camera.PERSPECTIVE_CAMERA;
  5784. this.isIntermediate = false;
  5785. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  5786. this.subCameras = [];
  5787. this.layerMask = 0xFFFFFFFF;
  5788. this._computedViewMatrix = BABYLON.Matrix.Identity();
  5789. this._projectionMatrix = new BABYLON.Matrix();
  5790. this._postProcesses = new Array();
  5791. this._postProcessesTakenIndices = [];
  5792. scene.cameras.push(this);
  5793. if (!scene.activeCamera) {
  5794. scene.activeCamera = this;
  5795. }
  5796. }
  5797. //Cache
  5798. Camera.prototype._initCache = function () {
  5799. _super.prototype._initCache.call(this);
  5800. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5801. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5802. this._cache.mode = undefined;
  5803. this._cache.minZ = undefined;
  5804. this._cache.maxZ = undefined;
  5805. this._cache.fov = undefined;
  5806. this._cache.aspectRatio = undefined;
  5807. this._cache.orthoLeft = undefined;
  5808. this._cache.orthoRight = undefined;
  5809. this._cache.orthoBottom = undefined;
  5810. this._cache.orthoTop = undefined;
  5811. this._cache.renderWidth = undefined;
  5812. this._cache.renderHeight = undefined;
  5813. };
  5814. Camera.prototype._updateCache = function (ignoreParentClass) {
  5815. if (!ignoreParentClass) {
  5816. _super.prototype._updateCache.call(this);
  5817. }
  5818. var engine = this.getEngine();
  5819. this._cache.position.copyFrom(this.position);
  5820. this._cache.upVector.copyFrom(this.upVector);
  5821. this._cache.mode = this.mode;
  5822. this._cache.minZ = this.minZ;
  5823. this._cache.maxZ = this.maxZ;
  5824. this._cache.fov = this.fov;
  5825. this._cache.aspectRatio = engine.getAspectRatio(this);
  5826. this._cache.orthoLeft = this.orthoLeft;
  5827. this._cache.orthoRight = this.orthoRight;
  5828. this._cache.orthoBottom = this.orthoBottom;
  5829. this._cache.orthoTop = this.orthoTop;
  5830. this._cache.renderWidth = engine.getRenderWidth();
  5831. this._cache.renderHeight = engine.getRenderHeight();
  5832. };
  5833. Camera.prototype._updateFromScene = function () {
  5834. this.updateCache();
  5835. this._update();
  5836. };
  5837. // Synchronized
  5838. Camera.prototype._isSynchronized = function () {
  5839. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  5840. };
  5841. Camera.prototype._isSynchronizedViewMatrix = function () {
  5842. if (!_super.prototype._isSynchronized.call(this))
  5843. return false;
  5844. return this._cache.position.equals(this.position) && this._cache.upVector.equals(this.upVector) && this.isSynchronizedWithParent();
  5845. };
  5846. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  5847. var check = this._cache.mode === this.mode && this._cache.minZ === this.minZ && this._cache.maxZ === this.maxZ;
  5848. if (!check) {
  5849. return false;
  5850. }
  5851. var engine = this.getEngine();
  5852. if (this.mode === BABYLON.Camera.PERSPECTIVE_CAMERA) {
  5853. check = this._cache.fov === this.fov && this._cache.aspectRatio === engine.getAspectRatio(this);
  5854. } else {
  5855. 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();
  5856. }
  5857. return check;
  5858. };
  5859. // Controls
  5860. Camera.prototype.attachControl = function (element) {
  5861. };
  5862. Camera.prototype.detachControl = function (element) {
  5863. };
  5864. Camera.prototype._update = function () {
  5865. };
  5866. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  5867. if (typeof insertAt === "undefined") { insertAt = null; }
  5868. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  5869. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  5870. return 0;
  5871. }
  5872. if (insertAt == null || insertAt < 0) {
  5873. this._postProcesses.push(postProcess);
  5874. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  5875. return this._postProcesses.length - 1;
  5876. }
  5877. var add = 0;
  5878. if (this._postProcesses[insertAt]) {
  5879. var start = this._postProcesses.length - 1;
  5880. for (var i = start; i >= insertAt + 1; --i) {
  5881. this._postProcesses[i + 1] = this._postProcesses[i];
  5882. }
  5883. add = 1;
  5884. }
  5885. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  5886. if (this._postProcessesTakenIndices[i] < insertAt) {
  5887. continue;
  5888. }
  5889. start = this._postProcessesTakenIndices.length - 1;
  5890. for (var j = start; j >= i; --j) {
  5891. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  5892. }
  5893. this._postProcessesTakenIndices[i] = insertAt;
  5894. break;
  5895. }
  5896. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) == -1) {
  5897. this._postProcessesTakenIndices.push(insertAt);
  5898. }
  5899. var result = insertAt + add;
  5900. this._postProcesses[result] = postProcess;
  5901. return result;
  5902. };
  5903. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  5904. if (typeof atIndices === "undefined") { atIndices = null; }
  5905. var result = [];
  5906. if (!atIndices) {
  5907. var length = this._postProcesses.length;
  5908. for (var i = 0; i < length; i++) {
  5909. if (this._postProcesses[i] !== postProcess) {
  5910. continue;
  5911. }
  5912. delete this._postProcesses[i];
  5913. var index = this._postProcessesTakenIndices.indexOf(i);
  5914. this._postProcessesTakenIndices.splice(index, 1);
  5915. }
  5916. } else {
  5917. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  5918. for (i = 0; i < atIndices.length; i++) {
  5919. var foundPostProcess = this._postProcesses[atIndices[i]];
  5920. if (foundPostProcess !== postProcess) {
  5921. result.push(i);
  5922. continue;
  5923. }
  5924. delete this._postProcesses[atIndices[i]];
  5925. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  5926. this._postProcessesTakenIndices.splice(index, 1);
  5927. }
  5928. }
  5929. return result;
  5930. };
  5931. Camera.prototype.getWorldMatrix = function () {
  5932. if (!this._worldMatrix) {
  5933. this._worldMatrix = BABYLON.Matrix.Identity();
  5934. }
  5935. var viewMatrix = this.getViewMatrix();
  5936. viewMatrix.invertToRef(this._worldMatrix);
  5937. return this._worldMatrix;
  5938. };
  5939. Camera.prototype._getViewMatrix = function () {
  5940. return BABYLON.Matrix.Identity();
  5941. };
  5942. Camera.prototype.getViewMatrix = function () {
  5943. this._computedViewMatrix = this._computeViewMatrix();
  5944. if (!this.parent || !this.parent.getWorldMatrix || this.isSynchronized()) {
  5945. return this._computedViewMatrix;
  5946. }
  5947. if (!this._worldMatrix) {
  5948. this._worldMatrix = BABYLON.Matrix.Identity();
  5949. }
  5950. this._computedViewMatrix.invertToRef(this._worldMatrix);
  5951. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  5952. this._computedViewMatrix.invert();
  5953. this._currentRenderId = this.getScene().getRenderId();
  5954. return this._computedViewMatrix;
  5955. };
  5956. Camera.prototype._computeViewMatrix = function (force) {
  5957. if (!force && this._isSynchronizedViewMatrix()) {
  5958. return this._computedViewMatrix;
  5959. }
  5960. this._computedViewMatrix = this._getViewMatrix();
  5961. if (!this.parent || !this.parent.getWorldMatrix) {
  5962. this._currentRenderId = this.getScene().getRenderId();
  5963. }
  5964. return this._computedViewMatrix;
  5965. };
  5966. Camera.prototype.getProjectionMatrix = function (force) {
  5967. if (!force && this._isSynchronizedProjectionMatrix()) {
  5968. return this._projectionMatrix;
  5969. }
  5970. var engine = this.getEngine();
  5971. if (this.mode === BABYLON.Camera.PERSPECTIVE_CAMERA) {
  5972. if (this.minZ <= 0) {
  5973. this.minZ = 0.1;
  5974. }
  5975. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix);
  5976. return this._projectionMatrix;
  5977. }
  5978. var halfWidth = engine.getRenderWidth() / 2.0;
  5979. var halfHeight = engine.getRenderHeight() / 2.0;
  5980. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  5981. return this._projectionMatrix;
  5982. };
  5983. Camera.prototype.dispose = function () {
  5984. // Remove from scene
  5985. var index = this.getScene().cameras.indexOf(this);
  5986. this.getScene().cameras.splice(index, 1);
  5987. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  5988. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  5989. }
  5990. };
  5991. Camera.PERSPECTIVE_CAMERA = 0;
  5992. Camera.ORTHOGRAPHIC_CAMERA = 1;
  5993. return Camera;
  5994. })(BABYLON.Node);
  5995. BABYLON.Camera = Camera;
  5996. })(BABYLON || (BABYLON = {}));
  5997. //# sourceMappingURL=babylon.camera.js.map
  5998. var BABYLON;
  5999. (function (BABYLON) {
  6000. var TargetCamera = (function (_super) {
  6001. __extends(TargetCamera, _super);
  6002. function TargetCamera(name, position, scene) {
  6003. _super.call(this, name, position, scene);
  6004. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  6005. this.cameraRotation = new BABYLON.Vector2(0, 0);
  6006. this.rotation = new BABYLON.Vector3(0, 0, 0);
  6007. this.speed = 2.0;
  6008. this.noRotationConstraint = false;
  6009. this.lockedTarget = null;
  6010. this._currentTarget = BABYLON.Vector3.Zero();
  6011. this._viewMatrix = BABYLON.Matrix.Zero();
  6012. this._camMatrix = BABYLON.Matrix.Zero();
  6013. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  6014. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  6015. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  6016. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  6017. this._lookAtTemp = BABYLON.Matrix.Zero();
  6018. this._tempMatrix = BABYLON.Matrix.Zero();
  6019. }
  6020. TargetCamera.prototype._getLockedTargetPosition = function () {
  6021. if (!this.lockedTarget) {
  6022. return null;
  6023. }
  6024. return this.lockedTarget.position || this.lockedTarget;
  6025. };
  6026. // Cache
  6027. TargetCamera.prototype._initCache = function () {
  6028. _super.prototype._initCache.call(this);
  6029. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6030. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6031. };
  6032. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  6033. if (!ignoreParentClass) {
  6034. _super.prototype._updateCache.call(this);
  6035. }
  6036. var lockedTargetPosition = this._getLockedTargetPosition();
  6037. if (!lockedTargetPosition) {
  6038. this._cache.lockedTarget = null;
  6039. } else {
  6040. if (!this._cache.lockedTarget) {
  6041. this._cache.lockedTarget = lockedTargetPosition.clone();
  6042. } else {
  6043. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  6044. }
  6045. }
  6046. this._cache.rotation.copyFrom(this.rotation);
  6047. };
  6048. // Synchronized
  6049. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  6050. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  6051. return false;
  6052. }
  6053. var lockedTargetPosition = this._getLockedTargetPosition();
  6054. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition) && this._cache.rotation.equals(this.rotation);
  6055. };
  6056. // Methods
  6057. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  6058. var engine = this.getEngine();
  6059. return this.speed * ((engine.getDeltaTime() / (engine.getFps() * 10.0)));
  6060. };
  6061. // Target
  6062. TargetCamera.prototype.setTarget = function (target) {
  6063. this.upVector.normalize();
  6064. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  6065. this._camMatrix.invert();
  6066. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  6067. var vDir = target.subtract(this.position);
  6068. if (vDir.x >= 0.0) {
  6069. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  6070. } else {
  6071. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  6072. }
  6073. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  6074. if (isNaN(this.rotation.x)) {
  6075. this.rotation.x = 0;
  6076. }
  6077. if (isNaN(this.rotation.y)) {
  6078. this.rotation.y = 0;
  6079. }
  6080. if (isNaN(this.rotation.z)) {
  6081. this.rotation.z = 0;
  6082. }
  6083. };
  6084. TargetCamera.prototype.getTarget = function () {
  6085. return this._currentTarget;
  6086. };
  6087. TargetCamera.prototype._decideIfNeedsToMove = function () {
  6088. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  6089. };
  6090. TargetCamera.prototype._updatePosition = function () {
  6091. this.position.addInPlace(this.cameraDirection);
  6092. };
  6093. TargetCamera.prototype._update = function () {
  6094. var needToMove = this._decideIfNeedsToMove();
  6095. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  6096. // Move
  6097. if (needToMove) {
  6098. this._updatePosition();
  6099. }
  6100. // Rotate
  6101. if (needToRotate) {
  6102. this.rotation.x += this.cameraRotation.x;
  6103. this.rotation.y += this.cameraRotation.y;
  6104. if (!this.noRotationConstraint) {
  6105. var limit = (Math.PI / 2) * 0.95;
  6106. if (this.rotation.x > limit)
  6107. this.rotation.x = limit;
  6108. if (this.rotation.x < -limit)
  6109. this.rotation.x = -limit;
  6110. }
  6111. }
  6112. // Inertia
  6113. if (needToMove) {
  6114. if (Math.abs(this.cameraDirection.x) < BABYLON.Engine.Epsilon) {
  6115. this.cameraDirection.x = 0;
  6116. }
  6117. if (Math.abs(this.cameraDirection.y) < BABYLON.Engine.Epsilon) {
  6118. this.cameraDirection.y = 0;
  6119. }
  6120. if (Math.abs(this.cameraDirection.z) < BABYLON.Engine.Epsilon) {
  6121. this.cameraDirection.z = 0;
  6122. }
  6123. this.cameraDirection.scaleInPlace(this.inertia);
  6124. }
  6125. if (needToRotate) {
  6126. if (Math.abs(this.cameraRotation.x) < BABYLON.Engine.Epsilon) {
  6127. this.cameraRotation.x = 0;
  6128. }
  6129. if (Math.abs(this.cameraRotation.y) < BABYLON.Engine.Epsilon) {
  6130. this.cameraRotation.y = 0;
  6131. }
  6132. this.cameraRotation.scaleInPlace(this.inertia);
  6133. }
  6134. };
  6135. TargetCamera.prototype._getViewMatrix = function () {
  6136. if (!this.lockedTarget) {
  6137. // Compute
  6138. if (this.upVector.x != 0 || this.upVector.y != 1.0 || this.upVector.z != 0) {
  6139. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  6140. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  6141. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  6142. this._lookAtTemp.invert();
  6143. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  6144. } else {
  6145. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  6146. }
  6147. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  6148. // Computing target and final matrix
  6149. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  6150. } else {
  6151. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  6152. }
  6153. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  6154. return this._viewMatrix;
  6155. };
  6156. return TargetCamera;
  6157. })(BABYLON.Camera);
  6158. BABYLON.TargetCamera = TargetCamera;
  6159. })(BABYLON || (BABYLON = {}));
  6160. //# sourceMappingURL=babylon.targetCamera.js.map
  6161. var BABYLON;
  6162. (function (BABYLON) {
  6163. var FollowCamera = (function (_super) {
  6164. __extends(FollowCamera, _super);
  6165. function FollowCamera(name, position, scene) {
  6166. _super.call(this, name, position, scene);
  6167. this.radius = 12;
  6168. this.rotationOffset = 0;
  6169. this.heightOffset = 4;
  6170. this.cameraAcceleration = 0.05;
  6171. this.maxCameraSpeed = 20;
  6172. }
  6173. FollowCamera.prototype.getRadians = function (degrees) {
  6174. return degrees * Math.PI / 180;
  6175. };
  6176. FollowCamera.prototype.follow = function (cameraTarget) {
  6177. if (!cameraTarget)
  6178. return;
  6179. var radians = this.getRadians(this.rotationOffset) + cameraTarget.rotation.y;
  6180. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  6181. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  6182. var dx = targetX - this.position.x;
  6183. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  6184. var dz = (targetZ) - this.position.z;
  6185. var vx = dx * this.cameraAcceleration * 2;
  6186. var vy = dy * this.cameraAcceleration;
  6187. var vz = dz * this.cameraAcceleration * 2;
  6188. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  6189. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  6190. }
  6191. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  6192. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  6193. }
  6194. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  6195. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  6196. }
  6197. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  6198. this.setTarget(cameraTarget.position);
  6199. };
  6200. FollowCamera.prototype._update = function () {
  6201. _super.prototype._update.call(this);
  6202. this.follow(this.target);
  6203. };
  6204. return FollowCamera;
  6205. })(BABYLON.TargetCamera);
  6206. BABYLON.FollowCamera = FollowCamera;
  6207. })(BABYLON || (BABYLON = {}));
  6208. //# sourceMappingURL=babylon.followCamera.js.map
  6209. var BABYLON;
  6210. (function (BABYLON) {
  6211. var FreeCamera = (function (_super) {
  6212. __extends(FreeCamera, _super);
  6213. function FreeCamera(name, position, scene) {
  6214. _super.call(this, name, position, scene);
  6215. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  6216. this.keysUp = [38];
  6217. this.keysDown = [40];
  6218. this.keysLeft = [37];
  6219. this.keysRight = [39];
  6220. this.checkCollisions = false;
  6221. this.applyGravity = false;
  6222. this.angularSensibility = 2000.0;
  6223. this._keys = [];
  6224. this._collider = new BABYLON.Collider();
  6225. this._needMoveForGravity = true;
  6226. this._oldPosition = BABYLON.Vector3.Zero();
  6227. this._diffPosition = BABYLON.Vector3.Zero();
  6228. this._newPosition = BABYLON.Vector3.Zero();
  6229. }
  6230. // Controls
  6231. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  6232. var _this = this;
  6233. var previousPosition;
  6234. var engine = this.getEngine();
  6235. if (this._attachedElement) {
  6236. return;
  6237. }
  6238. this._attachedElement = element;
  6239. if (this._onMouseDown === undefined) {
  6240. this._onMouseDown = function (evt) {
  6241. previousPosition = {
  6242. x: evt.clientX,
  6243. y: evt.clientY
  6244. };
  6245. if (!noPreventDefault) {
  6246. evt.preventDefault();
  6247. }
  6248. };
  6249. this._onMouseUp = function (evt) {
  6250. previousPosition = null;
  6251. if (!noPreventDefault) {
  6252. evt.preventDefault();
  6253. }
  6254. };
  6255. this._onMouseOut = function (evt) {
  6256. previousPosition = null;
  6257. _this._keys = [];
  6258. if (!noPreventDefault) {
  6259. evt.preventDefault();
  6260. }
  6261. };
  6262. this._onMouseMove = function (evt) {
  6263. if (!previousPosition && !engine.isPointerLock) {
  6264. return;
  6265. }
  6266. var offsetX;
  6267. var offsetY;
  6268. if (!engine.isPointerLock) {
  6269. offsetX = evt.clientX - previousPosition.x;
  6270. offsetY = evt.clientY - previousPosition.y;
  6271. } else {
  6272. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  6273. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  6274. }
  6275. _this.cameraRotation.y += offsetX / _this.angularSensibility;
  6276. _this.cameraRotation.x += offsetY / _this.angularSensibility;
  6277. previousPosition = {
  6278. x: evt.clientX,
  6279. y: evt.clientY
  6280. };
  6281. if (!noPreventDefault) {
  6282. evt.preventDefault();
  6283. }
  6284. };
  6285. this._onKeyDown = function (evt) {
  6286. 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) {
  6287. var index = _this._keys.indexOf(evt.keyCode);
  6288. if (index === -1) {
  6289. _this._keys.push(evt.keyCode);
  6290. }
  6291. if (!noPreventDefault) {
  6292. evt.preventDefault();
  6293. }
  6294. }
  6295. };
  6296. this._onKeyUp = function (evt) {
  6297. 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) {
  6298. var index = _this._keys.indexOf(evt.keyCode);
  6299. if (index >= 0) {
  6300. _this._keys.splice(index, 1);
  6301. }
  6302. if (!noPreventDefault) {
  6303. evt.preventDefault();
  6304. }
  6305. }
  6306. };
  6307. this._onLostFocus = function () {
  6308. _this._keys = [];
  6309. };
  6310. this._reset = function () {
  6311. _this._keys = [];
  6312. previousPosition = null;
  6313. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  6314. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  6315. };
  6316. }
  6317. element.addEventListener("mousedown", this._onMouseDown, false);
  6318. element.addEventListener("mouseup", this._onMouseUp, false);
  6319. element.addEventListener("mouseout", this._onMouseOut, false);
  6320. element.addEventListener("mousemove", this._onMouseMove, false);
  6321. BABYLON.Tools.RegisterTopRootEvents([
  6322. { name: "keydown", handler: this._onKeyDown },
  6323. { name: "keyup", handler: this._onKeyUp },
  6324. { name: "blur", handler: this._onLostFocus }
  6325. ]);
  6326. };
  6327. FreeCamera.prototype.detachControl = function (element) {
  6328. if (this._attachedElement != element) {
  6329. return;
  6330. }
  6331. element.removeEventListener("mousedown", this._onMouseDown);
  6332. element.removeEventListener("mouseup", this._onMouseUp);
  6333. element.removeEventListener("mouseout", this._onMouseOut);
  6334. element.removeEventListener("mousemove", this._onMouseMove);
  6335. BABYLON.Tools.UnregisterTopRootEvents([
  6336. { name: "keydown", handler: this._onKeyDown },
  6337. { name: "keyup", handler: this._onKeyUp },
  6338. { name: "blur", handler: this._onLostFocus }
  6339. ]);
  6340. this._attachedElement = null;
  6341. if (this._reset) {
  6342. this._reset();
  6343. }
  6344. };
  6345. FreeCamera.prototype._collideWithWorld = function (velocity) {
  6346. var globalPosition;
  6347. if (this.parent) {
  6348. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  6349. } else {
  6350. globalPosition = this.position;
  6351. }
  6352. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  6353. this._collider.radius = this.ellipsoid;
  6354. this.getScene()._getNewPosition(this._oldPosition, velocity, this._collider, 3, this._newPosition);
  6355. this._newPosition.subtractToRef(this._oldPosition, this._diffPosition);
  6356. if (this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  6357. this.position.addInPlace(this._diffPosition);
  6358. if (this.onCollide) {
  6359. this.onCollide(this._collider.collidedMesh);
  6360. }
  6361. }
  6362. };
  6363. FreeCamera.prototype._checkInputs = function () {
  6364. if (!this._localDirection) {
  6365. this._localDirection = BABYLON.Vector3.Zero();
  6366. this._transformedDirection = BABYLON.Vector3.Zero();
  6367. }
  6368. for (var index = 0; index < this._keys.length; index++) {
  6369. var keyCode = this._keys[index];
  6370. var speed = this._computeLocalCameraSpeed();
  6371. if (this.keysLeft.indexOf(keyCode) !== -1) {
  6372. this._localDirection.copyFromFloats(-speed, 0, 0);
  6373. } else if (this.keysUp.indexOf(keyCode) !== -1) {
  6374. this._localDirection.copyFromFloats(0, 0, speed);
  6375. } else if (this.keysRight.indexOf(keyCode) !== -1) {
  6376. this._localDirection.copyFromFloats(speed, 0, 0);
  6377. } else if (this.keysDown.indexOf(keyCode) !== -1) {
  6378. this._localDirection.copyFromFloats(0, 0, -speed);
  6379. }
  6380. this.getViewMatrix().invertToRef(this._cameraTransformMatrix);
  6381. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  6382. this.cameraDirection.addInPlace(this._transformedDirection);
  6383. }
  6384. };
  6385. FreeCamera.prototype._decideIfNeedsToMove = function () {
  6386. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  6387. };
  6388. FreeCamera.prototype._updatePosition = function () {
  6389. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  6390. this._collideWithWorld(this.cameraDirection);
  6391. if (this.applyGravity) {
  6392. var oldPosition = this.position;
  6393. this._collideWithWorld(this.getScene().gravity);
  6394. this._needMoveForGravity = (BABYLON.Vector3.DistanceSquared(oldPosition, this.position) != 0);
  6395. }
  6396. } else {
  6397. this.position.addInPlace(this.cameraDirection);
  6398. }
  6399. };
  6400. FreeCamera.prototype._update = function () {
  6401. this._checkInputs();
  6402. _super.prototype._update.call(this);
  6403. };
  6404. return FreeCamera;
  6405. })(BABYLON.TargetCamera);
  6406. BABYLON.FreeCamera = FreeCamera;
  6407. })(BABYLON || (BABYLON = {}));
  6408. //# sourceMappingURL=babylon.freeCamera.js.map
  6409. var BABYLON;
  6410. (function (BABYLON) {
  6411. // We're mainly based on the logic defined into the FreeCamera code
  6412. var TouchCamera = (function (_super) {
  6413. __extends(TouchCamera, _super);
  6414. function TouchCamera(name, position, scene) {
  6415. _super.call(this, name, position, scene);
  6416. this._offsetX = null;
  6417. this._offsetY = null;
  6418. this._pointerCount = 0;
  6419. this._pointerPressed = [];
  6420. this.angularSensibility = 200000.0;
  6421. this.moveSensibility = 500.0;
  6422. }
  6423. TouchCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  6424. var _this = this;
  6425. var previousPosition;
  6426. if (this._attachedCanvas) {
  6427. return;
  6428. }
  6429. this._attachedCanvas = canvas;
  6430. if (this._onPointerDown === undefined) {
  6431. this._onPointerDown = function (evt) {
  6432. if (!noPreventDefault) {
  6433. evt.preventDefault();
  6434. }
  6435. _this._pointerPressed.push(evt.pointerId);
  6436. if (_this._pointerPressed.length !== 1) {
  6437. return;
  6438. }
  6439. previousPosition = {
  6440. x: evt.clientX,
  6441. y: evt.clientY
  6442. };
  6443. };
  6444. this._onPointerUp = function (evt) {
  6445. if (!noPreventDefault) {
  6446. evt.preventDefault();
  6447. }
  6448. var index = _this._pointerPressed.indexOf(evt.pointerId);
  6449. if (index === -1) {
  6450. return;
  6451. }
  6452. _this._pointerPressed.splice(index, 1);
  6453. if (index != 0) {
  6454. return;
  6455. }
  6456. previousPosition = null;
  6457. _this._offsetX = null;
  6458. _this._offsetY = null;
  6459. };
  6460. this._onPointerMove = function (evt) {
  6461. if (!noPreventDefault) {
  6462. evt.preventDefault();
  6463. }
  6464. if (!previousPosition) {
  6465. return;
  6466. }
  6467. var index = _this._pointerPressed.indexOf(evt.pointerId);
  6468. if (index != 0) {
  6469. return;
  6470. }
  6471. _this._offsetX = evt.clientX - previousPosition.x;
  6472. _this._offsetY = -(evt.clientY - previousPosition.y);
  6473. };
  6474. this._onLostFocus = function () {
  6475. _this._offsetX = null;
  6476. _this._offsetY = null;
  6477. };
  6478. }
  6479. canvas.addEventListener("pointerdown", this._onPointerDown);
  6480. canvas.addEventListener("pointerup", this._onPointerUp);
  6481. canvas.addEventListener("pointerout", this._onPointerUp);
  6482. canvas.addEventListener("pointermove", this._onPointerMove);
  6483. BABYLON.Tools.RegisterTopRootEvents([
  6484. { name: "blur", handler: this._onLostFocus }
  6485. ]);
  6486. };
  6487. TouchCamera.prototype.detachControl = function (canvas) {
  6488. if (this._attachedCanvas != canvas) {
  6489. return;
  6490. }
  6491. canvas.removeEventListener("pointerdown", this._onPointerDown);
  6492. canvas.removeEventListener("pointerup", this._onPointerUp);
  6493. canvas.removeEventListener("pointerout", this._onPointerUp);
  6494. canvas.removeEventListener("pointermove", this._onPointerMove);
  6495. BABYLON.Tools.UnregisterTopRootEvents([
  6496. { name: "blur", handler: this._onLostFocus }
  6497. ]);
  6498. this._attachedCanvas = null;
  6499. };
  6500. TouchCamera.prototype._checkInputs = function () {
  6501. if (!this._offsetX) {
  6502. return;
  6503. }
  6504. this.cameraRotation.y += this._offsetX / this.angularSensibility;
  6505. if (this._pointerPressed.length > 1) {
  6506. this.cameraRotation.x += -this._offsetY / this.angularSensibility;
  6507. } else {
  6508. var speed = this._computeLocalCameraSpeed();
  6509. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  6510. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  6511. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  6512. }
  6513. };
  6514. return TouchCamera;
  6515. })(BABYLON.FreeCamera);
  6516. BABYLON.TouchCamera = TouchCamera;
  6517. })(BABYLON || (BABYLON = {}));
  6518. //# sourceMappingURL=babylon.touchCamera.js.map
  6519. var BABYLON;
  6520. (function (BABYLON) {
  6521. // We're mainly based on the logic defined into the FreeCamera code
  6522. var DeviceOrientationCamera = (function (_super) {
  6523. __extends(DeviceOrientationCamera, _super);
  6524. function DeviceOrientationCamera(name, position, scene) {
  6525. var _this = this;
  6526. _super.call(this, name, position, scene);
  6527. this._offsetX = null;
  6528. this._offsetY = null;
  6529. this._orientationGamma = 0;
  6530. this._orientationBeta = 0;
  6531. this._initialOrientationGamma = 0;
  6532. this._initialOrientationBeta = 0;
  6533. this.angularSensibility = 10000.0;
  6534. this.moveSensibility = 50.0;
  6535. window.addEventListener("resize", function () {
  6536. _this._initialOrientationGamma = null;
  6537. }, false);
  6538. }
  6539. DeviceOrientationCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  6540. var _this = this;
  6541. if (this._attachedCanvas) {
  6542. return;
  6543. }
  6544. this._attachedCanvas = canvas;
  6545. if (!this._orientationChanged) {
  6546. this._orientationChanged = function (evt) {
  6547. if (!_this._initialOrientationGamma) {
  6548. _this._initialOrientationGamma = evt.gamma;
  6549. _this._initialOrientationBeta = evt.beta;
  6550. }
  6551. _this._orientationGamma = evt.gamma;
  6552. _this._orientationBeta = evt.beta;
  6553. _this._offsetY = (_this._initialOrientationBeta - _this._orientationBeta);
  6554. _this._offsetX = (_this._initialOrientationGamma - _this._orientationGamma);
  6555. };
  6556. }
  6557. window.addEventListener("deviceorientation", this._orientationChanged);
  6558. };
  6559. DeviceOrientationCamera.prototype.detachControl = function (canvas) {
  6560. if (this._attachedCanvas != canvas) {
  6561. return;
  6562. }
  6563. window.removeEventListener("deviceorientation", this._orientationChanged);
  6564. this._attachedCanvas = null;
  6565. this._orientationGamma = 0;
  6566. this._orientationBeta = 0;
  6567. this._initialOrientationGamma = 0;
  6568. this._initialOrientationBeta = 0;
  6569. };
  6570. DeviceOrientationCamera.prototype._checkInputs = function () {
  6571. if (!this._offsetX) {
  6572. return;
  6573. }
  6574. this.cameraRotation.y -= this._offsetX / this.angularSensibility;
  6575. var speed = this._computeLocalCameraSpeed();
  6576. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  6577. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  6578. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  6579. };
  6580. return DeviceOrientationCamera;
  6581. })(BABYLON.FreeCamera);
  6582. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  6583. })(BABYLON || (BABYLON = {}));
  6584. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  6585. var BABYLON;
  6586. (function (BABYLON) {
  6587. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  6588. var ArcRotateCamera = (function (_super) {
  6589. __extends(ArcRotateCamera, _super);
  6590. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  6591. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  6592. this.alpha = alpha;
  6593. this.beta = beta;
  6594. this.radius = radius;
  6595. this.target = target;
  6596. this.inertialAlphaOffset = 0;
  6597. this.inertialBetaOffset = 0;
  6598. this.inertialRadiusOffset = 0;
  6599. this.lowerAlphaLimit = null;
  6600. this.upperAlphaLimit = null;
  6601. this.lowerBetaLimit = 0.01;
  6602. this.upperBetaLimit = Math.PI;
  6603. this.lowerRadiusLimit = null;
  6604. this.upperRadiusLimit = null;
  6605. this.angularSensibility = 1000.0;
  6606. this.wheelPrecision = 3.0;
  6607. this.keysUp = [38];
  6608. this.keysDown = [40];
  6609. this.keysLeft = [37];
  6610. this.keysRight = [39];
  6611. this.zoomOnFactor = 1;
  6612. this.targetScreenOffset = BABYLON.Vector2.Zero();
  6613. this._keys = [];
  6614. this._viewMatrix = new BABYLON.Matrix();
  6615. this.checkCollisions = false;
  6616. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  6617. this._collider = new BABYLON.Collider();
  6618. this._previousPosition = BABYLON.Vector3.Zero();
  6619. this._collisionVelocity = BABYLON.Vector3.Zero();
  6620. this._newPosition = BABYLON.Vector3.Zero();
  6621. // Pinch
  6622. // value for pinch step scaling
  6623. // set to 20 by default
  6624. this.pinchPrecision = 20;
  6625. this.getViewMatrix();
  6626. }
  6627. ArcRotateCamera.prototype._getTargetPosition = function () {
  6628. return this.target.position || this.target;
  6629. };
  6630. // Cache
  6631. ArcRotateCamera.prototype._initCache = function () {
  6632. _super.prototype._initCache.call(this);
  6633. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6634. this._cache.alpha = undefined;
  6635. this._cache.beta = undefined;
  6636. this._cache.radius = undefined;
  6637. this._cache.targetScreenOffset = undefined;
  6638. };
  6639. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  6640. if (!ignoreParentClass) {
  6641. _super.prototype._updateCache.call(this);
  6642. }
  6643. this._cache.target.copyFrom(this._getTargetPosition());
  6644. this._cache.alpha = this.alpha;
  6645. this._cache.beta = this.beta;
  6646. this._cache.radius = this.radius;
  6647. this._cache.targetScreenOffset = this.targetScreenOffset.clone();
  6648. };
  6649. // Synchronized
  6650. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  6651. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  6652. return false;
  6653. 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);
  6654. };
  6655. // Methods
  6656. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault) {
  6657. var _this = this;
  6658. var previousPosition;
  6659. var pointerId;
  6660. // to know if pinch started
  6661. var pinchStarted = false;
  6662. // two pinch point on X
  6663. // that will use for find if user action is pinch open or pinch close
  6664. var pinchPointX1, pinchPointX2;
  6665. if (this._attachedElement) {
  6666. return;
  6667. }
  6668. this._attachedElement = element;
  6669. var engine = this.getEngine();
  6670. if (this._onPointerDown === undefined) {
  6671. this._onPointerDown = function (evt) {
  6672. if (pointerId) {
  6673. return;
  6674. }
  6675. pointerId = evt.pointerId;
  6676. previousPosition = {
  6677. x: evt.clientX,
  6678. y: evt.clientY
  6679. };
  6680. if (!noPreventDefault) {
  6681. evt.preventDefault();
  6682. }
  6683. };
  6684. this._onPointerUp = function (evt) {
  6685. previousPosition = null;
  6686. pointerId = null;
  6687. if (!noPreventDefault) {
  6688. evt.preventDefault();
  6689. }
  6690. };
  6691. this._onPointerMove = function (evt) {
  6692. if (!previousPosition) {
  6693. return;
  6694. }
  6695. if (pointerId !== evt.pointerId) {
  6696. return;
  6697. }
  6698. // return pinch is started
  6699. if (pinchStarted) {
  6700. return;
  6701. }
  6702. var offsetX = evt.clientX - previousPosition.x;
  6703. var offsetY = evt.clientY - previousPosition.y;
  6704. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  6705. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  6706. previousPosition = {
  6707. x: evt.clientX,
  6708. y: evt.clientY
  6709. };
  6710. if (!noPreventDefault) {
  6711. evt.preventDefault();
  6712. }
  6713. };
  6714. this._onMouseMove = function (evt) {
  6715. if (!engine.isPointerLock) {
  6716. return;
  6717. }
  6718. // return pinch is started
  6719. if (pinchStarted) {
  6720. return;
  6721. }
  6722. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  6723. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  6724. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  6725. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  6726. if (!noPreventDefault) {
  6727. evt.preventDefault();
  6728. }
  6729. };
  6730. this._wheel = function (event) {
  6731. var delta = 0;
  6732. if (event.wheelDelta) {
  6733. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  6734. } else if (event.detail) {
  6735. delta = -event.detail / _this.wheelPrecision;
  6736. }
  6737. if (delta)
  6738. _this.inertialRadiusOffset += delta;
  6739. if (event.preventDefault) {
  6740. if (!noPreventDefault) {
  6741. event.preventDefault();
  6742. }
  6743. }
  6744. };
  6745. this._onKeyDown = function (evt) {
  6746. 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) {
  6747. var index = _this._keys.indexOf(evt.keyCode);
  6748. if (index === -1) {
  6749. _this._keys.push(evt.keyCode);
  6750. }
  6751. if (evt.preventDefault) {
  6752. if (!noPreventDefault) {
  6753. evt.preventDefault();
  6754. }
  6755. }
  6756. }
  6757. };
  6758. this._onKeyUp = function (evt) {
  6759. 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) {
  6760. var index = _this._keys.indexOf(evt.keyCode);
  6761. if (index >= 0) {
  6762. _this._keys.splice(index, 1);
  6763. }
  6764. if (evt.preventDefault) {
  6765. if (!noPreventDefault) {
  6766. evt.preventDefault();
  6767. }
  6768. }
  6769. }
  6770. };
  6771. this._onLostFocus = function () {
  6772. _this._keys = [];
  6773. pointerId = null;
  6774. };
  6775. this._onGestureStart = function (e) {
  6776. if (window.MSGesture === undefined) {
  6777. return;
  6778. }
  6779. if (!_this._MSGestureHandler) {
  6780. _this._MSGestureHandler = new MSGesture();
  6781. _this._MSGestureHandler.target = element;
  6782. }
  6783. _this._MSGestureHandler.addPointer(e.pointerId);
  6784. };
  6785. this._onGesture = function (e) {
  6786. _this.radius *= e.scale;
  6787. if (e.preventDefault) {
  6788. if (!noPreventDefault) {
  6789. e.stopPropagation();
  6790. e.preventDefault();
  6791. }
  6792. }
  6793. };
  6794. this._reset = function () {
  6795. _this._keys = [];
  6796. _this.inertialAlphaOffset = 0;
  6797. _this.inertialBetaOffset = 0;
  6798. _this.inertialRadiusOffset = 0;
  6799. previousPosition = null;
  6800. pointerId = null;
  6801. };
  6802. this._touchStart = function (event) {
  6803. if (event.touches.length === 2) {
  6804. //-- start pinch if two fingers on the screen
  6805. pinchStarted = true;
  6806. _this._pinchStart(event);
  6807. }
  6808. };
  6809. this._touchMove = function (event) {
  6810. if (pinchStarted) {
  6811. //-- make scaling
  6812. _this._pinchMove(event);
  6813. }
  6814. };
  6815. this._touchEnd = function (event) {
  6816. if (pinchStarted) {
  6817. //-- end of pinch
  6818. _this._pinchEnd(event);
  6819. }
  6820. };
  6821. this._pinchStart = function (event) {
  6822. // save origin touch point
  6823. pinchPointX1 = event.touches[0].clientX;
  6824. pinchPointX2 = event.touches[1].clientX;
  6825. // block the camera
  6826. // if not it rotate around target during pinch
  6827. pinchStarted = true;
  6828. };
  6829. this._pinchMove = function (event) {
  6830. // variable for new camera's radius
  6831. var delta = 0;
  6832. // variables to know if pinch open or pinch close
  6833. var direction = 1;
  6834. var distanceXOrigine, distanceXNow;
  6835. if (event.touches.length !== 2)
  6836. return;
  6837. // calculate absolute distances of the two fingers
  6838. distanceXOrigine = Math.abs(pinchPointX1 - pinchPointX2);
  6839. distanceXNow = Math.abs(event.touches[0].clientX - event.touches[1].clientX);
  6840. // if distanceXNow < distanceXOrigine -> pinch close so direction = -1
  6841. if (distanceXNow < distanceXOrigine) {
  6842. direction = -1;
  6843. }
  6844. // calculate new radius
  6845. delta = (_this.pinchPrecision / (_this.wheelPrecision * 40)) * direction;
  6846. // set new radius
  6847. _this.inertialRadiusOffset -= delta;
  6848. // save origin touch point
  6849. pinchPointX1 = event.touches[0].clientX;
  6850. pinchPointX2 = event.touches[1].clientX;
  6851. };
  6852. this._pinchEnd = function (event) {
  6853. // cancel pinch and deblock camera rotation
  6854. pinchStarted = false;
  6855. };
  6856. }
  6857. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  6858. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  6859. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  6860. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  6861. element.addEventListener("mousemove", this._onMouseMove, false);
  6862. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  6863. element.addEventListener("MSGestureChange", this._onGesture, false);
  6864. element.addEventListener('mousewheel', this._wheel, false);
  6865. element.addEventListener('DOMMouseScroll', this._wheel, false);
  6866. // pinch
  6867. element.addEventListener('touchstart', this._touchStart, false);
  6868. element.addEventListener('touchmove', this._touchMove, false);
  6869. element.addEventListener('touchend', this._touchEnd, false);
  6870. BABYLON.Tools.RegisterTopRootEvents([
  6871. { name: "keydown", handler: this._onKeyDown },
  6872. { name: "keyup", handler: this._onKeyUp },
  6873. { name: "blur", handler: this._onLostFocus }
  6874. ]);
  6875. };
  6876. ArcRotateCamera.prototype.detachControl = function (element) {
  6877. if (this._attachedElement != element) {
  6878. return;
  6879. }
  6880. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  6881. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  6882. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  6883. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  6884. element.removeEventListener("mousemove", this._onMouseMove);
  6885. element.removeEventListener("MSPointerDown", this._onGestureStart);
  6886. element.removeEventListener("MSGestureChange", this._onGesture);
  6887. element.removeEventListener('mousewheel', this._wheel);
  6888. element.removeEventListener('DOMMouseScroll', this._wheel);
  6889. // pinch
  6890. element.removeEventListener('touchstart', this._touchStart);
  6891. element.removeEventListener('touchmove', this._touchMove);
  6892. element.removeEventListener('touchend', this._touchEnd);
  6893. BABYLON.Tools.UnregisterTopRootEvents([
  6894. { name: "keydown", handler: this._onKeyDown },
  6895. { name: "keyup", handler: this._onKeyUp },
  6896. { name: "blur", handler: this._onLostFocus }
  6897. ]);
  6898. this._MSGestureHandler = null;
  6899. this._attachedElement = null;
  6900. if (this._reset) {
  6901. this._reset();
  6902. }
  6903. };
  6904. ArcRotateCamera.prototype._update = function () {
  6905. for (var index = 0; index < this._keys.length; index++) {
  6906. var keyCode = this._keys[index];
  6907. if (this.keysLeft.indexOf(keyCode) !== -1) {
  6908. this.inertialAlphaOffset -= 0.01;
  6909. } else if (this.keysUp.indexOf(keyCode) !== -1) {
  6910. this.inertialBetaOffset -= 0.01;
  6911. } else if (this.keysRight.indexOf(keyCode) !== -1) {
  6912. this.inertialAlphaOffset += 0.01;
  6913. } else if (this.keysDown.indexOf(keyCode) !== -1) {
  6914. this.inertialBetaOffset += 0.01;
  6915. }
  6916. }
  6917. // Inertia
  6918. if (this.inertialAlphaOffset != 0 || this.inertialBetaOffset != 0 || this.inertialRadiusOffset != 0) {
  6919. this.alpha += this.inertialAlphaOffset;
  6920. this.beta += this.inertialBetaOffset;
  6921. this.radius -= this.inertialRadiusOffset;
  6922. this.inertialAlphaOffset *= this.inertia;
  6923. this.inertialBetaOffset *= this.inertia;
  6924. this.inertialRadiusOffset *= this.inertia;
  6925. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Engine.Epsilon)
  6926. this.inertialAlphaOffset = 0;
  6927. if (Math.abs(this.inertialBetaOffset) < BABYLON.Engine.Epsilon)
  6928. this.inertialBetaOffset = 0;
  6929. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Engine.Epsilon)
  6930. this.inertialRadiusOffset = 0;
  6931. }
  6932. // Limits
  6933. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  6934. this.alpha = this.lowerAlphaLimit;
  6935. }
  6936. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  6937. this.alpha = this.upperAlphaLimit;
  6938. }
  6939. if (this.lowerBetaLimit && this.beta < this.lowerBetaLimit) {
  6940. this.beta = this.lowerBetaLimit;
  6941. }
  6942. if (this.upperBetaLimit && this.beta > this.upperBetaLimit) {
  6943. this.beta = this.upperBetaLimit;
  6944. }
  6945. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  6946. this.radius = this.lowerRadiusLimit;
  6947. }
  6948. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  6949. this.radius = this.upperRadiusLimit;
  6950. }
  6951. };
  6952. ArcRotateCamera.prototype.setPosition = function (position) {
  6953. var radiusv3 = position.subtract(this._getTargetPosition());
  6954. this.radius = radiusv3.length();
  6955. // Alpha
  6956. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  6957. if (radiusv3.z < 0) {
  6958. this.alpha = 2 * Math.PI - this.alpha;
  6959. }
  6960. // Beta
  6961. this.beta = Math.acos(radiusv3.y / this.radius);
  6962. };
  6963. ArcRotateCamera.prototype._getViewMatrix = function () {
  6964. // Compute
  6965. var cosa = Math.cos(this.alpha);
  6966. var sina = Math.sin(this.alpha);
  6967. var cosb = Math.cos(this.beta);
  6968. var sinb = Math.sin(this.beta);
  6969. var target = this._getTargetPosition();
  6970. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this.position);
  6971. if (this.checkCollisions) {
  6972. this._collider.radius = this.collisionRadius;
  6973. this.position.subtractToRef(this._previousPosition, this._collisionVelocity);
  6974. this.getScene()._getNewPosition(this._previousPosition, this._collisionVelocity, this._collider, 3, this._newPosition);
  6975. if (!this._newPosition.equalsWithEpsilon(this.position)) {
  6976. this.position.copyFrom(this._previousPosition);
  6977. this.alpha = this._previousAlpha;
  6978. this.beta = this._previousBeta;
  6979. this.radius = this._previousRadius;
  6980. if (this.onCollide) {
  6981. this.onCollide(this._collider.collidedMesh);
  6982. }
  6983. }
  6984. }
  6985. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._viewMatrix);
  6986. this._previousAlpha = this.alpha;
  6987. this._previousBeta = this.beta;
  6988. this._previousRadius = this.radius;
  6989. this._previousPosition.copyFrom(this.position);
  6990. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  6991. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  6992. return this._viewMatrix;
  6993. };
  6994. ArcRotateCamera.prototype.zoomOn = function (meshes) {
  6995. meshes = meshes || this.getScene().meshes;
  6996. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  6997. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  6998. this.radius = distance * this.zoomOnFactor;
  6999. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance });
  7000. };
  7001. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance) {
  7002. var meshesOrMinMaxVector;
  7003. var distance;
  7004. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  7005. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  7006. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  7007. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  7008. } else {
  7009. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  7010. distance = meshesOrMinMaxVectorAndDistance.distance;
  7011. }
  7012. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  7013. this.maxZ = distance * 2;
  7014. };
  7015. return ArcRotateCamera;
  7016. })(BABYLON.Camera);
  7017. BABYLON.ArcRotateCamera = ArcRotateCamera;
  7018. })(BABYLON || (BABYLON = {}));
  7019. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  7020. var BABYLON;
  7021. (function (BABYLON) {
  7022. var Scene = (function () {
  7023. // Constructor
  7024. function Scene(engine) {
  7025. // Members
  7026. this.autoClear = true;
  7027. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  7028. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  7029. this.forceWireframe = false;
  7030. this.forcePointsCloud = false;
  7031. this.forceShowBoundingBoxes = false;
  7032. this.animationsEnabled = true;
  7033. this.cameraToUseForPointers = null;
  7034. // Fog
  7035. this.fogEnabled = true;
  7036. this.fogMode = Scene.FOGMODE_NONE;
  7037. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  7038. this.fogDensity = 0.1;
  7039. this.fogStart = 0;
  7040. this.fogEnd = 1000.0;
  7041. // Lights
  7042. this.shadowsEnabled = true;
  7043. this.lightsEnabled = true;
  7044. this.lights = new Array();
  7045. // Cameras
  7046. this.cameras = new Array();
  7047. this.activeCameras = new Array();
  7048. // Meshes
  7049. this.meshes = new Array();
  7050. // Geometries
  7051. this._geometries = new Array();
  7052. this.materials = new Array();
  7053. this.multiMaterials = new Array();
  7054. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  7055. // Textures
  7056. this.texturesEnabled = true;
  7057. this.textures = new Array();
  7058. // Particles
  7059. this.particlesEnabled = true;
  7060. this.particleSystems = new Array();
  7061. // Sprites
  7062. this.spriteManagers = new Array();
  7063. // Layers
  7064. this.layers = new Array();
  7065. // Skeletons
  7066. this.skeletonsEnabled = true;
  7067. this.skeletons = new Array();
  7068. // Lens flares
  7069. this.lensFlaresEnabled = true;
  7070. this.lensFlareSystems = new Array();
  7071. // Collisions
  7072. this.collisionsEnabled = true;
  7073. this.gravity = new BABYLON.Vector3(0, -9.0, 0);
  7074. // Postprocesses
  7075. this.postProcessesEnabled = true;
  7076. // Customs render targets
  7077. this.renderTargetsEnabled = true;
  7078. this.customRenderTargets = new Array();
  7079. // Imported meshes
  7080. this.importedMeshesFiles = new Array();
  7081. this._actionManagers = new Array();
  7082. this._meshesForIntersections = new BABYLON.SmartArray(256);
  7083. // Procedural textures
  7084. this.proceduralTexturesEnabled = true;
  7085. this._proceduralTextures = new Array();
  7086. this.soundTracks = new Array();
  7087. this._totalVertices = 0;
  7088. this._activeVertices = 0;
  7089. this._activeParticles = 0;
  7090. this._lastFrameDuration = 0;
  7091. this._evaluateActiveMeshesDuration = 0;
  7092. this._renderTargetsDuration = 0;
  7093. this._particlesDuration = 0;
  7094. this._renderDuration = 0;
  7095. this._spritesDuration = 0;
  7096. this._animationRatio = 0;
  7097. this._renderId = 0;
  7098. this._executeWhenReadyTimeoutId = -1;
  7099. this._toBeDisposed = new BABYLON.SmartArray(256);
  7100. this._onReadyCallbacks = new Array();
  7101. this._pendingData = [];
  7102. this._onBeforeRenderCallbacks = new Array();
  7103. this._onAfterRenderCallbacks = new Array();
  7104. this._activeMeshes = new BABYLON.SmartArray(256);
  7105. this._processedMaterials = new BABYLON.SmartArray(256);
  7106. this._renderTargets = new BABYLON.SmartArray(256);
  7107. this._activeParticleSystems = new BABYLON.SmartArray(256);
  7108. this._activeSkeletons = new BABYLON.SmartArray(32);
  7109. this._activeBones = 0;
  7110. this._activeAnimatables = new Array();
  7111. this._transformMatrix = BABYLON.Matrix.Zero();
  7112. this._scaledPosition = BABYLON.Vector3.Zero();
  7113. this._scaledVelocity = BABYLON.Vector3.Zero();
  7114. this._engine = engine;
  7115. engine.scenes.push(this);
  7116. this._renderingManager = new BABYLON.RenderingManager(this);
  7117. this.postProcessManager = new BABYLON.PostProcessManager(this);
  7118. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  7119. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  7120. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  7121. this.attachControl();
  7122. this._debugLayer = new BABYLON.DebugLayer(this);
  7123. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  7124. }
  7125. Object.defineProperty(Scene.prototype, "debugLayer", {
  7126. // Properties
  7127. get: function () {
  7128. return this._debugLayer;
  7129. },
  7130. enumerable: true,
  7131. configurable: true
  7132. });
  7133. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  7134. get: function () {
  7135. return this._meshUnderPointer;
  7136. },
  7137. enumerable: true,
  7138. configurable: true
  7139. });
  7140. Object.defineProperty(Scene.prototype, "pointerX", {
  7141. get: function () {
  7142. return this._pointerX;
  7143. },
  7144. enumerable: true,
  7145. configurable: true
  7146. });
  7147. Object.defineProperty(Scene.prototype, "pointerY", {
  7148. get: function () {
  7149. return this._pointerY;
  7150. },
  7151. enumerable: true,
  7152. configurable: true
  7153. });
  7154. Scene.prototype.getCachedMaterial = function () {
  7155. return this._cachedMaterial;
  7156. };
  7157. Scene.prototype.getBoundingBoxRenderer = function () {
  7158. return this._boundingBoxRenderer;
  7159. };
  7160. Scene.prototype.getOutlineRenderer = function () {
  7161. return this._outlineRenderer;
  7162. };
  7163. Scene.prototype.getEngine = function () {
  7164. return this._engine;
  7165. };
  7166. Scene.prototype.getTotalVertices = function () {
  7167. return this._totalVertices;
  7168. };
  7169. Scene.prototype.getActiveVertices = function () {
  7170. return this._activeVertices;
  7171. };
  7172. Scene.prototype.getActiveParticles = function () {
  7173. return this._activeParticles;
  7174. };
  7175. Scene.prototype.getActiveBones = function () {
  7176. return this._activeBones;
  7177. };
  7178. // Stats
  7179. Scene.prototype.getLastFrameDuration = function () {
  7180. return this._lastFrameDuration;
  7181. };
  7182. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  7183. return this._evaluateActiveMeshesDuration;
  7184. };
  7185. Scene.prototype.getActiveMeshes = function () {
  7186. return this._activeMeshes;
  7187. };
  7188. Scene.prototype.getRenderTargetsDuration = function () {
  7189. return this._renderTargetsDuration;
  7190. };
  7191. Scene.prototype.getRenderDuration = function () {
  7192. return this._renderDuration;
  7193. };
  7194. Scene.prototype.getParticlesDuration = function () {
  7195. return this._particlesDuration;
  7196. };
  7197. Scene.prototype.getSpritesDuration = function () {
  7198. return this._spritesDuration;
  7199. };
  7200. Scene.prototype.getAnimationRatio = function () {
  7201. return this._animationRatio;
  7202. };
  7203. Scene.prototype.getRenderId = function () {
  7204. return this._renderId;
  7205. };
  7206. Scene.prototype._updatePointerPosition = function (evt) {
  7207. var canvasRect = this._engine.getRenderingCanvasClientRect();
  7208. this._pointerX = evt.clientX - canvasRect.left;
  7209. this._pointerY = evt.clientY - canvasRect.top;
  7210. if (this.cameraToUseForPointers) {
  7211. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  7212. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  7213. }
  7214. };
  7215. // Pointers handling
  7216. Scene.prototype.attachControl = function () {
  7217. var _this = this;
  7218. this._onPointerMove = function (evt) {
  7219. var canvas = _this._engine.getRenderingCanvas();
  7220. _this._updatePointerPosition(evt);
  7221. var pickResult = _this.pick(_this._pointerX, _this._pointerY, function (mesh) {
  7222. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPointerTriggers;
  7223. }, false, _this.cameraToUseForPointers);
  7224. if (pickResult.hit) {
  7225. _this._meshUnderPointer = pickResult.pickedMesh;
  7226. _this.setPointerOverMesh(pickResult.pickedMesh);
  7227. canvas.style.cursor = "pointer";
  7228. } else {
  7229. _this.setPointerOverMesh(null);
  7230. canvas.style.cursor = "";
  7231. _this._meshUnderPointer = null;
  7232. }
  7233. };
  7234. this._onPointerDown = function (evt) {
  7235. var predicate = null;
  7236. if (!_this.onPointerDown) {
  7237. predicate = function (mesh) {
  7238. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPickTriggers;
  7239. };
  7240. }
  7241. _this._updatePointerPosition(evt);
  7242. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  7243. if (pickResult.hit) {
  7244. if (pickResult.pickedMesh.actionManager) {
  7245. switch (evt.button) {
  7246. case 0:
  7247. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  7248. break;
  7249. case 1:
  7250. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  7251. break;
  7252. case 2:
  7253. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  7254. break;
  7255. }
  7256. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  7257. }
  7258. }
  7259. if (_this.onPointerDown) {
  7260. _this.onPointerDown(evt, pickResult);
  7261. }
  7262. };
  7263. this._onKeyDown = function (evt) {
  7264. if (_this.actionManager) {
  7265. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  7266. }
  7267. };
  7268. this._onKeyUp = function (evt) {
  7269. if (_this.actionManager) {
  7270. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  7271. }
  7272. };
  7273. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  7274. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  7275. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  7276. window.addEventListener("keydown", this._onKeyDown, false);
  7277. window.addEventListener("keyup", this._onKeyUp, false);
  7278. };
  7279. Scene.prototype.detachControl = function () {
  7280. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  7281. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  7282. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  7283. window.removeEventListener("keydown", this._onKeyDown);
  7284. window.removeEventListener("keyup", this._onKeyUp);
  7285. };
  7286. // Ready
  7287. Scene.prototype.isReady = function () {
  7288. if (this._pendingData.length > 0) {
  7289. return false;
  7290. }
  7291. for (var index = 0; index < this._geometries.length; index++) {
  7292. var geometry = this._geometries[index];
  7293. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  7294. return false;
  7295. }
  7296. }
  7297. for (index = 0; index < this.meshes.length; index++) {
  7298. var mesh = this.meshes[index];
  7299. if (!mesh.isReady()) {
  7300. return false;
  7301. }
  7302. var mat = mesh.material;
  7303. if (mat) {
  7304. if (!mat.isReady(mesh)) {
  7305. return false;
  7306. }
  7307. }
  7308. }
  7309. return true;
  7310. };
  7311. Scene.prototype.resetCachedMaterial = function () {
  7312. this._cachedMaterial = null;
  7313. };
  7314. Scene.prototype.registerBeforeRender = function (func) {
  7315. this._onBeforeRenderCallbacks.push(func);
  7316. };
  7317. Scene.prototype.unregisterBeforeRender = function (func) {
  7318. var index = this._onBeforeRenderCallbacks.indexOf(func);
  7319. if (index > -1) {
  7320. this._onBeforeRenderCallbacks.splice(index, 1);
  7321. }
  7322. };
  7323. Scene.prototype.registerAfterRender = function (func) {
  7324. this._onAfterRenderCallbacks.push(func);
  7325. };
  7326. Scene.prototype.unregisterAfterRender = function (func) {
  7327. var index = this._onAfterRenderCallbacks.indexOf(func);
  7328. if (index > -1) {
  7329. this._onAfterRenderCallbacks.splice(index, 1);
  7330. }
  7331. };
  7332. Scene.prototype._addPendingData = function (data) {
  7333. this._pendingData.push(data);
  7334. };
  7335. Scene.prototype._removePendingData = function (data) {
  7336. var index = this._pendingData.indexOf(data);
  7337. if (index !== -1) {
  7338. this._pendingData.splice(index, 1);
  7339. }
  7340. };
  7341. Scene.prototype.getWaitingItemsCount = function () {
  7342. return this._pendingData.length;
  7343. };
  7344. Scene.prototype.executeWhenReady = function (func) {
  7345. var _this = this;
  7346. this._onReadyCallbacks.push(func);
  7347. if (this._executeWhenReadyTimeoutId !== -1) {
  7348. return;
  7349. }
  7350. this._executeWhenReadyTimeoutId = setTimeout(function () {
  7351. _this._checkIsReady();
  7352. }, 150);
  7353. };
  7354. Scene.prototype._checkIsReady = function () {
  7355. var _this = this;
  7356. if (this.isReady()) {
  7357. this._onReadyCallbacks.forEach(function (func) {
  7358. func();
  7359. });
  7360. this._onReadyCallbacks = [];
  7361. this._executeWhenReadyTimeoutId = -1;
  7362. return;
  7363. }
  7364. this._executeWhenReadyTimeoutId = setTimeout(function () {
  7365. _this._checkIsReady();
  7366. }, 150);
  7367. };
  7368. // Animations
  7369. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  7370. if (speedRatio === undefined) {
  7371. speedRatio = 1.0;
  7372. }
  7373. this.stopAnimation(target);
  7374. if (!animatable) {
  7375. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  7376. }
  7377. // Local animations
  7378. if (target.animations) {
  7379. animatable.appendAnimations(target, target.animations);
  7380. }
  7381. // Children animations
  7382. if (target.getAnimatables) {
  7383. var animatables = target.getAnimatables();
  7384. for (var index = 0; index < animatables.length; index++) {
  7385. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  7386. }
  7387. }
  7388. return animatable;
  7389. };
  7390. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  7391. if (speedRatio === undefined) {
  7392. speedRatio = 1.0;
  7393. }
  7394. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  7395. return animatable;
  7396. };
  7397. Scene.prototype.getAnimatableByTarget = function (target) {
  7398. for (var index = 0; index < this._activeAnimatables.length; index++) {
  7399. if (this._activeAnimatables[index].target === target) {
  7400. return this._activeAnimatables[index];
  7401. }
  7402. }
  7403. return null;
  7404. };
  7405. Scene.prototype.stopAnimation = function (target) {
  7406. var animatable = this.getAnimatableByTarget(target);
  7407. if (animatable) {
  7408. animatable.stop();
  7409. }
  7410. };
  7411. Scene.prototype._animate = function () {
  7412. if (!this.animationsEnabled) {
  7413. return;
  7414. }
  7415. if (!this._animationStartDate) {
  7416. this._animationStartDate = BABYLON.Tools.Now;
  7417. }
  7418. // Getting time
  7419. var now = BABYLON.Tools.Now;
  7420. var delay = now - this._animationStartDate;
  7421. for (var index = 0; index < this._activeAnimatables.length; index++) {
  7422. if (!this._activeAnimatables[index]._animate(delay)) {
  7423. this._activeAnimatables.splice(index, 1);
  7424. index--;
  7425. }
  7426. }
  7427. };
  7428. // Matrix
  7429. Scene.prototype.getViewMatrix = function () {
  7430. return this._viewMatrix;
  7431. };
  7432. Scene.prototype.getProjectionMatrix = function () {
  7433. return this._projectionMatrix;
  7434. };
  7435. Scene.prototype.getTransformMatrix = function () {
  7436. return this._transformMatrix;
  7437. };
  7438. Scene.prototype.setTransformMatrix = function (view, projection) {
  7439. this._viewMatrix = view;
  7440. this._projectionMatrix = projection;
  7441. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  7442. };
  7443. // Methods
  7444. Scene.prototype.setActiveCameraByID = function (id) {
  7445. var camera = this.getCameraByID(id);
  7446. if (camera) {
  7447. this.activeCamera = camera;
  7448. return camera;
  7449. }
  7450. return null;
  7451. };
  7452. Scene.prototype.setActiveCameraByName = function (name) {
  7453. var camera = this.getCameraByName(name);
  7454. if (camera) {
  7455. this.activeCamera = camera;
  7456. return camera;
  7457. }
  7458. return null;
  7459. };
  7460. Scene.prototype.getMaterialByID = function (id) {
  7461. for (var index = 0; index < this.materials.length; index++) {
  7462. if (this.materials[index].id === id) {
  7463. return this.materials[index];
  7464. }
  7465. }
  7466. return null;
  7467. };
  7468. Scene.prototype.getMaterialByName = function (name) {
  7469. for (var index = 0; index < this.materials.length; index++) {
  7470. if (this.materials[index].name === name) {
  7471. return this.materials[index];
  7472. }
  7473. }
  7474. return null;
  7475. };
  7476. Scene.prototype.getCameraByID = function (id) {
  7477. for (var index = 0; index < this.cameras.length; index++) {
  7478. if (this.cameras[index].id === id) {
  7479. return this.cameras[index];
  7480. }
  7481. }
  7482. return null;
  7483. };
  7484. Scene.prototype.getCameraByName = function (name) {
  7485. for (var index = 0; index < this.cameras.length; index++) {
  7486. if (this.cameras[index].name === name) {
  7487. return this.cameras[index];
  7488. }
  7489. }
  7490. return null;
  7491. };
  7492. Scene.prototype.getLightByName = function (name) {
  7493. for (var index = 0; index < this.lights.length; index++) {
  7494. if (this.lights[index].name === name) {
  7495. return this.lights[index];
  7496. }
  7497. }
  7498. return null;
  7499. };
  7500. Scene.prototype.getLightByID = function (id) {
  7501. for (var index = 0; index < this.lights.length; index++) {
  7502. if (this.lights[index].id === id) {
  7503. return this.lights[index];
  7504. }
  7505. }
  7506. return null;
  7507. };
  7508. Scene.prototype.getGeometryByID = function (id) {
  7509. for (var index = 0; index < this._geometries.length; index++) {
  7510. if (this._geometries[index].id === id) {
  7511. return this._geometries[index];
  7512. }
  7513. }
  7514. return null;
  7515. };
  7516. Scene.prototype.pushGeometry = function (geometry, force) {
  7517. if (!force && this.getGeometryByID(geometry.id)) {
  7518. return false;
  7519. }
  7520. this._geometries.push(geometry);
  7521. return true;
  7522. };
  7523. Scene.prototype.getGeometries = function () {
  7524. return this._geometries;
  7525. };
  7526. Scene.prototype.getMeshByID = function (id) {
  7527. for (var index = 0; index < this.meshes.length; index++) {
  7528. if (this.meshes[index].id === id) {
  7529. return this.meshes[index];
  7530. }
  7531. }
  7532. return null;
  7533. };
  7534. Scene.prototype.getLastMeshByID = function (id) {
  7535. for (var index = this.meshes.length - 1; index >= 0; index--) {
  7536. if (this.meshes[index].id === id) {
  7537. return this.meshes[index];
  7538. }
  7539. }
  7540. return null;
  7541. };
  7542. Scene.prototype.getLastEntryByID = function (id) {
  7543. for (var index = this.meshes.length - 1; index >= 0; index--) {
  7544. if (this.meshes[index].id === id) {
  7545. return this.meshes[index];
  7546. }
  7547. }
  7548. for (index = this.cameras.length - 1; index >= 0; index--) {
  7549. if (this.cameras[index].id === id) {
  7550. return this.cameras[index];
  7551. }
  7552. }
  7553. for (index = this.lights.length - 1; index >= 0; index--) {
  7554. if (this.lights[index].id === id) {
  7555. return this.lights[index];
  7556. }
  7557. }
  7558. return null;
  7559. };
  7560. Scene.prototype.getMeshByName = function (name) {
  7561. for (var index = 0; index < this.meshes.length; index++) {
  7562. if (this.meshes[index].name === name) {
  7563. return this.meshes[index];
  7564. }
  7565. }
  7566. return null;
  7567. };
  7568. Scene.prototype.getLastSkeletonByID = function (id) {
  7569. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  7570. if (this.skeletons[index].id === id) {
  7571. return this.skeletons[index];
  7572. }
  7573. }
  7574. return null;
  7575. };
  7576. Scene.prototype.getSkeletonById = function (id) {
  7577. for (var index = 0; index < this.skeletons.length; index++) {
  7578. if (this.skeletons[index].id === id) {
  7579. return this.skeletons[index];
  7580. }
  7581. }
  7582. return null;
  7583. };
  7584. Scene.prototype.getSkeletonByName = function (name) {
  7585. for (var index = 0; index < this.skeletons.length; index++) {
  7586. if (this.skeletons[index].name === name) {
  7587. return this.skeletons[index];
  7588. }
  7589. }
  7590. return null;
  7591. };
  7592. Scene.prototype.isActiveMesh = function (mesh) {
  7593. return (this._activeMeshes.indexOf(mesh) !== -1);
  7594. };
  7595. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  7596. if (mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  7597. var material = subMesh.getMaterial();
  7598. if (mesh.showSubMeshesBoundingBox) {
  7599. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  7600. }
  7601. if (material) {
  7602. // Render targets
  7603. if (material.getRenderTargetTextures) {
  7604. if (this._processedMaterials.indexOf(material) === -1) {
  7605. this._processedMaterials.push(material);
  7606. this._renderTargets.concat(material.getRenderTargetTextures());
  7607. }
  7608. }
  7609. // Dispatch
  7610. this._activeVertices += subMesh.indexCount;
  7611. this._renderingManager.dispatch(subMesh);
  7612. }
  7613. }
  7614. };
  7615. Scene.prototype._evaluateActiveMeshes = function () {
  7616. this._activeMeshes.reset();
  7617. this._renderingManager.reset();
  7618. this._processedMaterials.reset();
  7619. this._activeParticleSystems.reset();
  7620. this._activeSkeletons.reset();
  7621. this._boundingBoxRenderer.reset();
  7622. if (!this._frustumPlanes) {
  7623. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  7624. } else {
  7625. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  7626. }
  7627. // Meshes
  7628. var meshes;
  7629. var len;
  7630. if (this._selectionOctree) {
  7631. var selection = this._selectionOctree.select(this._frustumPlanes);
  7632. meshes = selection.data;
  7633. len = selection.length;
  7634. } else {
  7635. len = this.meshes.length;
  7636. meshes = this.meshes;
  7637. }
  7638. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  7639. var mesh = meshes[meshIndex];
  7640. if (mesh.isBlocked) {
  7641. continue;
  7642. }
  7643. this._totalVertices += mesh.getTotalVertices();
  7644. if (!mesh.isReady()) {
  7645. continue;
  7646. }
  7647. mesh.computeWorldMatrix();
  7648. // Intersections
  7649. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  7650. this._meshesForIntersections.pushNoDuplicate(mesh);
  7651. }
  7652. // Switch to current LOD
  7653. var meshLOD = mesh.getLOD(this.activeCamera);
  7654. if (!meshLOD) {
  7655. continue;
  7656. }
  7657. mesh._preActivate();
  7658. if (mesh.isEnabled() && mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  7659. this._activeMeshes.push(mesh);
  7660. mesh._activate(this._renderId);
  7661. this._activeMesh(meshLOD);
  7662. }
  7663. }
  7664. // Particle systems
  7665. var beforeParticlesDate = BABYLON.Tools.Now;
  7666. if (this.particlesEnabled) {
  7667. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  7668. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  7669. var particleSystem = this.particleSystems[particleIndex];
  7670. if (!particleSystem.isStarted()) {
  7671. continue;
  7672. }
  7673. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  7674. this._activeParticleSystems.push(particleSystem);
  7675. particleSystem.animate();
  7676. }
  7677. }
  7678. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  7679. }
  7680. this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  7681. };
  7682. Scene.prototype._activeMesh = function (mesh) {
  7683. if (mesh.skeleton && this.skeletonsEnabled) {
  7684. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  7685. }
  7686. if (mesh.showBoundingBox || this.forceShowBoundingBoxes) {
  7687. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  7688. }
  7689. if (mesh && mesh.subMeshes) {
  7690. // Submeshes Octrees
  7691. var len;
  7692. var subMeshes;
  7693. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  7694. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  7695. len = intersections.length;
  7696. subMeshes = intersections.data;
  7697. } else {
  7698. subMeshes = mesh.subMeshes;
  7699. len = subMeshes.length;
  7700. }
  7701. for (var subIndex = 0; subIndex < len; subIndex++) {
  7702. var subMesh = subMeshes[subIndex];
  7703. this._evaluateSubMesh(subMesh, mesh);
  7704. }
  7705. }
  7706. };
  7707. Scene.prototype.updateTransformMatrix = function (force) {
  7708. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  7709. };
  7710. Scene.prototype._renderForCamera = function (camera) {
  7711. var engine = this._engine;
  7712. this.activeCamera = camera;
  7713. if (!this.activeCamera)
  7714. throw new Error("Active camera not set");
  7715. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  7716. // Viewport
  7717. engine.setViewport(this.activeCamera.viewport);
  7718. // Camera
  7719. this._renderId++;
  7720. this.updateTransformMatrix();
  7721. if (this.beforeCameraRender) {
  7722. this.beforeCameraRender(this.activeCamera);
  7723. }
  7724. // Meshes
  7725. var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
  7726. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  7727. this._evaluateActiveMeshes();
  7728. this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
  7729. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  7730. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  7731. var skeleton = this._activeSkeletons.data[skeletonIndex];
  7732. skeleton.prepare();
  7733. this._activeBones += skeleton.bones.length;
  7734. }
  7735. // Render targets
  7736. var beforeRenderTargetDate = BABYLON.Tools.Now;
  7737. if (this.renderTargetsEnabled) {
  7738. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  7739. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  7740. var renderTarget = this._renderTargets.data[renderIndex];
  7741. if (renderTarget._shouldRender()) {
  7742. this._renderId++;
  7743. renderTarget.render();
  7744. }
  7745. }
  7746. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  7747. this._renderId++;
  7748. }
  7749. if (this._renderTargets.length > 0) {
  7750. engine.restoreDefaultFramebuffer();
  7751. }
  7752. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  7753. // Prepare Frame
  7754. this.postProcessManager._prepareFrame();
  7755. var beforeRenderDate = BABYLON.Tools.Now;
  7756. // Backgrounds
  7757. if (this.layers.length) {
  7758. engine.setDepthBuffer(false);
  7759. var layerIndex;
  7760. var layer;
  7761. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  7762. layer = this.layers[layerIndex];
  7763. if (layer.isBackground) {
  7764. layer.render();
  7765. }
  7766. }
  7767. engine.setDepthBuffer(true);
  7768. }
  7769. // Render
  7770. BABYLON.Tools.StartPerformanceCounter("Main render");
  7771. this._renderingManager.render(null, null, true, true);
  7772. BABYLON.Tools.EndPerformanceCounter("Main render");
  7773. // Bounding boxes
  7774. this._boundingBoxRenderer.render();
  7775. // Lens flares
  7776. if (this.lensFlaresEnabled) {
  7777. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  7778. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  7779. this.lensFlareSystems[lensFlareSystemIndex].render();
  7780. }
  7781. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  7782. }
  7783. // Foregrounds
  7784. if (this.layers.length) {
  7785. engine.setDepthBuffer(false);
  7786. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  7787. layer = this.layers[layerIndex];
  7788. if (!layer.isBackground) {
  7789. layer.render();
  7790. }
  7791. }
  7792. engine.setDepthBuffer(true);
  7793. }
  7794. this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
  7795. // Finalize frame
  7796. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  7797. // Update camera
  7798. this.activeCamera._updateFromScene();
  7799. // Reset some special arrays
  7800. this._renderTargets.reset();
  7801. if (this.afterCameraRender) {
  7802. this.afterCameraRender(this.activeCamera);
  7803. }
  7804. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  7805. };
  7806. Scene.prototype._processSubCameras = function (camera) {
  7807. if (camera.subCameras.length === 0) {
  7808. this._renderForCamera(camera);
  7809. return;
  7810. }
  7811. for (var index = 0; index < camera.subCameras.length; index++) {
  7812. this._renderForCamera(camera.subCameras[index]);
  7813. }
  7814. this.activeCamera = camera;
  7815. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  7816. // Update camera
  7817. this.activeCamera._updateFromScene();
  7818. };
  7819. Scene.prototype._checkIntersections = function () {
  7820. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  7821. var sourceMesh = this._meshesForIntersections.data[index];
  7822. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  7823. var action = sourceMesh.actionManager.actions[actionIndex];
  7824. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  7825. var otherMesh = action.getTriggerParameter();
  7826. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, false);
  7827. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  7828. if (areIntersecting && currentIntersectionInProgress === -1 && action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  7829. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh));
  7830. sourceMesh._intersectionsInProgress.push(otherMesh);
  7831. } else if (!areIntersecting && currentIntersectionInProgress > -1 && action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  7832. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh));
  7833. var indexOfOther = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  7834. if (indexOfOther > -1) {
  7835. sourceMesh._intersectionsInProgress.splice(indexOfOther, 1);
  7836. }
  7837. }
  7838. }
  7839. }
  7840. }
  7841. };
  7842. Scene.prototype.render = function () {
  7843. var startDate = BABYLON.Tools.Now;
  7844. this._particlesDuration = 0;
  7845. this._spritesDuration = 0;
  7846. this._activeParticles = 0;
  7847. this._renderDuration = 0;
  7848. this._renderTargetsDuration = 0;
  7849. this._evaluateActiveMeshesDuration = 0;
  7850. this._totalVertices = 0;
  7851. this._activeVertices = 0;
  7852. this._activeBones = 0;
  7853. this.getEngine().resetDrawCalls();
  7854. this._meshesForIntersections.reset();
  7855. this.resetCachedMaterial();
  7856. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  7857. // Actions
  7858. if (this.actionManager) {
  7859. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  7860. }
  7861. // Before render
  7862. if (this.beforeRender) {
  7863. this.beforeRender();
  7864. }
  7865. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  7866. this._onBeforeRenderCallbacks[callbackIndex]();
  7867. }
  7868. // Animations
  7869. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  7870. this._animationRatio = deltaTime * (60.0 / 1000.0);
  7871. this._animate();
  7872. // Physics
  7873. if (this._physicsEngine) {
  7874. BABYLON.Tools.StartPerformanceCounter("Physics");
  7875. this._physicsEngine._runOneStep(deltaTime / 1000.0);
  7876. BABYLON.Tools.EndPerformanceCounter("Physics");
  7877. }
  7878. // Customs render targets
  7879. var beforeRenderTargetDate = BABYLON.Tools.Now;
  7880. var engine = this.getEngine();
  7881. if (this.renderTargetsEnabled) {
  7882. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  7883. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  7884. var renderTarget = this.customRenderTargets[customIndex];
  7885. if (renderTarget._shouldRender()) {
  7886. this._renderId++;
  7887. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  7888. if (!this.activeCamera)
  7889. throw new Error("Active camera not set");
  7890. // Viewport
  7891. engine.setViewport(this.activeCamera.viewport);
  7892. // Camera
  7893. this.updateTransformMatrix();
  7894. renderTarget.render();
  7895. }
  7896. }
  7897. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  7898. this._renderId++;
  7899. }
  7900. if (this.customRenderTargets.length > 0) {
  7901. engine.restoreDefaultFramebuffer();
  7902. }
  7903. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  7904. // Procedural textures
  7905. if (this.proceduralTexturesEnabled) {
  7906. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  7907. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  7908. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  7909. if (proceduralTexture._shouldRender()) {
  7910. proceduralTexture.render();
  7911. }
  7912. }
  7913. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  7914. }
  7915. // Clear
  7916. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  7917. // Shadows
  7918. if (this.shadowsEnabled) {
  7919. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  7920. var light = this.lights[lightIndex];
  7921. var shadowGenerator = light.getShadowGenerator();
  7922. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  7923. this._renderTargets.push(shadowGenerator.getShadowMap());
  7924. }
  7925. }
  7926. }
  7927. // RenderPipeline
  7928. this.postProcessRenderPipelineManager.update();
  7929. // Multi-cameras?
  7930. if (this.activeCameras.length > 0) {
  7931. var currentRenderId = this._renderId;
  7932. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  7933. this._renderId = currentRenderId;
  7934. this._processSubCameras(this.activeCameras[cameraIndex]);
  7935. }
  7936. } else {
  7937. if (!this.activeCamera) {
  7938. throw new Error("No camera defined");
  7939. }
  7940. this._processSubCameras(this.activeCamera);
  7941. }
  7942. // Intersection checks
  7943. this._checkIntersections();
  7944. // Update the audio listener attached to the camera
  7945. this._updateAudioParameters();
  7946. // After render
  7947. if (this.afterRender) {
  7948. this.afterRender();
  7949. }
  7950. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  7951. this._onAfterRenderCallbacks[callbackIndex]();
  7952. }
  7953. for (var index = 0; index < this._toBeDisposed.length; index++) {
  7954. this._toBeDisposed.data[index].dispose();
  7955. this._toBeDisposed[index] = null;
  7956. }
  7957. this._toBeDisposed.reset();
  7958. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  7959. this._lastFrameDuration = BABYLON.Tools.Now - startDate;
  7960. };
  7961. Scene.prototype._updateAudioParameters = function () {
  7962. var listeningCamera;
  7963. var audioEngine = this._engine.getAudioEngine();
  7964. if (this.activeCameras.length > 0) {
  7965. listeningCamera = this.activeCameras[0];
  7966. } else {
  7967. listeningCamera = this.activeCamera;
  7968. }
  7969. if (listeningCamera && audioEngine.canUseWebAudio) {
  7970. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  7971. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  7972. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  7973. cameraDirection.normalize();
  7974. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  7975. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  7976. var sound = this.mainSoundTrack.soundCollection[i];
  7977. if (sound.useCustomAttenuation) {
  7978. sound.updateDistanceFromListener();
  7979. }
  7980. }
  7981. for (var i = 0; i < this.soundTracks.length; i++) {
  7982. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  7983. var sound = this.soundTracks[i].soundCollection[j];
  7984. if (sound.useCustomAttenuation) {
  7985. sound.updateDistanceFromListener();
  7986. }
  7987. }
  7988. }
  7989. }
  7990. };
  7991. Scene.prototype.dispose = function () {
  7992. this.beforeRender = null;
  7993. this.afterRender = null;
  7994. this.skeletons = [];
  7995. this._boundingBoxRenderer.dispose();
  7996. // Debug layer
  7997. this.debugLayer.hide();
  7998. // Events
  7999. if (this.onDispose) {
  8000. this.onDispose();
  8001. }
  8002. this._onBeforeRenderCallbacks = [];
  8003. this._onAfterRenderCallbacks = [];
  8004. this.detachControl();
  8005. // Detach cameras
  8006. var canvas = this._engine.getRenderingCanvas();
  8007. var index;
  8008. for (index = 0; index < this.cameras.length; index++) {
  8009. this.cameras[index].detachControl(canvas);
  8010. }
  8011. while (this.lights.length) {
  8012. this.lights[0].dispose();
  8013. }
  8014. while (this.meshes.length) {
  8015. this.meshes[0].dispose(true);
  8016. }
  8017. while (this.cameras.length) {
  8018. this.cameras[0].dispose();
  8019. }
  8020. while (this.materials.length) {
  8021. this.materials[0].dispose();
  8022. }
  8023. while (this.particleSystems.length) {
  8024. this.particleSystems[0].dispose();
  8025. }
  8026. while (this.spriteManagers.length) {
  8027. this.spriteManagers[0].dispose();
  8028. }
  8029. while (this.layers.length) {
  8030. this.layers[0].dispose();
  8031. }
  8032. while (this.textures.length) {
  8033. this.textures[0].dispose();
  8034. }
  8035. // Post-processes
  8036. this.postProcessManager.dispose();
  8037. // Physics
  8038. if (this._physicsEngine) {
  8039. this.disablePhysicsEngine();
  8040. }
  8041. // Remove from engine
  8042. index = this._engine.scenes.indexOf(this);
  8043. if (index > -1) {
  8044. this._engine.scenes.splice(index, 1);
  8045. }
  8046. this._engine.wipeCaches();
  8047. };
  8048. // Collisions
  8049. Scene.prototype._getNewPosition = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  8050. if (typeof excludedMesh === "undefined") { excludedMesh = null; }
  8051. position.divideToRef(collider.radius, this._scaledPosition);
  8052. velocity.divideToRef(collider.radius, this._scaledVelocity);
  8053. collider.retry = 0;
  8054. collider.initialVelocity = this._scaledVelocity;
  8055. collider.initialPosition = this._scaledPosition;
  8056. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, finalPosition, excludedMesh);
  8057. finalPosition.multiplyInPlace(collider.radius);
  8058. };
  8059. Scene.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  8060. if (typeof excludedMesh === "undefined") { excludedMesh = null; }
  8061. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  8062. if (collider.retry >= maximumRetry) {
  8063. finalPosition.copyFrom(position);
  8064. return;
  8065. }
  8066. collider._initialize(position, velocity, closeDistance);
  8067. for (var index = 0; index < this.meshes.length; index++) {
  8068. var mesh = this.meshes[index];
  8069. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  8070. mesh._checkCollision(collider);
  8071. }
  8072. }
  8073. if (!collider.collisionFound) {
  8074. position.addToRef(velocity, finalPosition);
  8075. return;
  8076. }
  8077. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  8078. collider._getResponse(position, velocity);
  8079. }
  8080. if (velocity.length() <= closeDistance) {
  8081. finalPosition.copyFrom(position);
  8082. return;
  8083. }
  8084. collider.retry++;
  8085. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  8086. };
  8087. // Octrees
  8088. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  8089. if (typeof maxCapacity === "undefined") { maxCapacity = 64; }
  8090. if (typeof maxDepth === "undefined") { maxDepth = 2; }
  8091. if (!this._selectionOctree) {
  8092. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  8093. }
  8094. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8095. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8096. for (var index = 0; index < this.meshes.length; index++) {
  8097. var mesh = this.meshes[index];
  8098. mesh.computeWorldMatrix(true);
  8099. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  8100. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  8101. BABYLON.Tools.CheckExtends(minBox, min, max);
  8102. BABYLON.Tools.CheckExtends(maxBox, min, max);
  8103. }
  8104. // Update octree
  8105. this._selectionOctree.update(min, max, this.meshes);
  8106. return this._selectionOctree;
  8107. };
  8108. // Picking
  8109. Scene.prototype.createPickingRay = function (x, y, world, camera) {
  8110. var engine = this._engine;
  8111. if (!camera) {
  8112. if (!this.activeCamera)
  8113. throw new Error("Active camera not set");
  8114. camera = this.activeCamera;
  8115. }
  8116. var cameraViewport = camera.viewport;
  8117. var viewport = cameraViewport.toGlobal(engine);
  8118. // Moving coordinates to local viewport world
  8119. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  8120. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  8121. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  8122. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  8123. };
  8124. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  8125. var pickingInfo = null;
  8126. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  8127. var mesh = this.meshes[meshIndex];
  8128. if (predicate) {
  8129. if (!predicate(mesh)) {
  8130. continue;
  8131. }
  8132. } else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  8133. continue;
  8134. }
  8135. var world = mesh.getWorldMatrix();
  8136. var ray = rayFunction(world);
  8137. var result = mesh.intersects(ray, fastCheck);
  8138. if (!result || !result.hit)
  8139. continue;
  8140. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  8141. continue;
  8142. pickingInfo = result;
  8143. if (fastCheck) {
  8144. break;
  8145. }
  8146. }
  8147. return pickingInfo || new BABYLON.PickingInfo();
  8148. };
  8149. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  8150. var _this = this;
  8151. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  8152. /// <param name="x">X position on screen</param>
  8153. /// <param name="y">Y position on screen</param>
  8154. /// <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>
  8155. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  8156. /// <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>
  8157. return this._internalPick(function (world) {
  8158. return _this.createPickingRay(x, y, world, camera);
  8159. }, predicate, fastCheck);
  8160. };
  8161. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  8162. var _this = this;
  8163. return this._internalPick(function (world) {
  8164. if (!_this._pickWithRayInverseMatrix) {
  8165. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  8166. }
  8167. world.invertToRef(_this._pickWithRayInverseMatrix);
  8168. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  8169. }, predicate, fastCheck);
  8170. };
  8171. Scene.prototype.setPointerOverMesh = function (mesh) {
  8172. if (this._pointerOverMesh === mesh) {
  8173. return;
  8174. }
  8175. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  8176. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  8177. }
  8178. this._pointerOverMesh = mesh;
  8179. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  8180. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  8181. }
  8182. };
  8183. Scene.prototype.getPointerOverMesh = function () {
  8184. return this._pointerOverMesh;
  8185. };
  8186. // Physics
  8187. Scene.prototype.getPhysicsEngine = function () {
  8188. return this._physicsEngine;
  8189. };
  8190. Scene.prototype.enablePhysics = function (gravity, plugin) {
  8191. if (this._physicsEngine) {
  8192. return true;
  8193. }
  8194. this._physicsEngine = new BABYLON.PhysicsEngine(plugin);
  8195. if (!this._physicsEngine.isSupported()) {
  8196. this._physicsEngine = null;
  8197. return false;
  8198. }
  8199. this._physicsEngine._initialize(gravity);
  8200. return true;
  8201. };
  8202. Scene.prototype.disablePhysicsEngine = function () {
  8203. if (!this._physicsEngine) {
  8204. return;
  8205. }
  8206. this._physicsEngine.dispose();
  8207. this._physicsEngine = undefined;
  8208. };
  8209. Scene.prototype.isPhysicsEnabled = function () {
  8210. return this._physicsEngine !== undefined;
  8211. };
  8212. Scene.prototype.setGravity = function (gravity) {
  8213. if (!this._physicsEngine) {
  8214. return;
  8215. }
  8216. this._physicsEngine._setGravity(gravity);
  8217. };
  8218. Scene.prototype.createCompoundImpostor = function (parts, options) {
  8219. if (parts.parts) {
  8220. options = parts;
  8221. parts = parts.parts;
  8222. }
  8223. if (!this._physicsEngine) {
  8224. return null;
  8225. }
  8226. for (var index = 0; index < parts.length; index++) {
  8227. var mesh = parts[index].mesh;
  8228. mesh._physicImpostor = parts[index].impostor;
  8229. mesh._physicsMass = options.mass / parts.length;
  8230. mesh._physicsFriction = options.friction;
  8231. mesh._physicRestitution = options.restitution;
  8232. }
  8233. return this._physicsEngine._registerMeshesAsCompound(parts, options);
  8234. };
  8235. //ANY
  8236. Scene.prototype.deleteCompoundImpostor = function (compound) {
  8237. for (var index = 0; index < compound.parts.length; index++) {
  8238. var mesh = compound.parts[index].mesh;
  8239. mesh._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  8240. this._physicsEngine._unregisterMesh(mesh);
  8241. }
  8242. };
  8243. // Tags
  8244. Scene.prototype._getByTags = function (list, tagsQuery) {
  8245. if (tagsQuery === undefined) {
  8246. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  8247. return list;
  8248. }
  8249. var listByTags = [];
  8250. for (var i in list) {
  8251. var item = list[i];
  8252. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  8253. listByTags.push(item);
  8254. }
  8255. }
  8256. return listByTags;
  8257. };
  8258. Scene.prototype.getMeshesByTags = function (tagsQuery) {
  8259. return this._getByTags(this.meshes, tagsQuery);
  8260. };
  8261. Scene.prototype.getCamerasByTags = function (tagsQuery) {
  8262. return this._getByTags(this.cameras, tagsQuery);
  8263. };
  8264. Scene.prototype.getLightsByTags = function (tagsQuery) {
  8265. return this._getByTags(this.lights, tagsQuery);
  8266. };
  8267. Scene.prototype.getMaterialByTags = function (tagsQuery) {
  8268. return this._getByTags(this.materials, tagsQuery).concat(this._getByTags(this.multiMaterials, tagsQuery));
  8269. };
  8270. Scene.FOGMODE_NONE = 0;
  8271. Scene.FOGMODE_EXP = 1;
  8272. Scene.FOGMODE_EXP2 = 2;
  8273. Scene.FOGMODE_LINEAR = 3;
  8274. Scene.MinDeltaTime = 1.0;
  8275. Scene.MaxDeltaTime = 1000.0;
  8276. return Scene;
  8277. })();
  8278. BABYLON.Scene = Scene;
  8279. })(BABYLON || (BABYLON = {}));
  8280. //# sourceMappingURL=babylon.scene.js.map
  8281. var BABYLON;
  8282. (function (BABYLON) {
  8283. var VertexBuffer = (function () {
  8284. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride) {
  8285. if (engine instanceof BABYLON.Mesh) {
  8286. this._engine = engine.getScene().getEngine();
  8287. } else {
  8288. this._engine = engine;
  8289. }
  8290. this._updatable = updatable;
  8291. this._data = data;
  8292. if (!postponeInternalCreation) {
  8293. this.create();
  8294. }
  8295. this._kind = kind;
  8296. if (stride) {
  8297. this._strideSize = stride;
  8298. return;
  8299. }
  8300. switch (kind) {
  8301. case VertexBuffer.PositionKind:
  8302. this._strideSize = 3;
  8303. break;
  8304. case VertexBuffer.NormalKind:
  8305. this._strideSize = 3;
  8306. break;
  8307. case VertexBuffer.UVKind:
  8308. this._strideSize = 2;
  8309. break;
  8310. case VertexBuffer.UV2Kind:
  8311. this._strideSize = 2;
  8312. break;
  8313. case VertexBuffer.ColorKind:
  8314. this._strideSize = 4;
  8315. break;
  8316. case VertexBuffer.MatricesIndicesKind:
  8317. this._strideSize = 4;
  8318. break;
  8319. case VertexBuffer.MatricesWeightsKind:
  8320. this._strideSize = 4;
  8321. break;
  8322. }
  8323. }
  8324. // Properties
  8325. VertexBuffer.prototype.isUpdatable = function () {
  8326. return this._updatable;
  8327. };
  8328. VertexBuffer.prototype.getData = function () {
  8329. return this._data;
  8330. };
  8331. VertexBuffer.prototype.getBuffer = function () {
  8332. return this._buffer;
  8333. };
  8334. VertexBuffer.prototype.getStrideSize = function () {
  8335. return this._strideSize;
  8336. };
  8337. // Methods
  8338. VertexBuffer.prototype.create = function (data) {
  8339. if (!data && this._buffer) {
  8340. return;
  8341. }
  8342. data = data || this._data;
  8343. if (!this._buffer) {
  8344. if (this._updatable) {
  8345. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  8346. } else {
  8347. this._buffer = this._engine.createVertexBuffer(data);
  8348. }
  8349. }
  8350. if (this._updatable) {
  8351. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  8352. this._data = data;
  8353. }
  8354. };
  8355. VertexBuffer.prototype.update = function (data) {
  8356. this.create(data);
  8357. };
  8358. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  8359. if (!this._buffer) {
  8360. return;
  8361. }
  8362. if (this._updatable) {
  8363. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset);
  8364. this._data = null;
  8365. }
  8366. };
  8367. VertexBuffer.prototype.dispose = function () {
  8368. if (!this._buffer) {
  8369. return;
  8370. }
  8371. if (this._engine._releaseBuffer(this._buffer)) {
  8372. this._buffer = null;
  8373. }
  8374. };
  8375. Object.defineProperty(VertexBuffer, "PositionKind", {
  8376. get: function () {
  8377. return VertexBuffer._PositionKind;
  8378. },
  8379. enumerable: true,
  8380. configurable: true
  8381. });
  8382. Object.defineProperty(VertexBuffer, "NormalKind", {
  8383. get: function () {
  8384. return VertexBuffer._NormalKind;
  8385. },
  8386. enumerable: true,
  8387. configurable: true
  8388. });
  8389. Object.defineProperty(VertexBuffer, "UVKind", {
  8390. get: function () {
  8391. return VertexBuffer._UVKind;
  8392. },
  8393. enumerable: true,
  8394. configurable: true
  8395. });
  8396. Object.defineProperty(VertexBuffer, "UV2Kind", {
  8397. get: function () {
  8398. return VertexBuffer._UV2Kind;
  8399. },
  8400. enumerable: true,
  8401. configurable: true
  8402. });
  8403. Object.defineProperty(VertexBuffer, "ColorKind", {
  8404. get: function () {
  8405. return VertexBuffer._ColorKind;
  8406. },
  8407. enumerable: true,
  8408. configurable: true
  8409. });
  8410. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  8411. get: function () {
  8412. return VertexBuffer._MatricesIndicesKind;
  8413. },
  8414. enumerable: true,
  8415. configurable: true
  8416. });
  8417. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  8418. get: function () {
  8419. return VertexBuffer._MatricesWeightsKind;
  8420. },
  8421. enumerable: true,
  8422. configurable: true
  8423. });
  8424. VertexBuffer._PositionKind = "position";
  8425. VertexBuffer._NormalKind = "normal";
  8426. VertexBuffer._UVKind = "uv";
  8427. VertexBuffer._UV2Kind = "uv2";
  8428. VertexBuffer._ColorKind = "color";
  8429. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  8430. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  8431. return VertexBuffer;
  8432. })();
  8433. BABYLON.VertexBuffer = VertexBuffer;
  8434. })(BABYLON || (BABYLON = {}));
  8435. //# sourceMappingURL=babylon.vertexBuffer.js.map
  8436. var BABYLON;
  8437. (function (BABYLON) {
  8438. var AbstractMesh = (function (_super) {
  8439. __extends(AbstractMesh, _super);
  8440. function AbstractMesh(name, scene) {
  8441. _super.call(this, name, scene);
  8442. // Properties
  8443. this.position = new BABYLON.Vector3(0, 0, 0);
  8444. this.rotation = new BABYLON.Vector3(0, 0, 0);
  8445. this.scaling = new BABYLON.Vector3(1, 1, 1);
  8446. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  8447. this.visibility = 1.0;
  8448. this.alphaIndex = Number.MAX_VALUE;
  8449. this.infiniteDistance = false;
  8450. this.isVisible = true;
  8451. this.isPickable = true;
  8452. this.showBoundingBox = false;
  8453. this.showSubMeshesBoundingBox = false;
  8454. this.onDispose = null;
  8455. this.checkCollisions = false;
  8456. this.isBlocker = false;
  8457. this.renderingGroupId = 0;
  8458. this.receiveShadows = false;
  8459. this.renderOutline = false;
  8460. this.outlineColor = BABYLON.Color3.Red();
  8461. this.outlineWidth = 0.02;
  8462. this.renderOverlay = false;
  8463. this.overlayColor = BABYLON.Color3.Red();
  8464. this.overlayAlpha = 0.5;
  8465. this.hasVertexAlpha = false;
  8466. this.useVertexColors = true;
  8467. this.applyFog = true;
  8468. this.useOctreeForRenderingSelection = true;
  8469. this.useOctreeForPicking = true;
  8470. this.useOctreeForCollisions = true;
  8471. this.layerMask = 0xFFFFFFFF;
  8472. // Physics
  8473. this._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  8474. // Collisions
  8475. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  8476. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  8477. this._collider = new BABYLON.Collider();
  8478. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  8479. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  8480. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  8481. // Cache
  8482. this._localScaling = BABYLON.Matrix.Zero();
  8483. this._localRotation = BABYLON.Matrix.Zero();
  8484. this._localTranslation = BABYLON.Matrix.Zero();
  8485. this._localBillboard = BABYLON.Matrix.Zero();
  8486. this._localPivotScaling = BABYLON.Matrix.Zero();
  8487. this._localPivotScalingRotation = BABYLON.Matrix.Zero();
  8488. this._localWorld = BABYLON.Matrix.Zero();
  8489. this._worldMatrix = BABYLON.Matrix.Zero();
  8490. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  8491. this._absolutePosition = BABYLON.Vector3.Zero();
  8492. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  8493. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  8494. this._isDirty = false;
  8495. this._pivotMatrix = BABYLON.Matrix.Identity();
  8496. this._isDisposed = false;
  8497. this._renderId = 0;
  8498. this._intersectionsInProgress = new Array();
  8499. this._onAfterWorldMatrixUpdate = new Array();
  8500. scene.meshes.push(this);
  8501. }
  8502. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  8503. get: function () {
  8504. return AbstractMesh._BILLBOARDMODE_NONE;
  8505. },
  8506. enumerable: true,
  8507. configurable: true
  8508. });
  8509. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  8510. get: function () {
  8511. return AbstractMesh._BILLBOARDMODE_X;
  8512. },
  8513. enumerable: true,
  8514. configurable: true
  8515. });
  8516. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  8517. get: function () {
  8518. return AbstractMesh._BILLBOARDMODE_Y;
  8519. },
  8520. enumerable: true,
  8521. configurable: true
  8522. });
  8523. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  8524. get: function () {
  8525. return AbstractMesh._BILLBOARDMODE_Z;
  8526. },
  8527. enumerable: true,
  8528. configurable: true
  8529. });
  8530. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  8531. get: function () {
  8532. return AbstractMesh._BILLBOARDMODE_ALL;
  8533. },
  8534. enumerable: true,
  8535. configurable: true
  8536. });
  8537. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  8538. // Methods
  8539. get: function () {
  8540. return false;
  8541. },
  8542. enumerable: true,
  8543. configurable: true
  8544. });
  8545. AbstractMesh.prototype.getLOD = function (camera) {
  8546. return this;
  8547. };
  8548. AbstractMesh.prototype.getTotalVertices = function () {
  8549. return 0;
  8550. };
  8551. AbstractMesh.prototype.getIndices = function () {
  8552. return null;
  8553. };
  8554. AbstractMesh.prototype.getVerticesData = function (kind) {
  8555. return null;
  8556. };
  8557. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  8558. return false;
  8559. };
  8560. AbstractMesh.prototype.getBoundingInfo = function () {
  8561. if (this._masterMesh) {
  8562. return this._masterMesh.getBoundingInfo();
  8563. }
  8564. if (!this._boundingInfo) {
  8565. this._updateBoundingInfo();
  8566. }
  8567. return this._boundingInfo;
  8568. };
  8569. AbstractMesh.prototype._preActivate = function () {
  8570. };
  8571. AbstractMesh.prototype._activate = function (renderId) {
  8572. this._renderId = renderId;
  8573. };
  8574. AbstractMesh.prototype.getWorldMatrix = function () {
  8575. if (this._masterMesh) {
  8576. return this._masterMesh.getWorldMatrix();
  8577. }
  8578. if (this._currentRenderId !== this.getScene().getRenderId()) {
  8579. this.computeWorldMatrix();
  8580. }
  8581. return this._worldMatrix;
  8582. };
  8583. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  8584. get: function () {
  8585. return this._worldMatrix;
  8586. },
  8587. enumerable: true,
  8588. configurable: true
  8589. });
  8590. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  8591. get: function () {
  8592. return this._absolutePosition;
  8593. },
  8594. enumerable: true,
  8595. configurable: true
  8596. });
  8597. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  8598. if (!this.rotationQuaternion) {
  8599. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  8600. this.rotation = BABYLON.Vector3.Zero();
  8601. }
  8602. if (!space || space == 0 /* LOCAL */) {
  8603. var rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  8604. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  8605. } else {
  8606. if (this.parent) {
  8607. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  8608. invertParentWorldMatrix.invert();
  8609. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  8610. }
  8611. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  8612. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  8613. }
  8614. };
  8615. AbstractMesh.prototype.translate = function (axis, distance, space) {
  8616. var displacementVector = axis.scale(distance);
  8617. if (!space || space == 0 /* LOCAL */) {
  8618. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  8619. this.setPositionWithLocalVector(tempV3);
  8620. } else {
  8621. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  8622. }
  8623. };
  8624. AbstractMesh.prototype.getAbsolutePosition = function () {
  8625. this.computeWorldMatrix();
  8626. return this._absolutePosition;
  8627. };
  8628. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  8629. if (!absolutePosition) {
  8630. return;
  8631. }
  8632. var absolutePositionX;
  8633. var absolutePositionY;
  8634. var absolutePositionZ;
  8635. if (absolutePosition.x === undefined) {
  8636. if (arguments.length < 3) {
  8637. return;
  8638. }
  8639. absolutePositionX = arguments[0];
  8640. absolutePositionY = arguments[1];
  8641. absolutePositionZ = arguments[2];
  8642. } else {
  8643. absolutePositionX = absolutePosition.x;
  8644. absolutePositionY = absolutePosition.y;
  8645. absolutePositionZ = absolutePosition.z;
  8646. }
  8647. if (this.parent) {
  8648. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  8649. invertParentWorldMatrix.invert();
  8650. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  8651. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  8652. } else {
  8653. this.position.x = absolutePositionX;
  8654. this.position.y = absolutePositionY;
  8655. this.position.z = absolutePositionZ;
  8656. }
  8657. };
  8658. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  8659. this._pivotMatrix = matrix;
  8660. this._cache.pivotMatrixUpdated = true;
  8661. };
  8662. AbstractMesh.prototype.getPivotMatrix = function () {
  8663. return this._pivotMatrix;
  8664. };
  8665. AbstractMesh.prototype._isSynchronized = function () {
  8666. if (this._isDirty) {
  8667. return false;
  8668. }
  8669. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  8670. return false;
  8671. if (this._cache.pivotMatrixUpdated) {
  8672. return false;
  8673. }
  8674. if (this.infiniteDistance) {
  8675. return false;
  8676. }
  8677. if (!this._cache.position.equals(this.position))
  8678. return false;
  8679. if (this.rotationQuaternion) {
  8680. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  8681. return false;
  8682. } else {
  8683. if (!this._cache.rotation.equals(this.rotation))
  8684. return false;
  8685. }
  8686. if (!this._cache.scaling.equals(this.scaling))
  8687. return false;
  8688. return true;
  8689. };
  8690. AbstractMesh.prototype._initCache = function () {
  8691. _super.prototype._initCache.call(this);
  8692. this._cache.localMatrixUpdated = false;
  8693. this._cache.position = BABYLON.Vector3.Zero();
  8694. this._cache.scaling = BABYLON.Vector3.Zero();
  8695. this._cache.rotation = BABYLON.Vector3.Zero();
  8696. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  8697. };
  8698. AbstractMesh.prototype.markAsDirty = function (property) {
  8699. if (property === "rotation") {
  8700. this.rotationQuaternion = null;
  8701. }
  8702. this._currentRenderId = Number.MAX_VALUE;
  8703. this._isDirty = true;
  8704. };
  8705. AbstractMesh.prototype._updateBoundingInfo = function () {
  8706. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  8707. this._boundingInfo._update(this.worldMatrixFromCache);
  8708. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  8709. };
  8710. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  8711. if (!this.subMeshes) {
  8712. return;
  8713. }
  8714. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  8715. var subMesh = this.subMeshes[subIndex];
  8716. subMesh.updateBoundingInfo(matrix);
  8717. }
  8718. };
  8719. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  8720. if (!force && (this._currentRenderId == this.getScene().getRenderId() || this.isSynchronized(true))) {
  8721. return this._worldMatrix;
  8722. }
  8723. this._cache.position.copyFrom(this.position);
  8724. this._cache.scaling.copyFrom(this.scaling);
  8725. this._cache.pivotMatrixUpdated = false;
  8726. this._currentRenderId = this.getScene().getRenderId();
  8727. this._isDirty = false;
  8728. // Scaling
  8729. BABYLON.Matrix.ScalingToRef(this.scaling.x, this.scaling.y, this.scaling.z, this._localScaling);
  8730. // Rotation
  8731. if (this.rotationQuaternion) {
  8732. this.rotationQuaternion.toRotationMatrix(this._localRotation);
  8733. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  8734. } else {
  8735. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._localRotation);
  8736. this._cache.rotation.copyFrom(this.rotation);
  8737. }
  8738. // Translation
  8739. if (this.infiniteDistance && !this.parent) {
  8740. var camera = this.getScene().activeCamera;
  8741. var cameraWorldMatrix = camera.getWorldMatrix();
  8742. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  8743. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, this._localTranslation);
  8744. } else {
  8745. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._localTranslation);
  8746. }
  8747. // Composing transformations
  8748. this._pivotMatrix.multiplyToRef(this._localScaling, this._localPivotScaling);
  8749. this._localPivotScaling.multiplyToRef(this._localRotation, this._localPivotScalingRotation);
  8750. // Billboarding
  8751. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  8752. var localPosition = this.position.clone();
  8753. var zero = this.getScene().activeCamera.position.clone();
  8754. if (this.parent && this.parent.position) {
  8755. localPosition.addInPlace(this.parent.position);
  8756. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, this._localTranslation);
  8757. }
  8758. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) === AbstractMesh.BILLBOARDMODE_ALL) {
  8759. zero = this.getScene().activeCamera.position;
  8760. } else {
  8761. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X)
  8762. zero.x = localPosition.x + BABYLON.Engine.Epsilon;
  8763. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y)
  8764. zero.y = localPosition.y + 0.001;
  8765. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z)
  8766. zero.z = localPosition.z + 0.001;
  8767. }
  8768. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), this._localBillboard);
  8769. this._localBillboard.m[12] = this._localBillboard.m[13] = this._localBillboard.m[14] = 0;
  8770. this._localBillboard.invert();
  8771. this._localPivotScalingRotation.multiplyToRef(this._localBillboard, this._localWorld);
  8772. this._rotateYByPI.multiplyToRef(this._localWorld, this._localPivotScalingRotation);
  8773. }
  8774. // Local world
  8775. this._localPivotScalingRotation.multiplyToRef(this._localTranslation, this._localWorld);
  8776. // Parent
  8777. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  8778. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  8779. } else {
  8780. this._worldMatrix.copyFrom(this._localWorld);
  8781. }
  8782. // Bounding info
  8783. this._updateBoundingInfo();
  8784. // Absolute position
  8785. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  8786. for (var callbackIndex = 0; callbackIndex < this._onAfterWorldMatrixUpdate.length; callbackIndex++) {
  8787. this._onAfterWorldMatrixUpdate[callbackIndex](this);
  8788. }
  8789. return this._worldMatrix;
  8790. };
  8791. /**
  8792. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  8793. * @param func: callback function to add
  8794. */
  8795. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  8796. this._onAfterWorldMatrixUpdate.push(func);
  8797. };
  8798. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  8799. var index = this._onAfterWorldMatrixUpdate.indexOf(func);
  8800. if (index > -1) {
  8801. this._onAfterWorldMatrixUpdate.splice(index, 1);
  8802. }
  8803. };
  8804. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  8805. this.computeWorldMatrix();
  8806. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  8807. };
  8808. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  8809. this.computeWorldMatrix();
  8810. var invLocalWorldMatrix = this._localWorld.clone();
  8811. invLocalWorldMatrix.invert();
  8812. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  8813. };
  8814. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  8815. this.computeWorldMatrix();
  8816. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  8817. };
  8818. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  8819. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  8820. /// <param name="targetPoint" type="BABYLON.Vector3">The position (must be in same space as current mesh) to look at</param>
  8821. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  8822. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  8823. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  8824. /// <returns>Mesh oriented towards targetMesh</returns>
  8825. yawCor = yawCor || 0; // default to zero if undefined
  8826. pitchCor = pitchCor || 0;
  8827. rollCor = rollCor || 0;
  8828. var dv = targetPoint.subtract(this.position);
  8829. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  8830. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  8831. var pitch = Math.atan2(dv.y, len);
  8832. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  8833. };
  8834. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  8835. if (!this._boundingInfo.isInFrustum(frustumPlanes)) {
  8836. return false;
  8837. }
  8838. return true;
  8839. };
  8840. AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
  8841. if (!camera) {
  8842. camera = this.getScene().activeCamera;
  8843. }
  8844. var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
  8845. if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
  8846. return false;
  8847. }
  8848. return true;
  8849. };
  8850. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  8851. if (!this._boundingInfo || !mesh._boundingInfo) {
  8852. return false;
  8853. }
  8854. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  8855. };
  8856. AbstractMesh.prototype.intersectsPoint = function (point) {
  8857. if (!this._boundingInfo) {
  8858. return false;
  8859. }
  8860. return this._boundingInfo.intersectsPoint(point);
  8861. };
  8862. // Physics
  8863. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  8864. var physicsEngine = this.getScene().getPhysicsEngine();
  8865. if (!physicsEngine) {
  8866. return;
  8867. }
  8868. if (impostor.impostor) {
  8869. // Old API
  8870. options = impostor;
  8871. impostor = impostor.impostor;
  8872. }
  8873. impostor = impostor || BABYLON.PhysicsEngine.NoImpostor;
  8874. if (impostor === BABYLON.PhysicsEngine.NoImpostor) {
  8875. physicsEngine._unregisterMesh(this);
  8876. return;
  8877. }
  8878. options.mass = options.mass || 0;
  8879. options.friction = options.friction || 0.2;
  8880. options.restitution = options.restitution || 0.2;
  8881. this._physicImpostor = impostor;
  8882. this._physicsMass = options.mass;
  8883. this._physicsFriction = options.friction;
  8884. this._physicRestitution = options.restitution;
  8885. return physicsEngine._registerMesh(this, impostor, options);
  8886. };
  8887. AbstractMesh.prototype.getPhysicsImpostor = function () {
  8888. if (!this._physicImpostor) {
  8889. return BABYLON.PhysicsEngine.NoImpostor;
  8890. }
  8891. return this._physicImpostor;
  8892. };
  8893. AbstractMesh.prototype.getPhysicsMass = function () {
  8894. if (!this._physicsMass) {
  8895. return 0;
  8896. }
  8897. return this._physicsMass;
  8898. };
  8899. AbstractMesh.prototype.getPhysicsFriction = function () {
  8900. if (!this._physicsFriction) {
  8901. return 0;
  8902. }
  8903. return this._physicsFriction;
  8904. };
  8905. AbstractMesh.prototype.getPhysicsRestitution = function () {
  8906. if (!this._physicRestitution) {
  8907. return 0;
  8908. }
  8909. return this._physicRestitution;
  8910. };
  8911. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  8912. if (!camera) {
  8913. camera = this.getScene().activeCamera;
  8914. }
  8915. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  8916. };
  8917. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  8918. if (!camera) {
  8919. camera = this.getScene().activeCamera;
  8920. }
  8921. return this.absolutePosition.subtract(camera.position).length();
  8922. };
  8923. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  8924. if (!this._physicImpostor) {
  8925. return;
  8926. }
  8927. this.getScene().getPhysicsEngine()._applyImpulse(this, force, contactPoint);
  8928. };
  8929. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  8930. if (!this._physicImpostor) {
  8931. return;
  8932. }
  8933. this.getScene().getPhysicsEngine()._createLink(this, otherMesh, pivot1, pivot2, options);
  8934. };
  8935. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  8936. if (!this._physicImpostor) {
  8937. return;
  8938. }
  8939. this.getScene().getPhysicsEngine()._updateBodyPosition(this);
  8940. };
  8941. // Collisions
  8942. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  8943. var globalPosition = this.getAbsolutePosition();
  8944. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  8945. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  8946. this._collider.radius = this.ellipsoid;
  8947. this.getScene()._getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this._newPositionForCollisions, this);
  8948. this._newPositionForCollisions.subtractToRef(this._oldPositionForCollisions, this._diffPositionForCollisions);
  8949. if (this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  8950. this.position.addInPlace(this._diffPositionForCollisions);
  8951. }
  8952. };
  8953. // Submeshes octree
  8954. /**
  8955. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  8956. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  8957. */
  8958. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  8959. if (typeof maxCapacity === "undefined") { maxCapacity = 64; }
  8960. if (typeof maxDepth === "undefined") { maxDepth = 2; }
  8961. if (!this._submeshesOctree) {
  8962. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  8963. }
  8964. this.computeWorldMatrix(true);
  8965. // Update octree
  8966. var bbox = this.getBoundingInfo().boundingBox;
  8967. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  8968. return this._submeshesOctree;
  8969. };
  8970. // Collisions
  8971. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  8972. this._generatePointsArray();
  8973. // Transformation
  8974. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  8975. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  8976. subMesh._lastColliderWorldVertices = [];
  8977. subMesh._trianglePlanes = [];
  8978. var start = subMesh.verticesStart;
  8979. var end = (subMesh.verticesStart + subMesh.verticesCount);
  8980. for (var i = start; i < end; i++) {
  8981. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  8982. }
  8983. }
  8984. // Collide
  8985. collider._collide(subMesh, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart);
  8986. };
  8987. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  8988. var subMeshes;
  8989. var len;
  8990. // Octrees
  8991. if (this._submeshesOctree && this.useOctreeForCollisions) {
  8992. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  8993. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  8994. len = intersections.length;
  8995. subMeshes = intersections.data;
  8996. } else {
  8997. subMeshes = this.subMeshes;
  8998. len = subMeshes.length;
  8999. }
  9000. for (var index = 0; index < len; index++) {
  9001. var subMesh = subMeshes[index];
  9002. // Bounding test
  9003. if (len > 1 && !subMesh._checkCollision(collider))
  9004. continue;
  9005. this._collideForSubMesh(subMesh, transformMatrix, collider);
  9006. }
  9007. };
  9008. AbstractMesh.prototype._checkCollision = function (collider) {
  9009. // Bounding box test
  9010. if (!this._boundingInfo._checkCollision(collider))
  9011. return;
  9012. // Transformation matrix
  9013. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  9014. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  9015. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  9016. };
  9017. // Picking
  9018. AbstractMesh.prototype._generatePointsArray = function () {
  9019. return false;
  9020. };
  9021. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  9022. var pickingInfo = new BABYLON.PickingInfo();
  9023. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  9024. return pickingInfo;
  9025. }
  9026. if (!this._generatePointsArray()) {
  9027. return pickingInfo;
  9028. }
  9029. var intersectInfo = null;
  9030. // Octrees
  9031. var subMeshes;
  9032. var len;
  9033. if (this._submeshesOctree && this.useOctreeForPicking) {
  9034. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  9035. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  9036. len = intersections.length;
  9037. subMeshes = intersections.data;
  9038. } else {
  9039. subMeshes = this.subMeshes;
  9040. len = subMeshes.length;
  9041. }
  9042. for (var index = 0; index < len; index++) {
  9043. var subMesh = subMeshes[index];
  9044. // Bounding test
  9045. if (len > 1 && !subMesh.canIntersects(ray))
  9046. continue;
  9047. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  9048. if (currentIntersectInfo) {
  9049. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  9050. intersectInfo = currentIntersectInfo;
  9051. if (fastCheck) {
  9052. break;
  9053. }
  9054. }
  9055. }
  9056. }
  9057. if (intersectInfo) {
  9058. // Get picked point
  9059. var world = this.getWorldMatrix();
  9060. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  9061. var direction = ray.direction.clone();
  9062. direction.normalize();
  9063. direction = direction.scale(intersectInfo.distance);
  9064. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  9065. var pickedPoint = worldOrigin.add(worldDirection);
  9066. // Return result
  9067. pickingInfo.hit = true;
  9068. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  9069. pickingInfo.pickedPoint = pickedPoint;
  9070. pickingInfo.pickedMesh = this;
  9071. pickingInfo.bu = intersectInfo.bu;
  9072. pickingInfo.bv = intersectInfo.bv;
  9073. pickingInfo.faceId = intersectInfo.faceId;
  9074. return pickingInfo;
  9075. }
  9076. return pickingInfo;
  9077. };
  9078. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  9079. return null;
  9080. };
  9081. AbstractMesh.prototype.releaseSubMeshes = function () {
  9082. if (this.subMeshes) {
  9083. while (this.subMeshes.length) {
  9084. this.subMeshes[0].dispose();
  9085. }
  9086. } else {
  9087. this.subMeshes = new Array();
  9088. }
  9089. };
  9090. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  9091. // Physics
  9092. if (this.getPhysicsImpostor() != BABYLON.PhysicsEngine.NoImpostor) {
  9093. this.setPhysicsState(BABYLON.PhysicsEngine.NoImpostor);
  9094. }
  9095. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  9096. var other = this._intersectionsInProgress[index];
  9097. var pos = other._intersectionsInProgress.indexOf(this);
  9098. other._intersectionsInProgress.splice(pos, 1);
  9099. }
  9100. this._intersectionsInProgress = [];
  9101. // SubMeshes
  9102. this.releaseSubMeshes();
  9103. // Remove from scene
  9104. var index = this.getScene().meshes.indexOf(this);
  9105. if (index != -1) {
  9106. // Remove from the scene if mesh found
  9107. this.getScene().meshes.splice(index, 1);
  9108. }
  9109. if (!doNotRecurse) {
  9110. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  9111. if (this.getScene().particleSystems[index].emitter == this) {
  9112. this.getScene().particleSystems[index].dispose();
  9113. index--;
  9114. }
  9115. }
  9116. // Children
  9117. var objects = this.getScene().meshes.slice(0);
  9118. for (index = 0; index < objects.length; index++) {
  9119. if (objects[index].parent == this) {
  9120. objects[index].dispose();
  9121. }
  9122. }
  9123. } else {
  9124. for (index = 0; index < this.getScene().meshes.length; index++) {
  9125. var obj = this.getScene().meshes[index];
  9126. if (obj.parent === this) {
  9127. obj.parent = null;
  9128. obj.computeWorldMatrix(true);
  9129. }
  9130. }
  9131. }
  9132. this._onAfterWorldMatrixUpdate = [];
  9133. this._isDisposed = true;
  9134. // Callback
  9135. if (this.onDispose) {
  9136. this.onDispose();
  9137. }
  9138. };
  9139. AbstractMesh._BILLBOARDMODE_NONE = 0;
  9140. AbstractMesh._BILLBOARDMODE_X = 1;
  9141. AbstractMesh._BILLBOARDMODE_Y = 2;
  9142. AbstractMesh._BILLBOARDMODE_Z = 4;
  9143. AbstractMesh._BILLBOARDMODE_ALL = 7;
  9144. return AbstractMesh;
  9145. })(BABYLON.Node);
  9146. BABYLON.AbstractMesh = AbstractMesh;
  9147. })(BABYLON || (BABYLON = {}));
  9148. //# sourceMappingURL=babylon.abstractMesh.js.map
  9149. var BABYLON;
  9150. (function (BABYLON) {
  9151. var _InstancesBatch = (function () {
  9152. function _InstancesBatch() {
  9153. this.mustReturn = false;
  9154. this.visibleInstances = new Array();
  9155. this.renderSelf = new Array();
  9156. }
  9157. return _InstancesBatch;
  9158. })();
  9159. BABYLON._InstancesBatch = _InstancesBatch;
  9160. var Mesh = (function (_super) {
  9161. __extends(Mesh, _super);
  9162. /**
  9163. * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
  9164. * @param {BABYLON.Scene} scene - The scene to add this mesh to.
  9165. * @param {BABYLON.Node} parent - The parent of this mesh, if it has one
  9166. * @param {BABYLON.Mesh} source - An optional Mesh from which geometry is shared, cloned.
  9167. * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
  9168. * When false, achieved by calling a clone(), also passing False.
  9169. * This will make creation of children, recursive.
  9170. */
  9171. function Mesh(name, scene, parent, source, doNotCloneChildren) {
  9172. if (typeof parent === "undefined") { parent = null; }
  9173. _super.call(this, name, scene);
  9174. // Members
  9175. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  9176. this.instances = new Array();
  9177. this._LODLevels = new Array();
  9178. this._onBeforeRenderCallbacks = new Array();
  9179. this._onAfterRenderCallbacks = new Array();
  9180. this._visibleInstances = {};
  9181. this._renderIdForInstances = new Array();
  9182. this._batchCache = new _InstancesBatch();
  9183. this._instancesBufferSize = 32 * 16 * 4;
  9184. if (source) {
  9185. // Geometry
  9186. if (source._geometry) {
  9187. source._geometry.applyToMesh(this);
  9188. }
  9189. // Deep copy
  9190. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton"], []);
  9191. // Material
  9192. this.material = source.material;
  9193. if (!doNotCloneChildren) {
  9194. for (var index = 0; index < scene.meshes.length; index++) {
  9195. var mesh = scene.meshes[index];
  9196. if (mesh.parent === source) {
  9197. // doNotCloneChildren is always going to be False
  9198. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  9199. }
  9200. }
  9201. }
  9202. for (index = 0; index < scene.particleSystems.length; index++) {
  9203. var system = scene.particleSystems[index];
  9204. if (system.emitter === source) {
  9205. system.clone(system.name, this);
  9206. }
  9207. }
  9208. this.computeWorldMatrix(true);
  9209. }
  9210. // Parent
  9211. if (parent !== null) {
  9212. this.parent = parent;
  9213. }
  9214. }
  9215. Mesh.prototype._clone = function () {
  9216. };
  9217. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  9218. // Methods
  9219. get: function () {
  9220. return this._LODLevels.length > 0;
  9221. },
  9222. enumerable: true,
  9223. configurable: true
  9224. });
  9225. Mesh.prototype._sortLODLevels = function () {
  9226. this._LODLevels.sort(function (a, b) {
  9227. if (a.distance < b.distance) {
  9228. return 1;
  9229. }
  9230. if (a.distance > b.distance) {
  9231. return -1;
  9232. }
  9233. return 0;
  9234. });
  9235. };
  9236. Mesh.prototype.addLODLevel = function (distance, mesh) {
  9237. if (mesh && mesh._masterMesh) {
  9238. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  9239. return this;
  9240. }
  9241. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  9242. this._LODLevels.push(level);
  9243. if (mesh) {
  9244. mesh._masterMesh = this;
  9245. }
  9246. this._sortLODLevels();
  9247. return this;
  9248. };
  9249. Mesh.prototype.removeLODLevel = function (mesh) {
  9250. for (var index = 0; index < this._LODLevels.length; index++) {
  9251. if (this._LODLevels[index].mesh === mesh) {
  9252. this._LODLevels.splice(index, 1);
  9253. if (mesh) {
  9254. mesh._masterMesh = null;
  9255. }
  9256. }
  9257. }
  9258. this._sortLODLevels();
  9259. return this;
  9260. };
  9261. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  9262. if (!this._LODLevels || this._LODLevels.length === 0) {
  9263. return this;
  9264. }
  9265. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.position).length();
  9266. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  9267. return this;
  9268. }
  9269. for (var index = 0; index < this._LODLevels.length; index++) {
  9270. var level = this._LODLevels[index];
  9271. if (level.distance < distanceToCamera) {
  9272. if (level.mesh) {
  9273. level.mesh._preActivate();
  9274. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  9275. }
  9276. return level.mesh;
  9277. }
  9278. }
  9279. return this;
  9280. };
  9281. Object.defineProperty(Mesh.prototype, "geometry", {
  9282. get: function () {
  9283. return this._geometry;
  9284. },
  9285. enumerable: true,
  9286. configurable: true
  9287. });
  9288. Mesh.prototype.getTotalVertices = function () {
  9289. if (!this._geometry) {
  9290. return 0;
  9291. }
  9292. return this._geometry.getTotalVertices();
  9293. };
  9294. Mesh.prototype.getVerticesData = function (kind) {
  9295. if (!this._geometry) {
  9296. return null;
  9297. }
  9298. return this._geometry.getVerticesData(kind);
  9299. };
  9300. Mesh.prototype.getVertexBuffer = function (kind) {
  9301. if (!this._geometry) {
  9302. return undefined;
  9303. }
  9304. return this._geometry.getVertexBuffer(kind);
  9305. };
  9306. Mesh.prototype.isVerticesDataPresent = function (kind) {
  9307. if (!this._geometry) {
  9308. if (this._delayInfo) {
  9309. return this._delayInfo.indexOf(kind) !== -1;
  9310. }
  9311. return false;
  9312. }
  9313. return this._geometry.isVerticesDataPresent(kind);
  9314. };
  9315. Mesh.prototype.getVerticesDataKinds = function () {
  9316. if (!this._geometry) {
  9317. var result = [];
  9318. if (this._delayInfo) {
  9319. for (var kind in this._delayInfo) {
  9320. result.push(kind);
  9321. }
  9322. }
  9323. return result;
  9324. }
  9325. return this._geometry.getVerticesDataKinds();
  9326. };
  9327. Mesh.prototype.getTotalIndices = function () {
  9328. if (!this._geometry) {
  9329. return 0;
  9330. }
  9331. return this._geometry.getTotalIndices();
  9332. };
  9333. Mesh.prototype.getIndices = function () {
  9334. if (!this._geometry) {
  9335. return [];
  9336. }
  9337. return this._geometry.getIndices();
  9338. };
  9339. Object.defineProperty(Mesh.prototype, "isBlocked", {
  9340. get: function () {
  9341. return this._masterMesh !== null && this._masterMesh !== undefined;
  9342. },
  9343. enumerable: true,
  9344. configurable: true
  9345. });
  9346. Mesh.prototype.isReady = function () {
  9347. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  9348. return false;
  9349. }
  9350. return _super.prototype.isReady.call(this);
  9351. };
  9352. Mesh.prototype.isDisposed = function () {
  9353. return this._isDisposed;
  9354. };
  9355. // Methods
  9356. Mesh.prototype._preActivate = function () {
  9357. var sceneRenderId = this.getScene().getRenderId();
  9358. if (this._preActivateId == sceneRenderId) {
  9359. return;
  9360. }
  9361. this._preActivateId = sceneRenderId;
  9362. this._visibleInstances = null;
  9363. };
  9364. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  9365. if (!this._visibleInstances) {
  9366. this._visibleInstances = {};
  9367. this._visibleInstances.defaultRenderId = renderId;
  9368. this._visibleInstances.selfDefaultRenderId = this._renderId;
  9369. }
  9370. if (!this._visibleInstances[renderId]) {
  9371. this._visibleInstances[renderId] = new Array();
  9372. }
  9373. this._visibleInstances[renderId].push(instance);
  9374. };
  9375. Mesh.prototype.refreshBoundingInfo = function () {
  9376. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  9377. if (data) {
  9378. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  9379. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  9380. }
  9381. if (this.subMeshes) {
  9382. for (var index = 0; index < this.subMeshes.length; index++) {
  9383. this.subMeshes[index].refreshBoundingInfo();
  9384. }
  9385. }
  9386. this._updateBoundingInfo();
  9387. };
  9388. Mesh.prototype._createGlobalSubMesh = function () {
  9389. var totalVertices = this.getTotalVertices();
  9390. if (!totalVertices || !this.getIndices()) {
  9391. return null;
  9392. }
  9393. this.releaseSubMeshes();
  9394. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  9395. };
  9396. Mesh.prototype.subdivide = function (count) {
  9397. if (count < 1) {
  9398. return;
  9399. }
  9400. var totalIndices = this.getTotalIndices();
  9401. var subdivisionSize = (totalIndices / count) | 0;
  9402. var offset = 0;
  9403. while (subdivisionSize % 3 != 0) {
  9404. subdivisionSize++;
  9405. }
  9406. this.releaseSubMeshes();
  9407. for (var index = 0; index < count; index++) {
  9408. if (offset >= totalIndices) {
  9409. break;
  9410. }
  9411. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  9412. offset += subdivisionSize;
  9413. }
  9414. this.synchronizeInstances();
  9415. };
  9416. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  9417. if (kind instanceof Array) {
  9418. var temp = data;
  9419. data = kind;
  9420. kind = temp;
  9421. BABYLON.Tools.Warn("Deprecated usage of setVerticesData detected (since v1.12). Current signature is setVerticesData(kind, data, updatable).");
  9422. }
  9423. if (!this._geometry) {
  9424. var vertexData = new BABYLON.VertexData();
  9425. vertexData.set(data, kind);
  9426. var scene = this.getScene();
  9427. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  9428. } else {
  9429. this._geometry.setVerticesData(kind, data, updatable, stride);
  9430. }
  9431. };
  9432. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  9433. if (!this._geometry) {
  9434. return;
  9435. }
  9436. if (!makeItUnique) {
  9437. this._geometry.updateVerticesData(kind, data, updateExtends);
  9438. } else {
  9439. this.makeGeometryUnique();
  9440. this.updateVerticesData(kind, data, updateExtends, false);
  9441. }
  9442. };
  9443. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  9444. if (!this._geometry) {
  9445. return;
  9446. }
  9447. if (!makeItUnique) {
  9448. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  9449. } else {
  9450. this.makeGeometryUnique();
  9451. this.updateVerticesDataDirectly(kind, data, offset, false);
  9452. }
  9453. };
  9454. Mesh.prototype.makeGeometryUnique = function () {
  9455. if (!this._geometry) {
  9456. return;
  9457. }
  9458. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  9459. geometry.applyToMesh(this);
  9460. };
  9461. Mesh.prototype.setIndices = function (indices, totalVertices) {
  9462. if (!this._geometry) {
  9463. var vertexData = new BABYLON.VertexData();
  9464. vertexData.indices = indices;
  9465. var scene = this.getScene();
  9466. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  9467. } else {
  9468. this._geometry.setIndices(indices, totalVertices);
  9469. }
  9470. };
  9471. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  9472. var engine = this.getScene().getEngine();
  9473. // Wireframe
  9474. var indexToBind;
  9475. switch (fillMode) {
  9476. case BABYLON.Material.PointFillMode:
  9477. indexToBind = null;
  9478. break;
  9479. case BABYLON.Material.WireFrameFillMode:
  9480. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  9481. break;
  9482. default:
  9483. case BABYLON.Material.TriangleFillMode:
  9484. indexToBind = this._geometry.getIndexBuffer();
  9485. break;
  9486. }
  9487. // VBOs
  9488. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  9489. };
  9490. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  9491. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  9492. return;
  9493. }
  9494. var engine = this.getScene().getEngine();
  9495. switch (fillMode) {
  9496. case BABYLON.Material.PointFillMode:
  9497. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  9498. break;
  9499. case BABYLON.Material.WireFrameFillMode:
  9500. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  9501. break;
  9502. default:
  9503. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  9504. }
  9505. };
  9506. Mesh.prototype.registerBeforeRender = function (func) {
  9507. this._onBeforeRenderCallbacks.push(func);
  9508. };
  9509. Mesh.prototype.unregisterBeforeRender = function (func) {
  9510. var index = this._onBeforeRenderCallbacks.indexOf(func);
  9511. if (index > -1) {
  9512. this._onBeforeRenderCallbacks.splice(index, 1);
  9513. }
  9514. };
  9515. Mesh.prototype.registerAfterRender = function (func) {
  9516. this._onAfterRenderCallbacks.push(func);
  9517. };
  9518. Mesh.prototype.unregisterAfterRender = function (func) {
  9519. var index = this._onAfterRenderCallbacks.indexOf(func);
  9520. if (index > -1) {
  9521. this._onAfterRenderCallbacks.splice(index, 1);
  9522. }
  9523. };
  9524. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  9525. var scene = this.getScene();
  9526. this._batchCache.mustReturn = false;
  9527. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  9528. this._batchCache.visibleInstances[subMeshId] = null;
  9529. if (this._visibleInstances) {
  9530. var currentRenderId = scene.getRenderId();
  9531. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  9532. var selfRenderId = this._renderId;
  9533. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  9534. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  9535. currentRenderId = Math.max(this._visibleInstances.defaultRenderId, currentRenderId);
  9536. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  9537. }
  9538. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  9539. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  9540. this._batchCache.mustReturn = true;
  9541. return this._batchCache;
  9542. }
  9543. if (currentRenderId !== selfRenderId) {
  9544. this._batchCache.renderSelf[subMeshId] = false;
  9545. }
  9546. }
  9547. this._renderIdForInstances[subMeshId] = currentRenderId;
  9548. }
  9549. return this._batchCache;
  9550. };
  9551. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  9552. var visibleInstances = batch.visibleInstances[subMesh._id];
  9553. var matricesCount = visibleInstances.length + 1;
  9554. var bufferSize = matricesCount * 16 * 4;
  9555. while (this._instancesBufferSize < bufferSize) {
  9556. this._instancesBufferSize *= 2;
  9557. }
  9558. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  9559. if (this._worldMatricesInstancesBuffer) {
  9560. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  9561. }
  9562. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  9563. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  9564. }
  9565. var offset = 0;
  9566. var instancesCount = 0;
  9567. var world = this.getWorldMatrix();
  9568. if (batch.renderSelf[subMesh._id]) {
  9569. world.copyToArray(this._worldMatricesInstancesArray, offset);
  9570. offset += 16;
  9571. instancesCount++;
  9572. }
  9573. if (visibleInstances) {
  9574. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  9575. var instance = visibleInstances[instanceIndex];
  9576. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  9577. offset += 16;
  9578. instancesCount++;
  9579. }
  9580. }
  9581. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  9582. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  9583. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  9584. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  9585. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  9586. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  9587. this._draw(subMesh, fillMode, instancesCount);
  9588. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  9589. };
  9590. Mesh.prototype.render = function (subMesh) {
  9591. var scene = this.getScene();
  9592. // Managing instances
  9593. var batch = this._getInstancesRenderList(subMesh._id);
  9594. if (batch.mustReturn) {
  9595. return;
  9596. }
  9597. // Checking geometry state
  9598. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  9599. return;
  9600. }
  9601. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  9602. this._onBeforeRenderCallbacks[callbackIndex]();
  9603. }
  9604. var engine = scene.getEngine();
  9605. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  9606. // Material
  9607. var effectiveMaterial = subMesh.getMaterial();
  9608. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  9609. return;
  9610. }
  9611. // Outline - step 1
  9612. var savedDepthWrite = engine.getDepthWrite();
  9613. if (this.renderOutline) {
  9614. engine.setDepthWrite(false);
  9615. scene.getOutlineRenderer().render(subMesh, batch);
  9616. engine.setDepthWrite(savedDepthWrite);
  9617. }
  9618. effectiveMaterial._preBind();
  9619. var effect = effectiveMaterial.getEffect();
  9620. // Bind
  9621. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  9622. this._bind(subMesh, effect, fillMode);
  9623. var world = this.getWorldMatrix();
  9624. effectiveMaterial.bind(world, this);
  9625. // Instances rendering
  9626. if (hardwareInstancedRendering) {
  9627. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  9628. } else {
  9629. if (batch.renderSelf[subMesh._id]) {
  9630. // Draw
  9631. this._draw(subMesh, fillMode);
  9632. }
  9633. if (batch.visibleInstances[subMesh._id]) {
  9634. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  9635. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  9636. // World
  9637. world = instance.getWorldMatrix();
  9638. effectiveMaterial.bindOnlyWorldMatrix(world);
  9639. // Draw
  9640. this._draw(subMesh, fillMode);
  9641. }
  9642. }
  9643. }
  9644. // Unbind
  9645. effectiveMaterial.unbind();
  9646. // Outline - step 2
  9647. if (this.renderOutline && savedDepthWrite) {
  9648. engine.setDepthWrite(true);
  9649. engine.setColorWrite(false);
  9650. scene.getOutlineRenderer().render(subMesh, batch);
  9651. engine.setColorWrite(true);
  9652. }
  9653. // Overlay
  9654. if (this.renderOverlay) {
  9655. var currentMode = engine.getAlphaMode();
  9656. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  9657. scene.getOutlineRenderer().render(subMesh, batch, true);
  9658. engine.setAlphaMode(currentMode);
  9659. }
  9660. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  9661. this._onAfterRenderCallbacks[callbackIndex]();
  9662. }
  9663. };
  9664. Mesh.prototype.getEmittedParticleSystems = function () {
  9665. var results = new Array();
  9666. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  9667. var particleSystem = this.getScene().particleSystems[index];
  9668. if (particleSystem.emitter === this) {
  9669. results.push(particleSystem);
  9670. }
  9671. }
  9672. return results;
  9673. };
  9674. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  9675. var results = new Array();
  9676. var descendants = this.getDescendants();
  9677. descendants.push(this);
  9678. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  9679. var particleSystem = this.getScene().particleSystems[index];
  9680. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  9681. results.push(particleSystem);
  9682. }
  9683. }
  9684. return results;
  9685. };
  9686. Mesh.prototype.getChildren = function () {
  9687. var results = [];
  9688. for (var index = 0; index < this.getScene().meshes.length; index++) {
  9689. var mesh = this.getScene().meshes[index];
  9690. if (mesh.parent == this) {
  9691. results.push(mesh);
  9692. }
  9693. }
  9694. return results;
  9695. };
  9696. Mesh.prototype._checkDelayState = function () {
  9697. var _this = this;
  9698. var that = this;
  9699. var scene = this.getScene();
  9700. if (this._geometry) {
  9701. this._geometry.load(scene);
  9702. } else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  9703. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  9704. scene._addPendingData(that);
  9705. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1) ? true : false;
  9706. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  9707. if (data instanceof ArrayBuffer) {
  9708. _this._delayLoadingFunction(data, _this);
  9709. } else {
  9710. _this._delayLoadingFunction(JSON.parse(data), _this);
  9711. }
  9712. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  9713. scene._removePendingData(_this);
  9714. }, function () {
  9715. }, scene.database, getBinaryData);
  9716. }
  9717. };
  9718. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  9719. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  9720. return false;
  9721. }
  9722. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  9723. return false;
  9724. }
  9725. this._checkDelayState();
  9726. return true;
  9727. };
  9728. Mesh.prototype.setMaterialByID = function (id) {
  9729. var materials = this.getScene().materials;
  9730. for (var index = 0; index < materials.length; index++) {
  9731. if (materials[index].id == id) {
  9732. this.material = materials[index];
  9733. return;
  9734. }
  9735. }
  9736. // Multi
  9737. var multiMaterials = this.getScene().multiMaterials;
  9738. for (index = 0; index < multiMaterials.length; index++) {
  9739. if (multiMaterials[index].id == id) {
  9740. this.material = multiMaterials[index];
  9741. return;
  9742. }
  9743. }
  9744. };
  9745. Mesh.prototype.getAnimatables = function () {
  9746. var results = [];
  9747. if (this.material) {
  9748. results.push(this.material);
  9749. }
  9750. if (this.skeleton) {
  9751. results.push(this.skeleton);
  9752. }
  9753. return results;
  9754. };
  9755. // Geometry
  9756. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  9757. // Position
  9758. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  9759. return;
  9760. }
  9761. this._resetPointsArrayCache();
  9762. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  9763. var temp = [];
  9764. for (var index = 0; index < data.length; index += 3) {
  9765. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  9766. }
  9767. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  9768. // Normals
  9769. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  9770. return;
  9771. }
  9772. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  9773. for (index = 0; index < data.length; index += 3) {
  9774. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  9775. }
  9776. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  9777. };
  9778. // Cache
  9779. Mesh.prototype._resetPointsArrayCache = function () {
  9780. this._positions = null;
  9781. };
  9782. Mesh.prototype._generatePointsArray = function () {
  9783. if (this._positions)
  9784. return true;
  9785. this._positions = [];
  9786. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  9787. if (!data) {
  9788. return false;
  9789. }
  9790. for (var index = 0; index < data.length; index += 3) {
  9791. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  9792. }
  9793. return true;
  9794. };
  9795. // Clone
  9796. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  9797. return new BABYLON.Mesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  9798. };
  9799. // Dispose
  9800. Mesh.prototype.dispose = function (doNotRecurse) {
  9801. if (this._geometry) {
  9802. this._geometry.releaseForMesh(this, true);
  9803. }
  9804. // Instances
  9805. if (this._worldMatricesInstancesBuffer) {
  9806. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  9807. this._worldMatricesInstancesBuffer = null;
  9808. }
  9809. while (this.instances.length) {
  9810. this.instances[0].dispose();
  9811. }
  9812. _super.prototype.dispose.call(this, doNotRecurse);
  9813. };
  9814. // Geometric tools
  9815. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight) {
  9816. var _this = this;
  9817. var scene = this.getScene();
  9818. var onload = function (img) {
  9819. // Getting height map data
  9820. var canvas = document.createElement("canvas");
  9821. var context = canvas.getContext("2d");
  9822. var heightMapWidth = img.width;
  9823. var heightMapHeight = img.height;
  9824. canvas.width = heightMapWidth;
  9825. canvas.height = heightMapHeight;
  9826. context.drawImage(img, 0, 0);
  9827. // Create VertexData from map data
  9828. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  9829. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  9830. };
  9831. BABYLON.Tools.LoadImage(url, onload, function () {
  9832. }, scene.database);
  9833. };
  9834. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  9835. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  9836. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  9837. return;
  9838. }
  9839. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  9840. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  9841. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  9842. var position = BABYLON.Vector3.Zero();
  9843. var normal = BABYLON.Vector3.Zero();
  9844. var uv = BABYLON.Vector2.Zero();
  9845. for (var index = 0; index < positions.length; index += 3) {
  9846. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  9847. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  9848. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  9849. // Compute height
  9850. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  9851. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  9852. var pos = (u + v * heightMapWidth) * 4;
  9853. var r = buffer[pos] / 255.0;
  9854. var g = buffer[pos + 1] / 255.0;
  9855. var b = buffer[pos + 2] / 255.0;
  9856. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  9857. normal.normalize();
  9858. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  9859. position = position.add(normal);
  9860. position.toArray(positions, index);
  9861. }
  9862. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  9863. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  9864. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  9865. };
  9866. Mesh.prototype.convertToFlatShadedMesh = function () {
  9867. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  9868. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  9869. var kinds = this.getVerticesDataKinds();
  9870. var vbs = [];
  9871. var data = [];
  9872. var newdata = [];
  9873. var updatableNormals = false;
  9874. for (var kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  9875. var kind = kinds[kindIndex];
  9876. var vertexBuffer = this.getVertexBuffer(kind);
  9877. if (kind === BABYLON.VertexBuffer.NormalKind) {
  9878. updatableNormals = vertexBuffer.isUpdatable();
  9879. kinds.splice(kindIndex, 1);
  9880. kindIndex--;
  9881. continue;
  9882. }
  9883. vbs[kind] = vertexBuffer;
  9884. data[kind] = vbs[kind].getData();
  9885. newdata[kind] = [];
  9886. }
  9887. // Save previous submeshes
  9888. var previousSubmeshes = this.subMeshes.slice(0);
  9889. var indices = this.getIndices();
  9890. var totalIndices = this.getTotalIndices();
  9891. for (index = 0; index < totalIndices; index++) {
  9892. var vertexIndex = indices[index];
  9893. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  9894. kind = kinds[kindIndex];
  9895. var stride = vbs[kind].getStrideSize();
  9896. for (var offset = 0; offset < stride; offset++) {
  9897. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  9898. }
  9899. }
  9900. }
  9901. // Updating faces & normal
  9902. var normals = [];
  9903. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  9904. for (var index = 0; index < totalIndices; index += 3) {
  9905. indices[index] = index;
  9906. indices[index + 1] = index + 1;
  9907. indices[index + 2] = index + 2;
  9908. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  9909. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  9910. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  9911. var p1p2 = p1.subtract(p2);
  9912. var p3p2 = p3.subtract(p2);
  9913. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  9914. for (var localIndex = 0; localIndex < 3; localIndex++) {
  9915. normals.push(normal.x);
  9916. normals.push(normal.y);
  9917. normals.push(normal.z);
  9918. }
  9919. }
  9920. this.setIndices(indices);
  9921. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  9922. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  9923. kind = kinds[kindIndex];
  9924. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  9925. }
  9926. // Updating submeshes
  9927. this.releaseSubMeshes();
  9928. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  9929. var previousOne = previousSubmeshes[submeshIndex];
  9930. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  9931. }
  9932. this.synchronizeInstances();
  9933. };
  9934. // Instances
  9935. Mesh.prototype.createInstance = function (name) {
  9936. return new BABYLON.InstancedMesh(name, this);
  9937. };
  9938. Mesh.prototype.synchronizeInstances = function () {
  9939. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  9940. var instance = this.instances[instanceIndex];
  9941. instance._syncSubMeshes();
  9942. }
  9943. };
  9944. // Statics
  9945. Mesh.CreateBox = function (name, size, scene, updatable) {
  9946. var box = new BABYLON.Mesh(name, scene);
  9947. var vertexData = BABYLON.VertexData.CreateBox(size);
  9948. vertexData.applyToMesh(box, updatable);
  9949. return box;
  9950. };
  9951. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable) {
  9952. var sphere = new BABYLON.Mesh(name, scene);
  9953. var vertexData = BABYLON.VertexData.CreateSphere(segments, diameter);
  9954. vertexData.applyToMesh(sphere, updatable);
  9955. return sphere;
  9956. };
  9957. // Cylinder and cone (Code inspired by SharpDX.org)
  9958. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable) {
  9959. // subdivisions is a new parameter, we need to support old signature
  9960. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  9961. if (scene !== undefined) {
  9962. updatable = scene;
  9963. }
  9964. scene = subdivisions;
  9965. subdivisions = 1;
  9966. }
  9967. var cylinder = new BABYLON.Mesh(name, scene);
  9968. var vertexData = BABYLON.VertexData.CreateCylinder(height, diameterTop, diameterBottom, tessellation, subdivisions);
  9969. vertexData.applyToMesh(cylinder, updatable);
  9970. return cylinder;
  9971. };
  9972. // Torus (Code from SharpDX.org)
  9973. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable) {
  9974. var torus = new BABYLON.Mesh(name, scene);
  9975. var vertexData = BABYLON.VertexData.CreateTorus(diameter, thickness, tessellation);
  9976. vertexData.applyToMesh(torus, updatable);
  9977. return torus;
  9978. };
  9979. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable) {
  9980. var torusKnot = new BABYLON.Mesh(name, scene);
  9981. var vertexData = BABYLON.VertexData.CreateTorusKnot(radius, tube, radialSegments, tubularSegments, p, q);
  9982. vertexData.applyToMesh(torusKnot, updatable);
  9983. return torusKnot;
  9984. };
  9985. // Lines
  9986. Mesh.CreateLines = function (name, points, scene, updatable) {
  9987. var lines = new BABYLON.LinesMesh(name, scene, updatable);
  9988. var vertexData = BABYLON.VertexData.CreateLines(points);
  9989. vertexData.applyToMesh(lines, updatable);
  9990. return lines;
  9991. };
  9992. // Plane & ground
  9993. Mesh.CreatePlane = function (name, size, scene, updatable) {
  9994. var plane = new BABYLON.Mesh(name, scene);
  9995. var vertexData = BABYLON.VertexData.CreatePlane(size);
  9996. vertexData.applyToMesh(plane, updatable);
  9997. return plane;
  9998. };
  9999. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  10000. var ground = new BABYLON.GroundMesh(name, scene);
  10001. ground._setReady(false);
  10002. ground._subdivisions = subdivisions;
  10003. var vertexData = BABYLON.VertexData.CreateGround(width, height, subdivisions);
  10004. vertexData.applyToMesh(ground, updatable);
  10005. ground._setReady(true);
  10006. return ground;
  10007. };
  10008. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  10009. var tiledGround = new BABYLON.Mesh(name, scene);
  10010. var vertexData = BABYLON.VertexData.CreateTiledGround(xmin, zmin, xmax, zmax, subdivisions, precision);
  10011. vertexData.applyToMesh(tiledGround, updatable);
  10012. return tiledGround;
  10013. };
  10014. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable) {
  10015. var ground = new BABYLON.GroundMesh(name, scene);
  10016. ground._subdivisions = subdivisions;
  10017. ground._setReady(false);
  10018. var onload = function (img) {
  10019. // Getting height map data
  10020. var canvas = document.createElement("canvas");
  10021. var context = canvas.getContext("2d");
  10022. var heightMapWidth = img.width;
  10023. var heightMapHeight = img.height;
  10024. canvas.width = heightMapWidth;
  10025. canvas.height = heightMapHeight;
  10026. context.drawImage(img, 0, 0);
  10027. // Create VertexData from map data
  10028. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  10029. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap(width, height, subdivisions, minHeight, maxHeight, buffer, heightMapWidth, heightMapHeight);
  10030. vertexData.applyToMesh(ground, updatable);
  10031. ground._setReady(true);
  10032. };
  10033. BABYLON.Tools.LoadImage(url, onload, function () {
  10034. }, scene.database);
  10035. return ground;
  10036. };
  10037. // Tools
  10038. Mesh.MinMax = function (meshes) {
  10039. var minVector = null;
  10040. var maxVector = null;
  10041. for (var i in meshes) {
  10042. var mesh = meshes[i];
  10043. var boundingBox = mesh.getBoundingInfo().boundingBox;
  10044. if (!minVector) {
  10045. minVector = boundingBox.minimumWorld;
  10046. maxVector = boundingBox.maximumWorld;
  10047. continue;
  10048. }
  10049. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  10050. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  10051. }
  10052. return {
  10053. min: minVector,
  10054. max: maxVector
  10055. };
  10056. };
  10057. Mesh.Center = function (meshesOrMinMaxVector) {
  10058. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  10059. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  10060. };
  10061. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices) {
  10062. if (typeof disposeSource === "undefined") { disposeSource = true; }
  10063. var source = meshes[0];
  10064. var material = source.material;
  10065. var scene = source.getScene();
  10066. if (!allow32BitsIndices) {
  10067. var totalVertices = 0;
  10068. for (var index = 0; index < meshes.length; index++) {
  10069. totalVertices += meshes[index].getTotalVertices();
  10070. if (totalVertices > 65536) {
  10071. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  10072. return null;
  10073. }
  10074. }
  10075. }
  10076. // Merge
  10077. var vertexData = BABYLON.VertexData.ExtractFromMesh(source);
  10078. vertexData.transform(source.getWorldMatrix());
  10079. for (index = 1; index < meshes.length; index++) {
  10080. var otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index]);
  10081. otherVertexData.transform(meshes[index].getWorldMatrix());
  10082. vertexData.merge(otherVertexData);
  10083. }
  10084. var newMesh = new Mesh(source.name + "_merged", scene);
  10085. vertexData.applyToMesh(newMesh);
  10086. // Setting properties
  10087. newMesh.material = material;
  10088. newMesh.checkCollisions = source.checkCollisions;
  10089. // Cleaning
  10090. if (disposeSource) {
  10091. for (index = 0; index < meshes.length; index++) {
  10092. meshes[index].dispose();
  10093. }
  10094. }
  10095. return newMesh;
  10096. };
  10097. return Mesh;
  10098. })(BABYLON.AbstractMesh);
  10099. BABYLON.Mesh = Mesh;
  10100. })(BABYLON || (BABYLON = {}));
  10101. //# sourceMappingURL=babylon.mesh.js.map
  10102. var BABYLON;
  10103. (function (BABYLON) {
  10104. var GroundMesh = (function (_super) {
  10105. __extends(GroundMesh, _super);
  10106. function GroundMesh(name, scene) {
  10107. _super.call(this, name, scene);
  10108. this.generateOctree = false;
  10109. this._worldInverse = new BABYLON.Matrix();
  10110. }
  10111. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  10112. get: function () {
  10113. return this._subdivisions;
  10114. },
  10115. enumerable: true,
  10116. configurable: true
  10117. });
  10118. GroundMesh.prototype.optimize = function (chunksCount) {
  10119. this.subdivide(this._subdivisions);
  10120. this.createOrUpdateSubmeshesOctree(32);
  10121. };
  10122. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  10123. var ray = new BABYLON.Ray(new BABYLON.Vector3(x, this.getBoundingInfo().boundingBox.maximumWorld.y + 1, z), new BABYLON.Vector3(0, -1, 0));
  10124. this.getWorldMatrix().invertToRef(this._worldInverse);
  10125. ray = BABYLON.Ray.Transform(ray, this._worldInverse);
  10126. var pickInfo = this.intersects(ray);
  10127. if (pickInfo.hit) {
  10128. return pickInfo.pickedPoint.y;
  10129. }
  10130. return 0;
  10131. };
  10132. return GroundMesh;
  10133. })(BABYLON.Mesh);
  10134. BABYLON.GroundMesh = GroundMesh;
  10135. })(BABYLON || (BABYLON = {}));
  10136. //# sourceMappingURL=babylon.groundMesh.js.map
  10137. var BABYLON;
  10138. (function (BABYLON) {
  10139. var InstancedMesh = (function (_super) {
  10140. __extends(InstancedMesh, _super);
  10141. function InstancedMesh(name, source) {
  10142. _super.call(this, name, source.getScene());
  10143. source.instances.push(this);
  10144. this._sourceMesh = source;
  10145. this.position.copyFrom(source.position);
  10146. this.rotation.copyFrom(source.rotation);
  10147. this.scaling.copyFrom(source.scaling);
  10148. if (source.rotationQuaternion) {
  10149. this.rotationQuaternion = source.rotationQuaternion.clone();
  10150. }
  10151. this.infiniteDistance = source.infiniteDistance;
  10152. this.setPivotMatrix(source.getPivotMatrix());
  10153. this.refreshBoundingInfo();
  10154. this._syncSubMeshes();
  10155. }
  10156. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  10157. // Methods
  10158. get: function () {
  10159. return this._sourceMesh.receiveShadows;
  10160. },
  10161. enumerable: true,
  10162. configurable: true
  10163. });
  10164. Object.defineProperty(InstancedMesh.prototype, "material", {
  10165. get: function () {
  10166. return this._sourceMesh.material;
  10167. },
  10168. enumerable: true,
  10169. configurable: true
  10170. });
  10171. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  10172. get: function () {
  10173. return this._sourceMesh.visibility;
  10174. },
  10175. enumerable: true,
  10176. configurable: true
  10177. });
  10178. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  10179. get: function () {
  10180. return this._sourceMesh.skeleton;
  10181. },
  10182. enumerable: true,
  10183. configurable: true
  10184. });
  10185. InstancedMesh.prototype.getTotalVertices = function () {
  10186. return this._sourceMesh.getTotalVertices();
  10187. };
  10188. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  10189. get: function () {
  10190. return this._sourceMesh;
  10191. },
  10192. enumerable: true,
  10193. configurable: true
  10194. });
  10195. InstancedMesh.prototype.getVerticesData = function (kind) {
  10196. return this._sourceMesh.getVerticesData(kind);
  10197. };
  10198. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  10199. return this._sourceMesh.isVerticesDataPresent(kind);
  10200. };
  10201. InstancedMesh.prototype.getIndices = function () {
  10202. return this._sourceMesh.getIndices();
  10203. };
  10204. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  10205. get: function () {
  10206. return this._sourceMesh._positions;
  10207. },
  10208. enumerable: true,
  10209. configurable: true
  10210. });
  10211. InstancedMesh.prototype.refreshBoundingInfo = function () {
  10212. var data = this._sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  10213. if (data) {
  10214. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._sourceMesh.getTotalVertices());
  10215. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  10216. }
  10217. this._updateBoundingInfo();
  10218. };
  10219. InstancedMesh.prototype._preActivate = function () {
  10220. if (this._currentLOD) {
  10221. this._currentLOD._preActivate();
  10222. }
  10223. };
  10224. InstancedMesh.prototype._activate = function (renderId) {
  10225. if (this._currentLOD) {
  10226. this._currentLOD._registerInstanceForRenderId(this, renderId);
  10227. }
  10228. };
  10229. InstancedMesh.prototype.getLOD = function (camera) {
  10230. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  10231. if (this._currentLOD === this.sourceMesh) {
  10232. return this;
  10233. }
  10234. return this._currentLOD;
  10235. };
  10236. InstancedMesh.prototype._syncSubMeshes = function () {
  10237. this.releaseSubMeshes();
  10238. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  10239. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  10240. }
  10241. };
  10242. InstancedMesh.prototype._generatePointsArray = function () {
  10243. return this._sourceMesh._generatePointsArray();
  10244. };
  10245. // Clone
  10246. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  10247. var result = this._sourceMesh.createInstance(name);
  10248. // Deep copy
  10249. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  10250. // Bounding info
  10251. this.refreshBoundingInfo();
  10252. // Parent
  10253. if (newParent) {
  10254. result.parent = newParent;
  10255. }
  10256. if (!doNotCloneChildren) {
  10257. for (var index = 0; index < this.getScene().meshes.length; index++) {
  10258. var mesh = this.getScene().meshes[index];
  10259. if (mesh.parent == this) {
  10260. mesh.clone(mesh.name, result);
  10261. }
  10262. }
  10263. }
  10264. result.computeWorldMatrix(true);
  10265. return result;
  10266. };
  10267. // Dispoe
  10268. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  10269. // Remove from mesh
  10270. var index = this._sourceMesh.instances.indexOf(this);
  10271. this._sourceMesh.instances.splice(index, 1);
  10272. _super.prototype.dispose.call(this, doNotRecurse);
  10273. };
  10274. return InstancedMesh;
  10275. })(BABYLON.AbstractMesh);
  10276. BABYLON.InstancedMesh = InstancedMesh;
  10277. })(BABYLON || (BABYLON = {}));
  10278. //# sourceMappingURL=babylon.instancedMesh.js.map
  10279. var BABYLON;
  10280. (function (BABYLON) {
  10281. var SubMesh = (function () {
  10282. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  10283. if (typeof createBoundingBox === "undefined") { createBoundingBox = true; }
  10284. this.materialIndex = materialIndex;
  10285. this.verticesStart = verticesStart;
  10286. this.verticesCount = verticesCount;
  10287. this.indexStart = indexStart;
  10288. this.indexCount = indexCount;
  10289. this._renderId = 0;
  10290. this._mesh = mesh;
  10291. this._renderingMesh = renderingMesh || mesh;
  10292. mesh.subMeshes.push(this);
  10293. this._id = mesh.subMeshes.length - 1;
  10294. if (createBoundingBox) {
  10295. this.refreshBoundingInfo();
  10296. }
  10297. }
  10298. SubMesh.prototype.getBoundingInfo = function () {
  10299. return this._boundingInfo;
  10300. };
  10301. SubMesh.prototype.getMesh = function () {
  10302. return this._mesh;
  10303. };
  10304. SubMesh.prototype.getRenderingMesh = function () {
  10305. return this._renderingMesh;
  10306. };
  10307. SubMesh.prototype.getMaterial = function () {
  10308. var rootMaterial = this._renderingMesh.material;
  10309. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  10310. var multiMaterial = rootMaterial;
  10311. return multiMaterial.getSubMaterial(this.materialIndex);
  10312. }
  10313. if (!rootMaterial) {
  10314. return this._mesh.getScene().defaultMaterial;
  10315. }
  10316. return rootMaterial;
  10317. };
  10318. // Methods
  10319. SubMesh.prototype.refreshBoundingInfo = function () {
  10320. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  10321. if (!data) {
  10322. this._boundingInfo = this._mesh._boundingInfo;
  10323. return;
  10324. }
  10325. var indices = this._renderingMesh.getIndices();
  10326. var extend;
  10327. if (this.indexStart === 0 && this.indexCount === indices.length) {
  10328. extend = BABYLON.Tools.ExtractMinAndMax(data, this.verticesStart, this.verticesCount);
  10329. } else {
  10330. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
  10331. }
  10332. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  10333. };
  10334. SubMesh.prototype._checkCollision = function (collider) {
  10335. return this._boundingInfo._checkCollision(collider);
  10336. };
  10337. SubMesh.prototype.updateBoundingInfo = function (world) {
  10338. if (!this._boundingInfo) {
  10339. this.refreshBoundingInfo();
  10340. }
  10341. this._boundingInfo._update(world);
  10342. };
  10343. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  10344. return this._boundingInfo.isInFrustum(frustumPlanes);
  10345. };
  10346. SubMesh.prototype.render = function () {
  10347. this._renderingMesh.render(this);
  10348. };
  10349. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  10350. if (!this._linesIndexBuffer) {
  10351. var linesIndices = [];
  10352. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  10353. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  10354. }
  10355. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  10356. this.linesIndexCount = linesIndices.length;
  10357. }
  10358. return this._linesIndexBuffer;
  10359. };
  10360. SubMesh.prototype.canIntersects = function (ray) {
  10361. return ray.intersectsBox(this._boundingInfo.boundingBox);
  10362. };
  10363. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  10364. var intersectInfo = null;
  10365. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  10366. var p0 = positions[indices[index]];
  10367. var p1 = positions[indices[index + 1]];
  10368. var p2 = positions[indices[index + 2]];
  10369. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  10370. if (currentIntersectInfo) {
  10371. if (currentIntersectInfo.distance < 0) {
  10372. continue;
  10373. }
  10374. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  10375. intersectInfo = currentIntersectInfo;
  10376. intersectInfo.faceId = index / 3;
  10377. if (fastCheck) {
  10378. break;
  10379. }
  10380. }
  10381. }
  10382. }
  10383. return intersectInfo;
  10384. };
  10385. // Clone
  10386. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  10387. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  10388. result._boundingInfo = new BABYLON.BoundingInfo(this._boundingInfo.minimum, this._boundingInfo.maximum);
  10389. return result;
  10390. };
  10391. // Dispose
  10392. SubMesh.prototype.dispose = function () {
  10393. if (this._linesIndexBuffer) {
  10394. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  10395. this._linesIndexBuffer = null;
  10396. }
  10397. // Remove from mesh
  10398. var index = this._mesh.subMeshes.indexOf(this);
  10399. this._mesh.subMeshes.splice(index, 1);
  10400. };
  10401. // Statics
  10402. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  10403. var minVertexIndex = Number.MAX_VALUE;
  10404. var maxVertexIndex = -Number.MAX_VALUE;
  10405. renderingMesh = renderingMesh || mesh;
  10406. var indices = renderingMesh.getIndices();
  10407. for (var index = startIndex; index < startIndex + indexCount; index++) {
  10408. var vertexIndex = indices[index];
  10409. if (vertexIndex < minVertexIndex)
  10410. minVertexIndex = vertexIndex;
  10411. if (vertexIndex > maxVertexIndex)
  10412. maxVertexIndex = vertexIndex;
  10413. }
  10414. return new BABYLON.SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  10415. };
  10416. return SubMesh;
  10417. })();
  10418. BABYLON.SubMesh = SubMesh;
  10419. })(BABYLON || (BABYLON = {}));
  10420. //# sourceMappingURL=babylon.subMesh.js.map
  10421. var BABYLON;
  10422. (function (BABYLON) {
  10423. var BaseTexture = (function () {
  10424. function BaseTexture(scene) {
  10425. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  10426. this.hasAlpha = false;
  10427. this.getAlphaFromRGB = false;
  10428. this.level = 1;
  10429. this.isCube = false;
  10430. this.isRenderTarget = false;
  10431. this.animations = new Array();
  10432. this.coordinatesIndex = 0;
  10433. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  10434. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  10435. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  10436. this.anisotropicFilteringLevel = 4;
  10437. this._scene = scene;
  10438. this._scene.textures.push(this);
  10439. }
  10440. BaseTexture.prototype.getScene = function () {
  10441. return this._scene;
  10442. };
  10443. BaseTexture.prototype.getTextureMatrix = function () {
  10444. return null;
  10445. };
  10446. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  10447. return null;
  10448. };
  10449. BaseTexture.prototype.getInternalTexture = function () {
  10450. return this._texture;
  10451. };
  10452. BaseTexture.prototype.isReady = function () {
  10453. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  10454. return true;
  10455. }
  10456. if (this._texture) {
  10457. return this._texture.isReady;
  10458. }
  10459. return false;
  10460. };
  10461. BaseTexture.prototype.getSize = function () {
  10462. if (this._texture._width) {
  10463. return { width: this._texture._width, height: this._texture._height };
  10464. }
  10465. if (this._texture._size) {
  10466. return { width: this._texture._size, height: this._texture._size };
  10467. }
  10468. return { width: 0, height: 0 };
  10469. };
  10470. BaseTexture.prototype.getBaseSize = function () {
  10471. if (!this.isReady())
  10472. return { width: 0, height: 0 };
  10473. if (this._texture._size) {
  10474. return { width: this._texture._size, height: this._texture._size };
  10475. }
  10476. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  10477. };
  10478. BaseTexture.prototype.scale = function (ratio) {
  10479. };
  10480. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  10481. get: function () {
  10482. return false;
  10483. },
  10484. enumerable: true,
  10485. configurable: true
  10486. });
  10487. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  10488. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  10489. for (var index = 0; index < texturesCache.length; index++) {
  10490. var texturesCacheEntry = texturesCache[index];
  10491. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  10492. texturesCache.splice(index, 1);
  10493. return;
  10494. }
  10495. }
  10496. };
  10497. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  10498. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  10499. for (var index = 0; index < texturesCache.length; index++) {
  10500. var texturesCacheEntry = texturesCache[index];
  10501. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  10502. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  10503. texturesCacheEntry.references++;
  10504. return texturesCacheEntry;
  10505. }
  10506. }
  10507. }
  10508. return null;
  10509. };
  10510. BaseTexture.prototype.delayLoad = function () {
  10511. };
  10512. BaseTexture.prototype.releaseInternalTexture = function () {
  10513. if (!this._texture) {
  10514. return;
  10515. }
  10516. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  10517. this._texture.references--;
  10518. // Final reference ?
  10519. if (this._texture.references === 0) {
  10520. var index = texturesCache.indexOf(this._texture);
  10521. texturesCache.splice(index, 1);
  10522. this._scene.getEngine()._releaseTexture(this._texture);
  10523. delete this._texture;
  10524. }
  10525. };
  10526. BaseTexture.prototype.clone = function () {
  10527. return null;
  10528. };
  10529. BaseTexture.prototype.dispose = function () {
  10530. // Remove from scene
  10531. var index = this._scene.textures.indexOf(this);
  10532. if (index >= 0) {
  10533. this._scene.textures.splice(index, 1);
  10534. }
  10535. if (this._texture === undefined) {
  10536. return;
  10537. }
  10538. this.releaseInternalTexture();
  10539. // Callback
  10540. if (this.onDispose) {
  10541. this.onDispose();
  10542. }
  10543. };
  10544. return BaseTexture;
  10545. })();
  10546. BABYLON.BaseTexture = BaseTexture;
  10547. })(BABYLON || (BABYLON = {}));
  10548. //# sourceMappingURL=babylon.baseTexture.js.map
  10549. var BABYLON;
  10550. (function (BABYLON) {
  10551. var RenderingGroup = (function () {
  10552. function RenderingGroup(index, scene) {
  10553. this.index = index;
  10554. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  10555. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  10556. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  10557. this._scene = scene;
  10558. }
  10559. RenderingGroup.prototype.render = function (customRenderFunction) {
  10560. if (customRenderFunction) {
  10561. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  10562. return true;
  10563. }
  10564. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  10565. return false;
  10566. }
  10567. var engine = this._scene.getEngine();
  10568. // Opaque
  10569. var subIndex;
  10570. var submesh;
  10571. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  10572. submesh = this._opaqueSubMeshes.data[subIndex];
  10573. submesh.render();
  10574. }
  10575. // Alpha test
  10576. engine.setAlphaTesting(true);
  10577. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  10578. submesh = this._alphaTestSubMeshes.data[subIndex];
  10579. submesh.render();
  10580. }
  10581. engine.setAlphaTesting(false);
  10582. // Transparent
  10583. if (this._transparentSubMeshes.length) {
  10584. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  10585. submesh = this._transparentSubMeshes.data[subIndex];
  10586. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  10587. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.position).length();
  10588. }
  10589. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  10590. sortedArray.sort(function (a, b) {
  10591. // Alpha index first
  10592. if (a._alphaIndex > b._alphaIndex) {
  10593. return 1;
  10594. }
  10595. if (a._alphaIndex < b._alphaIndex) {
  10596. return -1;
  10597. }
  10598. // Then distance to camera
  10599. if (a._distanceToCamera < b._distanceToCamera) {
  10600. return 1;
  10601. }
  10602. if (a._distanceToCamera > b._distanceToCamera) {
  10603. return -1;
  10604. }
  10605. return 0;
  10606. });
  10607. // Rendering
  10608. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  10609. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  10610. submesh = sortedArray[subIndex];
  10611. submesh.render();
  10612. }
  10613. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  10614. }
  10615. return true;
  10616. };
  10617. RenderingGroup.prototype.prepare = function () {
  10618. this._opaqueSubMeshes.reset();
  10619. this._transparentSubMeshes.reset();
  10620. this._alphaTestSubMeshes.reset();
  10621. };
  10622. RenderingGroup.prototype.dispatch = function (subMesh) {
  10623. var material = subMesh.getMaterial();
  10624. var mesh = subMesh.getMesh();
  10625. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  10626. this._transparentSubMeshes.push(subMesh);
  10627. } else if (material.needAlphaTesting()) {
  10628. this._alphaTestSubMeshes.push(subMesh);
  10629. } else {
  10630. this._opaqueSubMeshes.push(subMesh); // Opaque
  10631. }
  10632. };
  10633. return RenderingGroup;
  10634. })();
  10635. BABYLON.RenderingGroup = RenderingGroup;
  10636. })(BABYLON || (BABYLON = {}));
  10637. //# sourceMappingURL=babylon.renderingGroup.js.map
  10638. var BABYLON;
  10639. (function (BABYLON) {
  10640. var RenderingManager = (function () {
  10641. function RenderingManager(scene) {
  10642. this._renderingGroups = new Array();
  10643. this._scene = scene;
  10644. }
  10645. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  10646. if (this._scene._activeParticleSystems.length === 0) {
  10647. return;
  10648. }
  10649. // Particles
  10650. var beforeParticlesDate = BABYLON.Tools.Now;
  10651. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  10652. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  10653. if (particleSystem.renderingGroupId !== index) {
  10654. continue;
  10655. }
  10656. this._clearDepthBuffer();
  10657. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  10658. this._scene._activeParticles += particleSystem.render();
  10659. }
  10660. }
  10661. this._scene._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  10662. };
  10663. RenderingManager.prototype._renderSprites = function (index) {
  10664. if (this._scene.spriteManagers.length === 0) {
  10665. return;
  10666. }
  10667. // Sprites
  10668. var beforeSpritessDate = BABYLON.Tools.Now;
  10669. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  10670. var spriteManager = this._scene.spriteManagers[id];
  10671. if (spriteManager.renderingGroupId === index) {
  10672. this._clearDepthBuffer();
  10673. spriteManager.render();
  10674. }
  10675. }
  10676. this._scene._spritesDuration += BABYLON.Tools.Now - beforeSpritessDate;
  10677. };
  10678. RenderingManager.prototype._clearDepthBuffer = function () {
  10679. if (this._depthBufferAlreadyCleaned) {
  10680. return;
  10681. }
  10682. this._scene.getEngine().clear(0, false, true);
  10683. this._depthBufferAlreadyCleaned = true;
  10684. };
  10685. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  10686. for (var index = 0; index < BABYLON.RenderingManager.MAX_RENDERINGGROUPS; index++) {
  10687. this._depthBufferAlreadyCleaned = false;
  10688. var renderingGroup = this._renderingGroups[index];
  10689. if (renderingGroup) {
  10690. this._clearDepthBuffer();
  10691. if (!renderingGroup.render(customRenderFunction)) {
  10692. this._renderingGroups.splice(index, 1);
  10693. }
  10694. }
  10695. this._renderSprites(index);
  10696. if (renderParticles) {
  10697. this._renderParticles(index, activeMeshes);
  10698. }
  10699. }
  10700. };
  10701. RenderingManager.prototype.reset = function () {
  10702. for (var index in this._renderingGroups) {
  10703. var renderingGroup = this._renderingGroups[index];
  10704. renderingGroup.prepare();
  10705. }
  10706. };
  10707. RenderingManager.prototype.dispatch = function (subMesh) {
  10708. var mesh = subMesh.getMesh();
  10709. var renderingGroupId = mesh.renderingGroupId || 0;
  10710. if (!this._renderingGroups[renderingGroupId]) {
  10711. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  10712. }
  10713. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  10714. };
  10715. RenderingManager.MAX_RENDERINGGROUPS = 4;
  10716. return RenderingManager;
  10717. })();
  10718. BABYLON.RenderingManager = RenderingManager;
  10719. })(BABYLON || (BABYLON = {}));
  10720. //# sourceMappingURL=babylon.renderingManager.js.map
  10721. var BABYLON;
  10722. (function (BABYLON) {
  10723. var Texture = (function (_super) {
  10724. __extends(Texture, _super);
  10725. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  10726. if (typeof samplingMode === "undefined") { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  10727. if (typeof onLoad === "undefined") { onLoad = null; }
  10728. if (typeof onError === "undefined") { onError = null; }
  10729. if (typeof buffer === "undefined") { buffer = null; }
  10730. if (typeof deleteBuffer === "undefined") { deleteBuffer = false; }
  10731. _super.call(this, scene);
  10732. this.uOffset = 0;
  10733. this.vOffset = 0;
  10734. this.uScale = 1.0;
  10735. this.vScale = 1.0;
  10736. this.uAng = 0;
  10737. this.vAng = 0;
  10738. this.wAng = 0;
  10739. this.name = url;
  10740. this.url = url;
  10741. this._noMipmap = noMipmap;
  10742. this._invertY = invertY;
  10743. this._samplingMode = samplingMode;
  10744. this._buffer = buffer;
  10745. this._deleteBuffer = deleteBuffer;
  10746. if (!url) {
  10747. return;
  10748. }
  10749. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  10750. if (!this._texture) {
  10751. if (!scene.useDelayedTextureLoading) {
  10752. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  10753. if (deleteBuffer) {
  10754. delete this._buffer;
  10755. }
  10756. } else {
  10757. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  10758. }
  10759. }
  10760. }
  10761. Texture.prototype.delayLoad = function () {
  10762. if (this.delayLoadState != BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  10763. return;
  10764. }
  10765. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  10766. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  10767. if (!this._texture) {
  10768. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, null, null, this._buffer);
  10769. if (this._deleteBuffer) {
  10770. delete this._buffer;
  10771. }
  10772. }
  10773. };
  10774. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  10775. x -= this.uOffset + 0.5;
  10776. y -= this.vOffset + 0.5;
  10777. z -= 0.5;
  10778. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  10779. t.x *= this.uScale;
  10780. t.y *= this.vScale;
  10781. t.x += 0.5;
  10782. t.y += 0.5;
  10783. t.z += 0.5;
  10784. };
  10785. Texture.prototype.getTextureMatrix = function () {
  10786. 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) {
  10787. return this._cachedTextureMatrix;
  10788. }
  10789. this._cachedUOffset = this.uOffset;
  10790. this._cachedVOffset = this.vOffset;
  10791. this._cachedUScale = this.uScale;
  10792. this._cachedVScale = this.vScale;
  10793. this._cachedUAng = this.uAng;
  10794. this._cachedVAng = this.vAng;
  10795. this._cachedWAng = this.wAng;
  10796. if (!this._cachedTextureMatrix) {
  10797. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  10798. this._rowGenerationMatrix = new BABYLON.Matrix();
  10799. this._t0 = BABYLON.Vector3.Zero();
  10800. this._t1 = BABYLON.Vector3.Zero();
  10801. this._t2 = BABYLON.Vector3.Zero();
  10802. }
  10803. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  10804. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  10805. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  10806. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  10807. this._t1.subtractInPlace(this._t0);
  10808. this._t2.subtractInPlace(this._t0);
  10809. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  10810. this._cachedTextureMatrix.m[0] = this._t1.x;
  10811. this._cachedTextureMatrix.m[1] = this._t1.y;
  10812. this._cachedTextureMatrix.m[2] = this._t1.z;
  10813. this._cachedTextureMatrix.m[4] = this._t2.x;
  10814. this._cachedTextureMatrix.m[5] = this._t2.y;
  10815. this._cachedTextureMatrix.m[6] = this._t2.z;
  10816. this._cachedTextureMatrix.m[8] = this._t0.x;
  10817. this._cachedTextureMatrix.m[9] = this._t0.y;
  10818. this._cachedTextureMatrix.m[10] = this._t0.z;
  10819. return this._cachedTextureMatrix;
  10820. };
  10821. Texture.prototype.getReflectionTextureMatrix = function () {
  10822. if (this.uOffset === this._cachedUOffset && this.vOffset === this._cachedVOffset && this.uScale === this._cachedUScale && this.vScale === this._cachedVScale && this.coordinatesMode === this._cachedCoordinatesMode) {
  10823. return this._cachedTextureMatrix;
  10824. }
  10825. if (!this._cachedTextureMatrix) {
  10826. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  10827. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  10828. }
  10829. this._cachedCoordinatesMode = this.coordinatesMode;
  10830. switch (this.coordinatesMode) {
  10831. case BABYLON.Texture.SPHERICAL_MODE:
  10832. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  10833. this._cachedTextureMatrix[0] = -0.5 * this.uScale;
  10834. this._cachedTextureMatrix[5] = -0.5 * this.vScale;
  10835. this._cachedTextureMatrix[12] = 0.5 + this.uOffset;
  10836. this._cachedTextureMatrix[13] = 0.5 + this.vOffset;
  10837. break;
  10838. case BABYLON.Texture.PLANAR_MODE:
  10839. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  10840. this._cachedTextureMatrix[0] = this.uScale;
  10841. this._cachedTextureMatrix[5] = this.vScale;
  10842. this._cachedTextureMatrix[12] = this.uOffset;
  10843. this._cachedTextureMatrix[13] = this.vOffset;
  10844. break;
  10845. case BABYLON.Texture.PROJECTION_MODE:
  10846. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  10847. this._projectionModeMatrix.m[0] = 0.5;
  10848. this._projectionModeMatrix.m[5] = -0.5;
  10849. this._projectionModeMatrix.m[10] = 0.0;
  10850. this._projectionModeMatrix.m[12] = 0.5;
  10851. this._projectionModeMatrix.m[13] = 0.5;
  10852. this._projectionModeMatrix.m[14] = 1.0;
  10853. this._projectionModeMatrix.m[15] = 1.0;
  10854. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  10855. break;
  10856. default:
  10857. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  10858. break;
  10859. }
  10860. return this._cachedTextureMatrix;
  10861. };
  10862. Texture.prototype.clone = function () {
  10863. var newTexture = new BABYLON.Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY);
  10864. // Base texture
  10865. newTexture.hasAlpha = this.hasAlpha;
  10866. newTexture.level = this.level;
  10867. newTexture.wrapU = this.wrapU;
  10868. newTexture.wrapV = this.wrapV;
  10869. newTexture.coordinatesIndex = this.coordinatesIndex;
  10870. newTexture.coordinatesMode = this.coordinatesMode;
  10871. // Texture
  10872. newTexture.uOffset = this.uOffset;
  10873. newTexture.vOffset = this.vOffset;
  10874. newTexture.uScale = this.uScale;
  10875. newTexture.vScale = this.vScale;
  10876. newTexture.uAng = this.uAng;
  10877. newTexture.vAng = this.vAng;
  10878. newTexture.wAng = this.wAng;
  10879. return newTexture;
  10880. };
  10881. // Statics
  10882. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  10883. if (typeof samplingMode === "undefined") { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  10884. if (typeof onLoad === "undefined") { onLoad = null; }
  10885. if (typeof onError === "undefined") { onError = null; }
  10886. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  10887. };
  10888. Texture.NEAREST_SAMPLINGMODE = 1;
  10889. Texture.BILINEAR_SAMPLINGMODE = 2;
  10890. Texture.TRILINEAR_SAMPLINGMODE = 3;
  10891. Texture.EXPLICIT_MODE = 0;
  10892. Texture.SPHERICAL_MODE = 1;
  10893. Texture.PLANAR_MODE = 2;
  10894. Texture.CUBIC_MODE = 3;
  10895. Texture.PROJECTION_MODE = 4;
  10896. Texture.SKYBOX_MODE = 5;
  10897. Texture.CLAMP_ADDRESSMODE = 0;
  10898. Texture.WRAP_ADDRESSMODE = 1;
  10899. Texture.MIRROR_ADDRESSMODE = 2;
  10900. return Texture;
  10901. })(BABYLON.BaseTexture);
  10902. BABYLON.Texture = Texture;
  10903. })(BABYLON || (BABYLON = {}));
  10904. //# sourceMappingURL=babylon.texture.js.map
  10905. var BABYLON;
  10906. (function (BABYLON) {
  10907. var CubeTexture = (function (_super) {
  10908. __extends(CubeTexture, _super);
  10909. function CubeTexture(rootUrl, scene, extensions, noMipmap) {
  10910. _super.call(this, scene);
  10911. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  10912. this.name = rootUrl;
  10913. this.url = rootUrl;
  10914. this._noMipmap = noMipmap;
  10915. this.hasAlpha = false;
  10916. this._texture = this._getFromCache(rootUrl, noMipmap);
  10917. if (!extensions) {
  10918. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  10919. }
  10920. this._extensions = extensions;
  10921. if (!this._texture) {
  10922. if (!scene.useDelayedTextureLoading) {
  10923. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, extensions, noMipmap);
  10924. } else {
  10925. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  10926. }
  10927. }
  10928. this.isCube = true;
  10929. this._textureMatrix = BABYLON.Matrix.Identity();
  10930. }
  10931. CubeTexture.prototype.clone = function () {
  10932. var newTexture = new BABYLON.CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap);
  10933. // Base texture
  10934. newTexture.level = this.level;
  10935. newTexture.wrapU = this.wrapU;
  10936. newTexture.wrapV = this.wrapV;
  10937. newTexture.coordinatesIndex = this.coordinatesIndex;
  10938. newTexture.coordinatesMode = this.coordinatesMode;
  10939. return newTexture;
  10940. };
  10941. // Methods
  10942. CubeTexture.prototype.delayLoad = function () {
  10943. if (this.delayLoadState != BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  10944. return;
  10945. }
  10946. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  10947. this._texture = this._getFromCache(this.url, this._noMipmap);
  10948. if (!this._texture) {
  10949. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  10950. }
  10951. };
  10952. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  10953. return this._textureMatrix;
  10954. };
  10955. return CubeTexture;
  10956. })(BABYLON.BaseTexture);
  10957. BABYLON.CubeTexture = CubeTexture;
  10958. })(BABYLON || (BABYLON = {}));
  10959. //# sourceMappingURL=babylon.cubeTexture.js.map
  10960. var BABYLON;
  10961. (function (BABYLON) {
  10962. var RenderTargetTexture = (function (_super) {
  10963. __extends(RenderTargetTexture, _super);
  10964. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio) {
  10965. if (typeof doNotChangeAspectRatio === "undefined") { doNotChangeAspectRatio = true; }
  10966. _super.call(this, null, scene, !generateMipMaps);
  10967. this.renderList = new Array();
  10968. this.renderParticles = true;
  10969. this.renderSprites = false;
  10970. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  10971. this._currentRefreshId = -1;
  10972. this._refreshRate = 1;
  10973. this.name = name;
  10974. this.isRenderTarget = true;
  10975. this._size = size;
  10976. this._generateMipMaps = generateMipMaps;
  10977. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  10978. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  10979. // Rendering groups
  10980. this._renderingManager = new BABYLON.RenderingManager(scene);
  10981. }
  10982. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  10983. this._currentRefreshId = -1;
  10984. };
  10985. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  10986. get: function () {
  10987. return this._refreshRate;
  10988. },
  10989. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  10990. set: function (value) {
  10991. this._refreshRate = value;
  10992. this.resetRefreshCounter();
  10993. },
  10994. enumerable: true,
  10995. configurable: true
  10996. });
  10997. RenderTargetTexture.prototype._shouldRender = function () {
  10998. if (this._currentRefreshId === -1) {
  10999. this._currentRefreshId = 1;
  11000. return true;
  11001. }
  11002. if (this.refreshRate == this._currentRefreshId) {
  11003. this._currentRefreshId = 1;
  11004. return true;
  11005. }
  11006. this._currentRefreshId++;
  11007. return false;
  11008. };
  11009. RenderTargetTexture.prototype.isReady = function () {
  11010. if (!this.getScene().renderTargetsEnabled) {
  11011. return false;
  11012. }
  11013. return _super.prototype.isReady.call(this);
  11014. };
  11015. RenderTargetTexture.prototype.getRenderSize = function () {
  11016. return this._size;
  11017. };
  11018. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  11019. get: function () {
  11020. return true;
  11021. },
  11022. enumerable: true,
  11023. configurable: true
  11024. });
  11025. RenderTargetTexture.prototype.scale = function (ratio) {
  11026. var newSize = this._size * ratio;
  11027. this.resize(newSize, this._generateMipMaps);
  11028. };
  11029. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  11030. this.releaseInternalTexture();
  11031. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  11032. };
  11033. RenderTargetTexture.prototype.render = function (useCameraPostProcess) {
  11034. var scene = this.getScene();
  11035. var engine = scene.getEngine();
  11036. if (this._waitingRenderList) {
  11037. this.renderList = [];
  11038. for (var index = 0; index < this._waitingRenderList.length; index++) {
  11039. var id = this._waitingRenderList[index];
  11040. this.renderList.push(scene.getMeshByID(id));
  11041. }
  11042. delete this._waitingRenderList;
  11043. }
  11044. if (!this.renderList) {
  11045. return;
  11046. }
  11047. // Bind
  11048. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  11049. engine.bindFramebuffer(this._texture);
  11050. }
  11051. // Clear
  11052. engine.clear(scene.clearColor, true, true);
  11053. this._renderingManager.reset();
  11054. for (var meshIndex = 0; meshIndex < this.renderList.length; meshIndex++) {
  11055. var mesh = this.renderList[meshIndex];
  11056. if (mesh) {
  11057. if (!mesh.isReady() || (mesh.material && !mesh.material.isReady())) {
  11058. // Reset _currentRefreshId
  11059. this.resetRefreshCounter();
  11060. continue;
  11061. }
  11062. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) != 0)) {
  11063. mesh._activate(scene.getRenderId());
  11064. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  11065. var subMesh = mesh.subMeshes[subIndex];
  11066. scene._activeVertices += subMesh.indexCount;
  11067. this._renderingManager.dispatch(subMesh);
  11068. }
  11069. }
  11070. }
  11071. }
  11072. if (!this._doNotChangeAspectRatio) {
  11073. scene.updateTransformMatrix(true);
  11074. }
  11075. if (this.onBeforeRender) {
  11076. this.onBeforeRender();
  11077. }
  11078. // Render
  11079. this._renderingManager.render(this.customRenderFunction, this.renderList, this.renderParticles, this.renderSprites);
  11080. if (useCameraPostProcess) {
  11081. scene.postProcessManager._finalizeFrame(false, this._texture);
  11082. }
  11083. if (this.onAfterRender) {
  11084. this.onAfterRender();
  11085. }
  11086. // Unbind
  11087. engine.unBindFramebuffer(this._texture);
  11088. if (!this._doNotChangeAspectRatio) {
  11089. scene.updateTransformMatrix(true);
  11090. }
  11091. };
  11092. RenderTargetTexture.prototype.clone = function () {
  11093. var textureSize = this.getSize();
  11094. var newTexture = new BABYLON.RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  11095. // Base texture
  11096. newTexture.hasAlpha = this.hasAlpha;
  11097. newTexture.level = this.level;
  11098. // RenderTarget Texture
  11099. newTexture.coordinatesMode = this.coordinatesMode;
  11100. newTexture.renderList = this.renderList.slice(0);
  11101. return newTexture;
  11102. };
  11103. return RenderTargetTexture;
  11104. })(BABYLON.Texture);
  11105. BABYLON.RenderTargetTexture = RenderTargetTexture;
  11106. })(BABYLON || (BABYLON = {}));
  11107. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  11108. var BABYLON;
  11109. (function (BABYLON) {
  11110. var ProceduralTexture = (function (_super) {
  11111. __extends(ProceduralTexture, _super);
  11112. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps) {
  11113. if (typeof generateMipMaps === "undefined") { generateMipMaps = true; }
  11114. _super.call(this, null, scene, !generateMipMaps);
  11115. this._currentRefreshId = -1;
  11116. this._refreshRate = 1;
  11117. this._vertexDeclaration = [2];
  11118. this._vertexStrideSize = 2 * 4;
  11119. this._uniforms = new Array();
  11120. this._samplers = new Array();
  11121. this._textures = new Array();
  11122. this._floats = new Array();
  11123. this._floatsArrays = {};
  11124. this._colors3 = new Array();
  11125. this._colors4 = new Array();
  11126. this._vectors2 = new Array();
  11127. this._vectors3 = new Array();
  11128. this._matrices = new Array();
  11129. this._fallbackTextureUsed = false;
  11130. scene._proceduralTextures.push(this);
  11131. this.name = name;
  11132. this.isRenderTarget = true;
  11133. this._size = size;
  11134. this._generateMipMaps = generateMipMaps;
  11135. this.setFragment(fragment);
  11136. this._fallbackTexture = fallbackTexture;
  11137. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  11138. // VBO
  11139. var vertices = [];
  11140. vertices.push(1, 1);
  11141. vertices.push(-1, 1);
  11142. vertices.push(-1, -1);
  11143. vertices.push(1, -1);
  11144. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  11145. // Indices
  11146. var indices = [];
  11147. indices.push(0);
  11148. indices.push(1);
  11149. indices.push(2);
  11150. indices.push(0);
  11151. indices.push(2);
  11152. indices.push(3);
  11153. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  11154. }
  11155. ProceduralTexture.prototype.reset = function () {
  11156. if (this._effect === undefined) {
  11157. return;
  11158. }
  11159. var engine = this.getScene().getEngine();
  11160. engine._releaseEffect(this._effect);
  11161. };
  11162. ProceduralTexture.prototype.isReady = function () {
  11163. var _this = this;
  11164. var engine = this.getScene().getEngine();
  11165. var shaders;
  11166. if (!this._fragment) {
  11167. return false;
  11168. }
  11169. if (this._fallbackTextureUsed) {
  11170. return true;
  11171. }
  11172. if (this._fragment.fragmentElement !== undefined) {
  11173. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  11174. } else {
  11175. shaders = { vertex: "procedural", fragment: this._fragment };
  11176. }
  11177. this._effect = engine.createEffect(shaders, ["position"], this._uniforms, this._samplers, "", null, null, function () {
  11178. _this.releaseInternalTexture();
  11179. if (_this._fallbackTexture) {
  11180. _this._texture = _this._fallbackTexture._texture;
  11181. _this._texture.references++;
  11182. }
  11183. _this._fallbackTextureUsed = true;
  11184. });
  11185. return this._effect.isReady();
  11186. };
  11187. ProceduralTexture.prototype.resetRefreshCounter = function () {
  11188. this._currentRefreshId = -1;
  11189. };
  11190. ProceduralTexture.prototype.setFragment = function (fragment) {
  11191. this._fragment = fragment;
  11192. };
  11193. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  11194. get: function () {
  11195. return this._refreshRate;
  11196. },
  11197. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  11198. set: function (value) {
  11199. this._refreshRate = value;
  11200. this.resetRefreshCounter();
  11201. },
  11202. enumerable: true,
  11203. configurable: true
  11204. });
  11205. ProceduralTexture.prototype._shouldRender = function () {
  11206. if (!this.isReady() || !this._texture) {
  11207. return false;
  11208. }
  11209. if (this._fallbackTextureUsed) {
  11210. return false;
  11211. }
  11212. if (this._currentRefreshId === -1) {
  11213. this._currentRefreshId = 1;
  11214. return true;
  11215. }
  11216. if (this.refreshRate === this._currentRefreshId) {
  11217. this._currentRefreshId = 1;
  11218. return true;
  11219. }
  11220. this._currentRefreshId++;
  11221. return false;
  11222. };
  11223. ProceduralTexture.prototype.getRenderSize = function () {
  11224. return this._size;
  11225. };
  11226. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  11227. if (this._fallbackTextureUsed) {
  11228. return;
  11229. }
  11230. this.releaseInternalTexture();
  11231. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  11232. };
  11233. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  11234. if (this._uniforms.indexOf(uniformName) === -1) {
  11235. this._uniforms.push(uniformName);
  11236. }
  11237. };
  11238. ProceduralTexture.prototype.setTexture = function (name, texture) {
  11239. if (this._samplers.indexOf(name) === -1) {
  11240. this._samplers.push(name);
  11241. }
  11242. this._textures[name] = texture;
  11243. return this;
  11244. };
  11245. ProceduralTexture.prototype.setFloat = function (name, value) {
  11246. this._checkUniform(name);
  11247. this._floats[name] = value;
  11248. return this;
  11249. };
  11250. ProceduralTexture.prototype.setFloats = function (name, value) {
  11251. this._checkUniform(name);
  11252. this._floatsArrays[name] = value;
  11253. return this;
  11254. };
  11255. ProceduralTexture.prototype.setColor3 = function (name, value) {
  11256. this._checkUniform(name);
  11257. this._colors3[name] = value;
  11258. return this;
  11259. };
  11260. ProceduralTexture.prototype.setColor4 = function (name, value) {
  11261. this._checkUniform(name);
  11262. this._colors4[name] = value;
  11263. return this;
  11264. };
  11265. ProceduralTexture.prototype.setVector2 = function (name, value) {
  11266. this._checkUniform(name);
  11267. this._vectors2[name] = value;
  11268. return this;
  11269. };
  11270. ProceduralTexture.prototype.setVector3 = function (name, value) {
  11271. this._checkUniform(name);
  11272. this._vectors3[name] = value;
  11273. return this;
  11274. };
  11275. ProceduralTexture.prototype.setMatrix = function (name, value) {
  11276. this._checkUniform(name);
  11277. this._matrices[name] = value;
  11278. return this;
  11279. };
  11280. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  11281. var scene = this.getScene();
  11282. var engine = scene.getEngine();
  11283. engine.bindFramebuffer(this._texture);
  11284. // Clear
  11285. engine.clear(scene.clearColor, true, true);
  11286. // Render
  11287. engine.enableEffect(this._effect);
  11288. engine.setState(false);
  11289. for (var name in this._textures) {
  11290. this._effect.setTexture(name, this._textures[name]);
  11291. }
  11292. for (name in this._floats) {
  11293. this._effect.setFloat(name, this._floats[name]);
  11294. }
  11295. for (name in this._floatsArrays) {
  11296. this._effect.setArray(name, this._floatsArrays[name]);
  11297. }
  11298. for (name in this._colors3) {
  11299. this._effect.setColor3(name, this._colors3[name]);
  11300. }
  11301. for (name in this._colors4) {
  11302. var color = this._colors4[name];
  11303. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  11304. }
  11305. for (name in this._vectors2) {
  11306. this._effect.setVector2(name, this._vectors2[name]);
  11307. }
  11308. for (name in this._vectors3) {
  11309. this._effect.setVector3(name, this._vectors3[name]);
  11310. }
  11311. for (name in this._matrices) {
  11312. this._effect.setMatrix(name, this._matrices[name]);
  11313. }
  11314. // VBOs
  11315. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  11316. // Draw order
  11317. engine.draw(true, 0, 6);
  11318. // Unbind
  11319. engine.unBindFramebuffer(this._texture);
  11320. };
  11321. ProceduralTexture.prototype.clone = function () {
  11322. var textureSize = this.getSize();
  11323. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  11324. // Base texture
  11325. newTexture.hasAlpha = this.hasAlpha;
  11326. newTexture.level = this.level;
  11327. // RenderTarget Texture
  11328. newTexture.coordinatesMode = this.coordinatesMode;
  11329. return newTexture;
  11330. };
  11331. ProceduralTexture.prototype.dispose = function () {
  11332. var index = this.getScene()._proceduralTextures.indexOf(this);
  11333. if (index >= 0) {
  11334. this.getScene()._proceduralTextures.splice(index, 1);
  11335. }
  11336. _super.prototype.dispose.call(this);
  11337. };
  11338. return ProceduralTexture;
  11339. })(BABYLON.Texture);
  11340. BABYLON.ProceduralTexture = ProceduralTexture;
  11341. })(BABYLON || (BABYLON = {}));
  11342. //# sourceMappingURL=babylon.proceduralTexture.js.map
  11343. var BABYLON;
  11344. (function (BABYLON) {
  11345. var WoodProceduralTexture = (function (_super) {
  11346. __extends(WoodProceduralTexture, _super);
  11347. function WoodProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  11348. _super.call(this, name, size, "wood", scene, fallbackTexture, generateMipMaps);
  11349. this._ampScale = 100.0;
  11350. this._woodColor = new BABYLON.Color3(0.32, 0.17, 0.09);
  11351. this.updateShaderUniforms();
  11352. this.refreshRate = 0;
  11353. }
  11354. WoodProceduralTexture.prototype.updateShaderUniforms = function () {
  11355. this.setFloat("ampScale", this._ampScale);
  11356. this.setColor3("woodColor", this._woodColor);
  11357. };
  11358. Object.defineProperty(WoodProceduralTexture.prototype, "ampScale", {
  11359. get: function () {
  11360. return this._ampScale;
  11361. },
  11362. set: function (value) {
  11363. this._ampScale = value;
  11364. this.updateShaderUniforms();
  11365. },
  11366. enumerable: true,
  11367. configurable: true
  11368. });
  11369. Object.defineProperty(WoodProceduralTexture.prototype, "woodColor", {
  11370. get: function () {
  11371. return this._woodColor;
  11372. },
  11373. set: function (value) {
  11374. this._woodColor = value;
  11375. this.updateShaderUniforms();
  11376. },
  11377. enumerable: true,
  11378. configurable: true
  11379. });
  11380. return WoodProceduralTexture;
  11381. })(BABYLON.ProceduralTexture);
  11382. BABYLON.WoodProceduralTexture = WoodProceduralTexture;
  11383. var FireProceduralTexture = (function (_super) {
  11384. __extends(FireProceduralTexture, _super);
  11385. function FireProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  11386. _super.call(this, name, size, "fire", scene, fallbackTexture, generateMipMaps);
  11387. this._time = 0.0;
  11388. this._speed = new BABYLON.Vector2(0.5, 0.3);
  11389. this._shift = 1.6;
  11390. this._autoGenerateTime = true;
  11391. this._alphaThreshold = 0.5;
  11392. this._fireColors = FireProceduralTexture.RedFireColors;
  11393. this.updateShaderUniforms();
  11394. this.refreshRate = 1;
  11395. }
  11396. FireProceduralTexture.prototype.updateShaderUniforms = function () {
  11397. this.setFloat("time", this._time);
  11398. this.setVector2("speed", this._speed);
  11399. this.setFloat("shift", this._shift);
  11400. this.setColor3("c1", this._fireColors[0]);
  11401. this.setColor3("c2", this._fireColors[1]);
  11402. this.setColor3("c3", this._fireColors[2]);
  11403. this.setColor3("c4", this._fireColors[3]);
  11404. this.setColor3("c5", this._fireColors[4]);
  11405. this.setColor3("c6", this._fireColors[5]);
  11406. this.setFloat("alphaThreshold", this._alphaThreshold);
  11407. };
  11408. FireProceduralTexture.prototype.render = function (useCameraPostProcess) {
  11409. if (this._autoGenerateTime) {
  11410. this._time += this.getScene().getAnimationRatio() * 0.03;
  11411. this.updateShaderUniforms();
  11412. }
  11413. _super.prototype.render.call(this, useCameraPostProcess);
  11414. };
  11415. Object.defineProperty(FireProceduralTexture, "PurpleFireColors", {
  11416. get: function () {
  11417. return [
  11418. new BABYLON.Color3(0.5, 0.0, 1.0),
  11419. new BABYLON.Color3(0.9, 0.0, 1.0),
  11420. new BABYLON.Color3(0.2, 0.0, 1.0),
  11421. new BABYLON.Color3(1.0, 0.9, 1.0),
  11422. new BABYLON.Color3(0.1, 0.1, 1.0),
  11423. new BABYLON.Color3(0.9, 0.9, 1.0)
  11424. ];
  11425. },
  11426. enumerable: true,
  11427. configurable: true
  11428. });
  11429. Object.defineProperty(FireProceduralTexture, "GreenFireColors", {
  11430. get: function () {
  11431. return [
  11432. new BABYLON.Color3(0.5, 1.0, 0.0),
  11433. new BABYLON.Color3(0.5, 1.0, 0.0),
  11434. new BABYLON.Color3(0.3, 0.4, 0.0),
  11435. new BABYLON.Color3(0.5, 1.0, 0.0),
  11436. new BABYLON.Color3(0.2, 0.0, 0.0),
  11437. new BABYLON.Color3(0.5, 1.0, 0.0)
  11438. ];
  11439. },
  11440. enumerable: true,
  11441. configurable: true
  11442. });
  11443. Object.defineProperty(FireProceduralTexture, "RedFireColors", {
  11444. get: function () {
  11445. return [
  11446. new BABYLON.Color3(0.5, 0.0, 0.1),
  11447. new BABYLON.Color3(0.9, 0.0, 0.0),
  11448. new BABYLON.Color3(0.2, 0.0, 0.0),
  11449. new BABYLON.Color3(1.0, 0.9, 0.0),
  11450. new BABYLON.Color3(0.1, 0.1, 0.1),
  11451. new BABYLON.Color3(0.9, 0.9, 0.9)
  11452. ];
  11453. },
  11454. enumerable: true,
  11455. configurable: true
  11456. });
  11457. Object.defineProperty(FireProceduralTexture, "BlueFireColors", {
  11458. get: function () {
  11459. return [
  11460. new BABYLON.Color3(0.1, 0.0, 0.5),
  11461. new BABYLON.Color3(0.0, 0.0, 0.5),
  11462. new BABYLON.Color3(0.1, 0.0, 0.2),
  11463. new BABYLON.Color3(0.0, 0.0, 1.0),
  11464. new BABYLON.Color3(0.1, 0.2, 0.3),
  11465. new BABYLON.Color3(0.0, 0.2, 0.9)
  11466. ];
  11467. },
  11468. enumerable: true,
  11469. configurable: true
  11470. });
  11471. Object.defineProperty(FireProceduralTexture.prototype, "fireColors", {
  11472. get: function () {
  11473. return this._fireColors;
  11474. },
  11475. set: function (value) {
  11476. this._fireColors = value;
  11477. this.updateShaderUniforms();
  11478. },
  11479. enumerable: true,
  11480. configurable: true
  11481. });
  11482. Object.defineProperty(FireProceduralTexture.prototype, "time", {
  11483. get: function () {
  11484. return this._time;
  11485. },
  11486. set: function (value) {
  11487. this._time = value;
  11488. this.updateShaderUniforms();
  11489. },
  11490. enumerable: true,
  11491. configurable: true
  11492. });
  11493. Object.defineProperty(FireProceduralTexture.prototype, "speed", {
  11494. get: function () {
  11495. return this._speed;
  11496. },
  11497. set: function (value) {
  11498. this._speed = value;
  11499. this.updateShaderUniforms();
  11500. },
  11501. enumerable: true,
  11502. configurable: true
  11503. });
  11504. Object.defineProperty(FireProceduralTexture.prototype, "shift", {
  11505. get: function () {
  11506. return this._shift;
  11507. },
  11508. set: function (value) {
  11509. this._shift = value;
  11510. this.updateShaderUniforms();
  11511. },
  11512. enumerable: true,
  11513. configurable: true
  11514. });
  11515. Object.defineProperty(FireProceduralTexture.prototype, "alphaThreshold", {
  11516. get: function () {
  11517. return this._alphaThreshold;
  11518. },
  11519. set: function (value) {
  11520. this._alphaThreshold = value;
  11521. this.updateShaderUniforms();
  11522. },
  11523. enumerable: true,
  11524. configurable: true
  11525. });
  11526. return FireProceduralTexture;
  11527. })(BABYLON.ProceduralTexture);
  11528. BABYLON.FireProceduralTexture = FireProceduralTexture;
  11529. var CloudProceduralTexture = (function (_super) {
  11530. __extends(CloudProceduralTexture, _super);
  11531. function CloudProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  11532. _super.call(this, name, size, "cloud", scene, fallbackTexture, generateMipMaps);
  11533. this._skyColor = new BABYLON.Color3(0.15, 0.68, 1.0);
  11534. this._cloudColor = new BABYLON.Color3(1, 1, 1);
  11535. this.updateShaderUniforms();
  11536. this.refreshRate = 0;
  11537. }
  11538. CloudProceduralTexture.prototype.updateShaderUniforms = function () {
  11539. this.setColor3("skyColor", this._skyColor);
  11540. this.setColor3("cloudColor", this._cloudColor);
  11541. };
  11542. Object.defineProperty(CloudProceduralTexture.prototype, "skyColor", {
  11543. get: function () {
  11544. return this._skyColor;
  11545. },
  11546. set: function (value) {
  11547. this._skyColor = value;
  11548. this.updateShaderUniforms();
  11549. },
  11550. enumerable: true,
  11551. configurable: true
  11552. });
  11553. Object.defineProperty(CloudProceduralTexture.prototype, "cloudColor", {
  11554. get: function () {
  11555. return this._cloudColor;
  11556. },
  11557. set: function (value) {
  11558. this._cloudColor = value;
  11559. this.updateShaderUniforms();
  11560. },
  11561. enumerable: true,
  11562. configurable: true
  11563. });
  11564. return CloudProceduralTexture;
  11565. })(BABYLON.ProceduralTexture);
  11566. BABYLON.CloudProceduralTexture = CloudProceduralTexture;
  11567. var GrassProceduralTexture = (function (_super) {
  11568. __extends(GrassProceduralTexture, _super);
  11569. function GrassProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  11570. _super.call(this, name, size, "grass", scene, fallbackTexture, generateMipMaps);
  11571. this._herb1 = new BABYLON.Color3(0.29, 0.38, 0.02);
  11572. this._herb2 = new BABYLON.Color3(0.36, 0.49, 0.09);
  11573. this._herb3 = new BABYLON.Color3(0.51, 0.6, 0.28);
  11574. this._groundColor = new BABYLON.Color3(1, 1, 1);
  11575. this._grassColors = [
  11576. new BABYLON.Color3(0.29, 0.38, 0.02),
  11577. new BABYLON.Color3(0.36, 0.49, 0.09),
  11578. new BABYLON.Color3(0.51, 0.6, 0.28)
  11579. ];
  11580. this.updateShaderUniforms();
  11581. this.refreshRate = 0;
  11582. }
  11583. GrassProceduralTexture.prototype.updateShaderUniforms = function () {
  11584. this.setColor3("herb1Color", this._grassColors[0]);
  11585. this.setColor3("herb2Color", this._grassColors[1]);
  11586. this.setColor3("herb3Color", this._grassColors[2]);
  11587. this.setColor3("groundColor", this._groundColor);
  11588. };
  11589. Object.defineProperty(GrassProceduralTexture.prototype, "grassColors", {
  11590. get: function () {
  11591. return this._grassColors;
  11592. },
  11593. set: function (value) {
  11594. this._grassColors = value;
  11595. this.updateShaderUniforms();
  11596. },
  11597. enumerable: true,
  11598. configurable: true
  11599. });
  11600. Object.defineProperty(GrassProceduralTexture.prototype, "groundColor", {
  11601. get: function () {
  11602. return this._groundColor;
  11603. },
  11604. set: function (value) {
  11605. this.groundColor = value;
  11606. this.updateShaderUniforms();
  11607. },
  11608. enumerable: true,
  11609. configurable: true
  11610. });
  11611. return GrassProceduralTexture;
  11612. })(BABYLON.ProceduralTexture);
  11613. BABYLON.GrassProceduralTexture = GrassProceduralTexture;
  11614. var RoadProceduralTexture = (function (_super) {
  11615. __extends(RoadProceduralTexture, _super);
  11616. function RoadProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  11617. _super.call(this, name, size, "road", scene, fallbackTexture, generateMipMaps);
  11618. this._roadColor = new BABYLON.Color3(0.53, 0.53, 0.53);
  11619. this.updateShaderUniforms();
  11620. this.refreshRate = 0;
  11621. }
  11622. RoadProceduralTexture.prototype.updateShaderUniforms = function () {
  11623. this.setColor3("roadColor", this._roadColor);
  11624. };
  11625. Object.defineProperty(RoadProceduralTexture.prototype, "roadColor", {
  11626. get: function () {
  11627. return this._roadColor;
  11628. },
  11629. set: function (value) {
  11630. this._roadColor = value;
  11631. this.updateShaderUniforms();
  11632. },
  11633. enumerable: true,
  11634. configurable: true
  11635. });
  11636. return RoadProceduralTexture;
  11637. })(BABYLON.ProceduralTexture);
  11638. BABYLON.RoadProceduralTexture = RoadProceduralTexture;
  11639. var BrickProceduralTexture = (function (_super) {
  11640. __extends(BrickProceduralTexture, _super);
  11641. function BrickProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  11642. _super.call(this, name, size, "brick", scene, fallbackTexture, generateMipMaps);
  11643. this._numberOfBricksHeight = 15;
  11644. this._numberOfBricksWidth = 5;
  11645. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  11646. this._brickColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  11647. this.updateShaderUniforms();
  11648. this.refreshRate = 0;
  11649. }
  11650. BrickProceduralTexture.prototype.updateShaderUniforms = function () {
  11651. this.setFloat("numberOfBricksHeight", this._numberOfBricksHeight);
  11652. this.setFloat("numberOfBricksWidth", this._numberOfBricksWidth);
  11653. this.setColor3("brickColor", this._brickColor);
  11654. this.setColor3("jointColor", this._jointColor);
  11655. };
  11656. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksHeight", {
  11657. get: function () {
  11658. return this._numberOfBricksHeight;
  11659. },
  11660. enumerable: true,
  11661. configurable: true
  11662. });
  11663. Object.defineProperty(BrickProceduralTexture.prototype, "cloudColor", {
  11664. set: function (value) {
  11665. this._numberOfBricksHeight = value;
  11666. this.updateShaderUniforms();
  11667. },
  11668. enumerable: true,
  11669. configurable: true
  11670. });
  11671. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksWidth", {
  11672. get: function () {
  11673. return this._numberOfBricksWidth;
  11674. },
  11675. set: function (value) {
  11676. this._numberOfBricksHeight = value;
  11677. this.updateShaderUniforms();
  11678. },
  11679. enumerable: true,
  11680. configurable: true
  11681. });
  11682. Object.defineProperty(BrickProceduralTexture.prototype, "jointColor", {
  11683. get: function () {
  11684. return this._jointColor;
  11685. },
  11686. set: function (value) {
  11687. this._jointColor = value;
  11688. this.updateShaderUniforms();
  11689. },
  11690. enumerable: true,
  11691. configurable: true
  11692. });
  11693. Object.defineProperty(BrickProceduralTexture.prototype, "brickColor", {
  11694. get: function () {
  11695. return this._brickColor;
  11696. },
  11697. set: function (value) {
  11698. this._brickColor = value;
  11699. this.updateShaderUniforms();
  11700. },
  11701. enumerable: true,
  11702. configurable: true
  11703. });
  11704. return BrickProceduralTexture;
  11705. })(BABYLON.ProceduralTexture);
  11706. BABYLON.BrickProceduralTexture = BrickProceduralTexture;
  11707. var MarbleProceduralTexture = (function (_super) {
  11708. __extends(MarbleProceduralTexture, _super);
  11709. function MarbleProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  11710. _super.call(this, name, size, "marble", scene, fallbackTexture, generateMipMaps);
  11711. this._numberOfTilesHeight = 3;
  11712. this._numberOfTilesWidth = 3;
  11713. this._amplitude = 9.0;
  11714. this._marbleColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  11715. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  11716. this.updateShaderUniforms();
  11717. this.refreshRate = 0;
  11718. }
  11719. MarbleProceduralTexture.prototype.updateShaderUniforms = function () {
  11720. this.setFloat("numberOfTilesHeight", this._numberOfTilesHeight);
  11721. this.setFloat("numberOfTilesWidth", this._numberOfTilesWidth);
  11722. this.setFloat("amplitude", this._amplitude);
  11723. this.setColor3("marbleColor", this._marbleColor);
  11724. this.setColor3("jointColor", this._jointColor);
  11725. };
  11726. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesHeight", {
  11727. get: function () {
  11728. return this._numberOfTilesHeight;
  11729. },
  11730. set: function (value) {
  11731. this._numberOfTilesHeight = value;
  11732. this.updateShaderUniforms();
  11733. },
  11734. enumerable: true,
  11735. configurable: true
  11736. });
  11737. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesWidth", {
  11738. get: function () {
  11739. return this._numberOfTilesWidth;
  11740. },
  11741. set: function (value) {
  11742. this._numberOfTilesWidth = value;
  11743. this.updateShaderUniforms();
  11744. },
  11745. enumerable: true,
  11746. configurable: true
  11747. });
  11748. Object.defineProperty(MarbleProceduralTexture.prototype, "jointColor", {
  11749. get: function () {
  11750. return this._jointColor;
  11751. },
  11752. set: function (value) {
  11753. this._jointColor = value;
  11754. this.updateShaderUniforms();
  11755. },
  11756. enumerable: true,
  11757. configurable: true
  11758. });
  11759. Object.defineProperty(MarbleProceduralTexture.prototype, "marbleColor", {
  11760. get: function () {
  11761. return this._marbleColor;
  11762. },
  11763. set: function (value) {
  11764. this._marbleColor = value;
  11765. this.updateShaderUniforms();
  11766. },
  11767. enumerable: true,
  11768. configurable: true
  11769. });
  11770. return MarbleProceduralTexture;
  11771. })(BABYLON.ProceduralTexture);
  11772. BABYLON.MarbleProceduralTexture = MarbleProceduralTexture;
  11773. })(BABYLON || (BABYLON = {}));
  11774. //# sourceMappingURL=babylon.standardProceduralTexture.js.map
  11775. var BABYLON;
  11776. (function (BABYLON) {
  11777. var CustomProceduralTexture = (function (_super) {
  11778. __extends(CustomProceduralTexture, _super);
  11779. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  11780. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  11781. this._animate = true;
  11782. this._time = 0;
  11783. this._texturePath = texturePath;
  11784. //Try to load json
  11785. this.loadJson(texturePath);
  11786. this.refreshRate = 1;
  11787. }
  11788. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  11789. var _this = this;
  11790. var that = this;
  11791. function noConfigFile() {
  11792. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShaderStore or DOM element");
  11793. try {
  11794. that.setFragment(that._texturePath);
  11795. } catch (ex) {
  11796. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  11797. }
  11798. }
  11799. var configFileUrl = jsonUrl + "/config.json";
  11800. var xhr = new XMLHttpRequest();
  11801. xhr.open("GET", configFileUrl, true);
  11802. xhr.addEventListener("load", function () {
  11803. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  11804. try {
  11805. _this._config = JSON.parse(xhr.response);
  11806. _this.updateShaderUniforms();
  11807. _this.updateTextures();
  11808. _this.setFragment(_this._texturePath + "/custom");
  11809. _this._animate = _this._config.animate;
  11810. _this.refreshRate = _this._config.refreshrate;
  11811. } catch (ex) {
  11812. noConfigFile();
  11813. }
  11814. } else {
  11815. noConfigFile();
  11816. }
  11817. }, false);
  11818. xhr.addEventListener("error", function (event) {
  11819. noConfigFile();
  11820. }, false);
  11821. try {
  11822. xhr.send();
  11823. } catch (ex) {
  11824. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  11825. }
  11826. };
  11827. CustomProceduralTexture.prototype.isReady = function () {
  11828. if (!_super.prototype.isReady.call(this)) {
  11829. return false;
  11830. }
  11831. for (var name in this._textures) {
  11832. var texture = this._textures[name];
  11833. if (!texture.isReady()) {
  11834. return false;
  11835. }
  11836. }
  11837. return true;
  11838. };
  11839. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  11840. if (this._animate) {
  11841. this._time += this.getScene().getAnimationRatio() * 0.03;
  11842. this.updateShaderUniforms();
  11843. }
  11844. _super.prototype.render.call(this, useCameraPostProcess);
  11845. };
  11846. CustomProceduralTexture.prototype.updateTextures = function () {
  11847. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  11848. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  11849. }
  11850. };
  11851. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  11852. if (this._config) {
  11853. for (var j = 0; j < this._config.uniforms.length; j++) {
  11854. var uniform = this._config.uniforms[j];
  11855. switch (uniform.type) {
  11856. case "float":
  11857. this.setFloat(uniform.name, uniform.value);
  11858. break;
  11859. case "color3":
  11860. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  11861. break;
  11862. case "color4":
  11863. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  11864. break;
  11865. case "vector2":
  11866. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  11867. break;
  11868. case "vector3":
  11869. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  11870. break;
  11871. }
  11872. }
  11873. }
  11874. this.setFloat("time", this._time);
  11875. };
  11876. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  11877. get: function () {
  11878. return this._animate;
  11879. },
  11880. set: function (value) {
  11881. this._animate = value;
  11882. },
  11883. enumerable: true,
  11884. configurable: true
  11885. });
  11886. return CustomProceduralTexture;
  11887. })(BABYLON.ProceduralTexture);
  11888. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  11889. })(BABYLON || (BABYLON = {}));
  11890. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  11891. var BABYLON;
  11892. (function (BABYLON) {
  11893. var MirrorTexture = (function (_super) {
  11894. __extends(MirrorTexture, _super);
  11895. function MirrorTexture(name, size, scene, generateMipMaps) {
  11896. var _this = this;
  11897. _super.call(this, name, size, scene, generateMipMaps, true);
  11898. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  11899. this._transformMatrix = BABYLON.Matrix.Zero();
  11900. this._mirrorMatrix = BABYLON.Matrix.Zero();
  11901. this.onBeforeRender = function () {
  11902. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  11903. _this._savedViewMatrix = scene.getViewMatrix();
  11904. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  11905. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  11906. scene.clipPlane = _this.mirrorPlane;
  11907. scene.getEngine().cullBackFaces = false;
  11908. };
  11909. this.onAfterRender = function () {
  11910. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  11911. scene.getEngine().cullBackFaces = true;
  11912. delete scene.clipPlane;
  11913. };
  11914. }
  11915. MirrorTexture.prototype.clone = function () {
  11916. var textureSize = this.getSize();
  11917. var newTexture = new BABYLON.MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  11918. // Base texture
  11919. newTexture.hasAlpha = this.hasAlpha;
  11920. newTexture.level = this.level;
  11921. // Mirror Texture
  11922. newTexture.mirrorPlane = this.mirrorPlane.clone();
  11923. newTexture.renderList = this.renderList.slice(0);
  11924. return newTexture;
  11925. };
  11926. return MirrorTexture;
  11927. })(BABYLON.RenderTargetTexture);
  11928. BABYLON.MirrorTexture = MirrorTexture;
  11929. })(BABYLON || (BABYLON = {}));
  11930. //# sourceMappingURL=babylon.mirrorTexture.js.map
  11931. var BABYLON;
  11932. (function (BABYLON) {
  11933. var DynamicTexture = (function (_super) {
  11934. __extends(DynamicTexture, _super);
  11935. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  11936. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  11937. _super.call(this, null, scene, !generateMipMaps);
  11938. this.name = name;
  11939. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  11940. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  11941. this._generateMipMaps = generateMipMaps;
  11942. if (options.getContext) {
  11943. this._canvas = options;
  11944. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  11945. } else {
  11946. this._canvas = document.createElement("canvas");
  11947. if (options.width) {
  11948. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  11949. } else {
  11950. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  11951. }
  11952. }
  11953. var textureSize = this.getSize();
  11954. this._canvas.width = textureSize.width;
  11955. this._canvas.height = textureSize.height;
  11956. this._context = this._canvas.getContext("2d");
  11957. }
  11958. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  11959. get: function () {
  11960. return true;
  11961. },
  11962. enumerable: true,
  11963. configurable: true
  11964. });
  11965. DynamicTexture.prototype.scale = function (ratio) {
  11966. var textureSize = this.getSize();
  11967. textureSize.width *= ratio;
  11968. textureSize.height *= ratio;
  11969. this._canvas.width = textureSize.width;
  11970. this._canvas.height = textureSize.height;
  11971. this.releaseInternalTexture();
  11972. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  11973. };
  11974. DynamicTexture.prototype.getContext = function () {
  11975. return this._context;
  11976. };
  11977. DynamicTexture.prototype.clear = function () {
  11978. var size = this.getSize();
  11979. this._context.fillRect(0, 0, size.width, size.height);
  11980. };
  11981. DynamicTexture.prototype.update = function (invertY) {
  11982. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  11983. };
  11984. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  11985. if (typeof update === "undefined") { update = true; }
  11986. var size = this.getSize();
  11987. if (clearColor) {
  11988. this._context.fillStyle = clearColor;
  11989. this._context.fillRect(0, 0, size.width, size.height);
  11990. }
  11991. this._context.font = font;
  11992. if (x === null) {
  11993. var textSize = this._context.measureText(text);
  11994. x = (size.width - textSize.width) / 2;
  11995. }
  11996. this._context.fillStyle = color;
  11997. this._context.fillText(text, x, y);
  11998. if (update) {
  11999. this.update(invertY);
  12000. }
  12001. };
  12002. DynamicTexture.prototype.clone = function () {
  12003. var textureSize = this.getSize();
  12004. var newTexture = new DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  12005. // Base texture
  12006. newTexture.hasAlpha = this.hasAlpha;
  12007. newTexture.level = this.level;
  12008. // Dynamic Texture
  12009. newTexture.wrapU = this.wrapU;
  12010. newTexture.wrapV = this.wrapV;
  12011. return newTexture;
  12012. };
  12013. return DynamicTexture;
  12014. })(BABYLON.Texture);
  12015. BABYLON.DynamicTexture = DynamicTexture;
  12016. })(BABYLON || (BABYLON = {}));
  12017. //# sourceMappingURL=babylon.dynamicTexture.js.map
  12018. var BABYLON;
  12019. (function (BABYLON) {
  12020. var VideoTexture = (function (_super) {
  12021. __extends(VideoTexture, _super);
  12022. function VideoTexture(name, urls, size, scene, generateMipMaps, invertY, samplingMode) {
  12023. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  12024. var _this = this;
  12025. _super.call(this, null, scene, !generateMipMaps, invertY);
  12026. this._autoLaunch = true;
  12027. this.name = name;
  12028. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  12029. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  12030. var requiredWidth = size.width || size;
  12031. var requiredHeight = size.height || size;
  12032. this._texture = scene.getEngine().createDynamicTexture(requiredWidth, requiredHeight, generateMipMaps, samplingMode);
  12033. var textureSize = this.getSize();
  12034. this.video = document.createElement("video");
  12035. this.video.width = textureSize.width;
  12036. this.video.height = textureSize.height;
  12037. this.video.autoplay = false;
  12038. this.video.loop = true;
  12039. this.video.addEventListener("canplaythrough", function () {
  12040. if (_this._texture) {
  12041. _this._texture.isReady = true;
  12042. }
  12043. });
  12044. urls.forEach(function (url) {
  12045. var source = document.createElement("source");
  12046. source.src = url;
  12047. _this.video.appendChild(source);
  12048. });
  12049. this._lastUpdate = BABYLON.Tools.Now;
  12050. }
  12051. VideoTexture.prototype.update = function () {
  12052. if (this._autoLaunch) {
  12053. this._autoLaunch = false;
  12054. this.video.play();
  12055. }
  12056. var now = BABYLON.Tools.Now;
  12057. if (now - this._lastUpdate < 15) {
  12058. return false;
  12059. }
  12060. this._lastUpdate = now;
  12061. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  12062. return true;
  12063. };
  12064. return VideoTexture;
  12065. })(BABYLON.Texture);
  12066. BABYLON.VideoTexture = VideoTexture;
  12067. })(BABYLON || (BABYLON = {}));
  12068. //# sourceMappingURL=babylon.videoTexture.js.map
  12069. var BABYLON;
  12070. (function (BABYLON) {
  12071. var EffectFallbacks = (function () {
  12072. function EffectFallbacks() {
  12073. this._defines = {};
  12074. this._currentRank = 32;
  12075. this._maxRank = -1;
  12076. }
  12077. EffectFallbacks.prototype.addFallback = function (rank, define) {
  12078. if (!this._defines[rank]) {
  12079. if (rank < this._currentRank) {
  12080. this._currentRank = rank;
  12081. }
  12082. if (rank > this._maxRank) {
  12083. this._maxRank = rank;
  12084. }
  12085. this._defines[rank] = new Array();
  12086. }
  12087. this._defines[rank].push(define);
  12088. };
  12089. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  12090. get: function () {
  12091. return this._currentRank <= this._maxRank;
  12092. },
  12093. enumerable: true,
  12094. configurable: true
  12095. });
  12096. EffectFallbacks.prototype.reduce = function (currentDefines) {
  12097. var currentFallbacks = this._defines[this._currentRank];
  12098. for (var index = 0; index < currentFallbacks.length; index++) {
  12099. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  12100. }
  12101. this._currentRank++;
  12102. return currentDefines;
  12103. };
  12104. return EffectFallbacks;
  12105. })();
  12106. BABYLON.EffectFallbacks = EffectFallbacks;
  12107. var Effect = (function () {
  12108. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  12109. var _this = this;
  12110. this._isReady = false;
  12111. this._compilationError = "";
  12112. this._valueCache = [];
  12113. this._engine = engine;
  12114. this.name = baseName;
  12115. this.defines = defines;
  12116. this._uniformsNames = uniformsNames.concat(samplers);
  12117. this._samplers = samplers;
  12118. this._attributesNames = attributesNames;
  12119. this.onError = onError;
  12120. this.onCompiled = onCompiled;
  12121. var vertexSource;
  12122. var fragmentSource;
  12123. if (baseName.vertexElement) {
  12124. vertexSource = document.getElementById(baseName.vertexElement);
  12125. if (!vertexSource) {
  12126. vertexSource = baseName.vertexElement;
  12127. }
  12128. } else {
  12129. vertexSource = baseName.vertex || baseName;
  12130. }
  12131. if (baseName.fragmentElement) {
  12132. fragmentSource = document.getElementById(baseName.fragmentElement);
  12133. if (!fragmentSource) {
  12134. fragmentSource = baseName.fragmentElement;
  12135. }
  12136. } else {
  12137. fragmentSource = baseName.fragment || baseName;
  12138. }
  12139. this._loadVertexShader(vertexSource, function (vertexCode) {
  12140. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  12141. _this._prepareEffect(vertexCode, fragmentCode, attributesNames, defines, fallbacks);
  12142. });
  12143. });
  12144. }
  12145. // Properties
  12146. Effect.prototype.isReady = function () {
  12147. return this._isReady;
  12148. };
  12149. Effect.prototype.getProgram = function () {
  12150. return this._program;
  12151. };
  12152. Effect.prototype.getAttributesNames = function () {
  12153. return this._attributesNames;
  12154. };
  12155. Effect.prototype.getAttributeLocation = function (index) {
  12156. return this._attributes[index];
  12157. };
  12158. Effect.prototype.getAttributeLocationByName = function (name) {
  12159. var index = this._attributesNames.indexOf(name);
  12160. return this._attributes[index];
  12161. };
  12162. Effect.prototype.getAttributesCount = function () {
  12163. return this._attributes.length;
  12164. };
  12165. Effect.prototype.getUniformIndex = function (uniformName) {
  12166. return this._uniformsNames.indexOf(uniformName);
  12167. };
  12168. Effect.prototype.getUniform = function (uniformName) {
  12169. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  12170. };
  12171. Effect.prototype.getSamplers = function () {
  12172. return this._samplers;
  12173. };
  12174. Effect.prototype.getCompilationError = function () {
  12175. return this._compilationError;
  12176. };
  12177. // Methods
  12178. Effect.prototype._loadVertexShader = function (vertex, callback) {
  12179. // DOM element ?
  12180. if (vertex instanceof HTMLElement) {
  12181. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  12182. callback(vertexCode);
  12183. return;
  12184. }
  12185. // Is in local store ?
  12186. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  12187. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  12188. return;
  12189. }
  12190. var vertexShaderUrl;
  12191. if (vertex[0] === ".") {
  12192. vertexShaderUrl = vertex;
  12193. } else {
  12194. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  12195. }
  12196. // Vertex shader
  12197. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  12198. };
  12199. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  12200. // DOM element ?
  12201. if (fragment instanceof HTMLElement) {
  12202. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  12203. callback(fragmentCode);
  12204. return;
  12205. }
  12206. // Is in local store ?
  12207. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  12208. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  12209. return;
  12210. }
  12211. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  12212. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  12213. return;
  12214. }
  12215. var fragmentShaderUrl;
  12216. if (fragment[0] === ".") {
  12217. fragmentShaderUrl = fragment;
  12218. } else {
  12219. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  12220. }
  12221. // Fragment shader
  12222. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  12223. };
  12224. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  12225. try {
  12226. var engine = this._engine;
  12227. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  12228. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  12229. this._attributes = engine.getAttributes(this._program, attributesNames);
  12230. for (var index = 0; index < this._samplers.length; index++) {
  12231. var sampler = this.getUniform(this._samplers[index]);
  12232. if (sampler == null) {
  12233. this._samplers.splice(index, 1);
  12234. index--;
  12235. }
  12236. }
  12237. engine.bindSamplers(this);
  12238. this._isReady = true;
  12239. if (this.onCompiled) {
  12240. this.onCompiled(this);
  12241. }
  12242. } catch (e) {
  12243. // Is it a problem with precision?
  12244. if (e.message.indexOf("highp") !== -1) {
  12245. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  12246. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  12247. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  12248. return;
  12249. }
  12250. // Let's go through fallbacks then
  12251. if (fallbacks && fallbacks.isMoreFallbacks) {
  12252. defines = fallbacks.reduce(defines);
  12253. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  12254. } else {
  12255. BABYLON.Tools.Error("Unable to compile effect: " + this.name);
  12256. BABYLON.Tools.Error("Defines: " + defines);
  12257. BABYLON.Tools.Error("Error: " + e.message);
  12258. this._compilationError = e.message;
  12259. if (this.onError) {
  12260. this.onError(this, this._compilationError);
  12261. }
  12262. }
  12263. }
  12264. };
  12265. Effect.prototype._bindTexture = function (channel, texture) {
  12266. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  12267. };
  12268. Effect.prototype.setTexture = function (channel, texture) {
  12269. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  12270. };
  12271. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  12272. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  12273. };
  12274. //public _cacheMatrix(uniformName, matrix) {
  12275. // if (!this._valueCache[uniformName]) {
  12276. // this._valueCache[uniformName] = new BABYLON.Matrix();
  12277. // }
  12278. // for (var index = 0; index < 16; index++) {
  12279. // this._valueCache[uniformName].m[index] = matrix.m[index];
  12280. // }
  12281. //};
  12282. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  12283. if (!this._valueCache[uniformName]) {
  12284. this._valueCache[uniformName] = [x, y];
  12285. return;
  12286. }
  12287. this._valueCache[uniformName][0] = x;
  12288. this._valueCache[uniformName][1] = y;
  12289. };
  12290. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  12291. if (!this._valueCache[uniformName]) {
  12292. this._valueCache[uniformName] = [x, y, z];
  12293. return;
  12294. }
  12295. this._valueCache[uniformName][0] = x;
  12296. this._valueCache[uniformName][1] = y;
  12297. this._valueCache[uniformName][2] = z;
  12298. };
  12299. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  12300. if (!this._valueCache[uniformName]) {
  12301. this._valueCache[uniformName] = [x, y, z, w];
  12302. return;
  12303. }
  12304. this._valueCache[uniformName][0] = x;
  12305. this._valueCache[uniformName][1] = y;
  12306. this._valueCache[uniformName][2] = z;
  12307. this._valueCache[uniformName][3] = w;
  12308. };
  12309. Effect.prototype.setArray = function (uniformName, array) {
  12310. this._engine.setArray(this.getUniform(uniformName), array);
  12311. return this;
  12312. };
  12313. Effect.prototype.setMatrices = function (uniformName, matrices) {
  12314. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  12315. return this;
  12316. };
  12317. Effect.prototype.setMatrix = function (uniformName, matrix) {
  12318. //if (this._valueCache[uniformName] && this._valueCache[uniformName].equals(matrix))
  12319. // return;
  12320. //this._cacheMatrix(uniformName, matrix);
  12321. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  12322. return this;
  12323. };
  12324. Effect.prototype.setFloat = function (uniformName, value) {
  12325. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  12326. return this;
  12327. this._valueCache[uniformName] = value;
  12328. this._engine.setFloat(this.getUniform(uniformName), value);
  12329. return this;
  12330. };
  12331. Effect.prototype.setBool = function (uniformName, bool) {
  12332. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  12333. return this;
  12334. this._valueCache[uniformName] = bool;
  12335. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  12336. return this;
  12337. };
  12338. Effect.prototype.setVector2 = function (uniformName, vector2) {
  12339. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector2.x && this._valueCache[uniformName][1] === vector2.y)
  12340. return this;
  12341. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  12342. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  12343. return this;
  12344. };
  12345. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  12346. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y)
  12347. return this;
  12348. this._cacheFloat2(uniformName, x, y);
  12349. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  12350. return this;
  12351. };
  12352. Effect.prototype.setVector3 = function (uniformName, vector3) {
  12353. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector3.x && this._valueCache[uniformName][1] === vector3.y && this._valueCache[uniformName][2] === vector3.z)
  12354. return this;
  12355. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  12356. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  12357. return this;
  12358. };
  12359. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  12360. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z)
  12361. return this;
  12362. this._cacheFloat3(uniformName, x, y, z);
  12363. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  12364. return this;
  12365. };
  12366. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  12367. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z && this._valueCache[uniformName][3] === w)
  12368. return this;
  12369. this._cacheFloat4(uniformName, x, y, z, w);
  12370. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  12371. return this;
  12372. };
  12373. Effect.prototype.setColor3 = function (uniformName, color3) {
  12374. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b)
  12375. return this;
  12376. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  12377. this._engine.setColor3(this.getUniform(uniformName), color3);
  12378. return this;
  12379. };
  12380. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  12381. 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)
  12382. return this;
  12383. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  12384. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  12385. return this;
  12386. };
  12387. 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}",
  12388. 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}",
  12389. 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}",
  12390. 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}",
  12391. 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}",
  12392. colorPixelShader:"precision highp float;\n\nuniform vec4 color;\n\nvoid main(void) {\n gl_FragColor = color;\n}",
  12393. 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}",
  12394. 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}",
  12395. defaultPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n#define MAP_EXPLICIT 0.\n#define MAP_SPHERICAL 1.\n#define MAP_PLANAR 2.\n#define MAP_CUBIC 3.\n#define MAP_PROJECTION 4.\n#define MAP_SKYBOX 5.\n\n// Constants\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vDiffuseColor;\nuniform vec4 vSpecularColor;\nuniform vec3 vEmissiveColor;\n\n// Input\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n// Lights\n#ifdef LIGHT0\nuniform vec4 vLightData0;\nuniform vec4 vLightDiffuse0;\nuniform vec3 vLightSpecular0;\n#ifdef SHADOW0\nvarying vec4 vPositionFromLight0;\nuniform sampler2D shadowSampler0;\nuniform float darkness0;\n#endif\n#ifdef SPOTLIGHT0\nuniform vec4 vLightDirection0;\n#endif\n#ifdef HEMILIGHT0\nuniform vec3 vLightGround0;\n#endif\n#endif\n\n#ifdef LIGHT1\nuniform vec4 vLightData1;\nuniform vec4 vLightDiffuse1;\nuniform vec3 vLightSpecular1;\n#ifdef SHADOW1\nvarying vec4 vPositionFromLight1;\nuniform sampler2D shadowSampler1;\nuniform float darkness1;\n#endif\n#ifdef SPOTLIGHT1\nuniform vec4 vLightDirection1;\n#endif\n#ifdef HEMILIGHT1\nuniform vec3 vLightGround1;\n#endif\n#endif\n\n#ifdef LIGHT2\nuniform vec4 vLightData2;\nuniform vec4 vLightDiffuse2;\nuniform vec3 vLightSpecular2;\n#ifdef SHADOW2\nvarying vec4 vPositionFromLight2;\nuniform sampler2D shadowSampler2;\nuniform float darkness2;\n#endif\n#ifdef SPOTLIGHT2\nuniform vec4 vLightDirection2;\n#endif\n#ifdef HEMILIGHT2\nuniform vec3 vLightGround2;\n#endif\n#endif\n\n#ifdef LIGHT3\nuniform vec4 vLightData3;\nuniform vec4 vLightDiffuse3;\nuniform vec3 vLightSpecular3;\n#ifdef SHADOW3\nvarying vec4 vPositionFromLight3;\nuniform sampler2D shadowSampler3;\nuniform float darkness3;\n#endif\n#ifdef SPOTLIGHT3\nuniform vec4 vLightDirection3;\n#endif\n#ifdef HEMILIGHT3\nuniform vec3 vLightGround3;\n#endif\n#endif\n\n// Samplers\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\nuniform vec2 vDiffuseInfos;\n#endif\n\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec2 vAmbientInfos;\n#endif\n\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n\n#ifdef SPECULAR\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform sampler2D specularSampler;\n#endif\n\n// Fresnel\n#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection, vec3 worldNormal, float bias, float power)\n{\n float fresnelTerm = pow(bias + abs(dot(viewDirection, worldNormal)), power);\n return clamp(fresnelTerm, 0., 1.);\n}\n#endif\n\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n// Reflection\n#ifdef REFLECTION\nvarying vec3 vPositionUVW;\nuniform samplerCube reflectionCubeSampler;\nuniform sampler2D reflection2DSampler;\nuniform vec3 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform mat4 view;\n\nvec3 computeReflectionCoords(float mode, vec4 worldPos, vec3 worldNormal)\n{\n if (mode == MAP_SPHERICAL)\n {\n vec3 coords = vec3(view * vec4(worldNormal, 0.0));\n\n return vec3(reflectionMatrix * vec4(coords, 1.0));\n }\n else if (mode == MAP_PLANAR)\n {\n vec3 viewDir = worldPos.xyz - vEyePosition;\n vec3 coords = normalize(reflect(viewDir, worldNormal));\n\n return vec3(reflectionMatrix * vec4(coords, 1));\n }\n else if (mode == MAP_CUBIC)\n {\n vec3 viewDir = worldPos.xyz - vEyePosition;\n vec3 coords = reflect(viewDir, worldNormal);\n\n return vec3(reflectionMatrix * vec4(coords, 0));\n }\n else if (mode == MAP_PROJECTION)\n {\n return vec3(reflectionMatrix * (view * worldPos));\n }\n else if (mode == MAP_SKYBOX)\n {\n return vPositionUVW;\n }\n\n return vec3(0, 0, 0);\n}\n#endif\n\n// Shadows\n#ifdef SHADOWS\n\nfloat unpack(vec4 color)\n{\n const vec4 bitShift = vec4(1. / (255. * 255. * 255.), 1. / (255. * 255.), 1. / 255., 1.);\n return dot(color, bitShift);\n}\n\nfloat unpackHalf(vec2 color)\n{\n return color.x + (color.y / 255.0);\n}\n\nfloat computeShadow(vec4 vPositionFromLight, sampler2D shadowSampler, float darkness)\n{\n vec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\n vec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\n\n if (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n {\n return 1.0;\n }\n\n float shadow = unpack(texture2D(shadowSampler, uv));\n\n if (depth.z > shadow)\n {\n return darkness;\n }\n return 1.;\n}\n\nfloat computeShadowWithPCF(vec4 vPositionFromLight, sampler2D shadowSampler)\n{\n vec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\n vec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\n\n if (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n {\n return 1.0;\n }\n\n float visibility = 1.;\n\n vec2 poissonDisk[4];\n poissonDisk[0] = vec2(-0.94201624, -0.39906216);\n poissonDisk[1] = vec2(0.94558609, -0.76890725);\n poissonDisk[2] = vec2(-0.094184101, -0.92938870);\n poissonDisk[3] = vec2(0.34495938, 0.29387760);\n\n // Poisson Sampling\n if (unpack(texture2D(shadowSampler, uv + poissonDisk[0] / 1500.0)) < depth.z) visibility -= 0.2;\n if (unpack(texture2D(shadowSampler, uv + poissonDisk[1] / 1500.0)) < depth.z) visibility -= 0.2;\n if (unpack(texture2D(shadowSampler, uv + poissonDisk[2] / 1500.0)) < depth.z) visibility -= 0.2;\n if (unpack(texture2D(shadowSampler, uv + poissonDisk[3] / 1500.0)) < depth.z) visibility -= 0.2;\n\n return visibility;\n}\n\n// Thanks to http://devmaster.net/\nfloat ChebychevInequality(vec2 moments, float t)\n{\n if (t <= moments.x)\n {\n return 1.0;\n }\n\n float variance = moments.y - (moments.x * moments.x);\n variance = max(variance, 0.);\n\n float d = t - moments.x;\n return variance / (variance + d * d);\n}\n\nfloat computeShadowWithVSM(vec4 vPositionFromLight, sampler2D shadowSampler)\n{\n vec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\n vec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\n\n if (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n {\n return 1.0;\n }\n\n vec4 texel = texture2D(shadowSampler, uv);\n\n vec2 moments = vec2(unpackHalf(texel.xy), unpackHalf(texel.zw));\n return clamp(1.3 - ChebychevInequality(moments, depth.z), 0., 1.0);\n}\n#endif\n\n// Bump\n#ifdef BUMP\n#extension GL_OES_standard_derivatives : enable\nvarying vec2 vBumpUV;\nuniform vec2 vBumpInfos;\nuniform sampler2D bumpSampler;\n\n// Thanks to http://www.thetenthplanet.de/archives/1180\nmat3 cotangent_frame(vec3 normal, vec3 p, vec2 uv)\n{\n // get edge vectors of the pixel triangle\n vec3 dp1 = dFdx(p);\n vec3 dp2 = dFdy(p);\n vec2 duv1 = dFdx(uv);\n vec2 duv2 = dFdy(uv);\n\n // solve the linear system\n vec3 dp2perp = cross(dp2, normal);\n vec3 dp1perp = cross(normal, dp1);\n vec3 tangent = dp2perp * duv1.x + dp1perp * duv2.x;\n vec3 binormal = dp2perp * duv1.y + dp1perp * duv2.y;\n\n // construct a scale-invariant frame \n float invmax = inversesqrt(max(dot(tangent, tangent), dot(binormal, binormal)));\n return mat3(tangent * invmax, binormal * invmax, normal);\n}\n\nvec3 perturbNormal(vec3 viewDir)\n{\n vec3 map = texture2D(bumpSampler, vBumpUV).xyz;\n map = map * 255. / 127. - 128. / 127.;\n mat3 TBN = cotangent_frame(vNormalW * vBumpInfos.y, -viewDir, vBumpUV);\n return normalize(TBN * map);\n}\n#endif\n\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\n\n// Fog\n#ifdef FOG\n\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\n\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying float fFogDistance;\n\nfloat CalcFogFactor()\n{\n float fogCoeff = 1.0;\n float fogStart = vFogInfos.y;\n float fogEnd = vFogInfos.z;\n float fogDensity = vFogInfos.w;\n\n if (FOGMODE_LINEAR == vFogInfos.x)\n {\n fogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\n }\n else if (FOGMODE_EXP == vFogInfos.x)\n {\n fogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\n }\n else if (FOGMODE_EXP2 == vFogInfos.x)\n {\n fogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\n }\n\n return clamp(fogCoeff, 0.0, 1.0);\n}\n#endif\n\n// Light Computing\nstruct lightingInfo\n{\n vec3 diffuse;\n vec3 specular;\n};\n\nlightingInfo computeLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec3 diffuseColor, vec3 specularColor, float range) {\n lightingInfo result;\n\n vec3 lightVectorW;\n float attenuation = 1.0;\n if (lightData.w == 0.)\n {\n vec3 direction = lightData.xyz - vPositionW;\n\n attenuation = max(0., 1.0 - length(direction) / range);\n lightVectorW = normalize(direction);\n }\n else\n {\n lightVectorW = normalize(-lightData.xyz);\n }\n\n // diffuse\n float ndl = max(0., dot(vNormal, lightVectorW));\n\n // Specular\n vec3 angleW = normalize(viewDirectionW + lightVectorW);\n float specComp = max(0., dot(vNormal, angleW));\n specComp = pow(specComp, max(1., vSpecularColor.a));\n\n result.diffuse = ndl * diffuseColor * attenuation;\n result.specular = specComp * specularColor * attenuation;\n\n return result;\n}\n\nlightingInfo computeSpotLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 lightDirection, vec3 diffuseColor, vec3 specularColor, float range) {\n lightingInfo result;\n\n vec3 direction = lightData.xyz - vPositionW;\n vec3 lightVectorW = normalize(direction);\n float attenuation = max(0., 1.0 - length(direction) / range);\n\n // diffuse\n float cosAngle = max(0., dot(-lightDirection.xyz, lightVectorW));\n float spotAtten = 0.0;\n\n if (cosAngle >= lightDirection.w)\n {\n cosAngle = max(0., pow(cosAngle, lightData.w));\n spotAtten = max(0., (cosAngle - lightDirection.w) / (1. - cosAngle));\n\n // Diffuse\n float ndl = max(0., dot(vNormal, -lightDirection.xyz));\n\n // Specular\n vec3 angleW = normalize(viewDirectionW - lightDirection.xyz);\n float specComp = max(0., dot(vNormal, angleW));\n specComp = pow(specComp, vSpecularColor.a);\n\n result.diffuse = ndl * spotAtten * diffuseColor * attenuation;\n result.specular = specComp * specularColor * spotAtten * attenuation;\n\n return result;\n }\n\n result.diffuse = vec3(0.);\n result.specular = vec3(0.);\n\n return result;\n}\n\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec3 diffuseColor, vec3 specularColor, vec3 groundColor) {\n lightingInfo result;\n\n // Diffuse\n float ndl = dot(vNormal, lightData.xyz) * 0.5 + 0.5;\n\n // Specular\n vec3 angleW = normalize(viewDirectionW + lightData.xyz);\n float specComp = max(0., dot(vNormal, angleW));\n specComp = pow(specComp, vSpecularColor.a);\n\n result.diffuse = mix(groundColor, diffuseColor, ndl);\n result.specular = specComp * specularColor;\n\n return result;\n}\n\nvoid main(void) {\n // Clip plane\n#ifdef CLIPPLANE\n if (fClipDistance > 0.0)\n discard;\n#endif\n\n vec3 viewDirectionW = normalize(vEyePosition - vPositionW);\n\n // Base color\n vec4 baseColor = vec4(1., 1., 1., 1.);\n vec3 diffuseColor = vDiffuseColor.rgb;\n\n // Alpha\n float alpha = vDiffuseColor.a;\n\n#ifdef VERTEXCOLOR\n baseColor.rgb *= vColor.rgb;\n#endif\n\n#ifdef DIFFUSE\n baseColor = texture2D(diffuseSampler, vDiffuseUV);\n\n#ifdef ALPHATEST\n if (baseColor.a < 0.4)\n discard;\n#endif\n\n#ifdef ALPHAFROMDIFFUSE\n alpha *= baseColor.a;\n#endif\n\n baseColor.rgb *= vDiffuseInfos.y;\n#endif\n\n // Bump\n vec3 normalW = normalize(vNormalW);\n\n#ifdef BUMP\n normalW = perturbNormal(viewDirectionW);\n#endif\n\n // Ambient color\n vec3 baseAmbientColor = vec3(1., 1., 1.);\n\n#ifdef AMBIENT\n baseAmbientColor = texture2D(ambientSampler, vAmbientUV).rgb * vAmbientInfos.y;\n#endif\n\n // Lighting\n vec3 diffuseBase = vec3(0., 0., 0.);\n vec3 specularBase = vec3(0., 0., 0.);\n float shadow = 1.;\n\n#ifdef LIGHT0\n#ifdef SPOTLIGHT0\n lightingInfo info = computeSpotLighting(viewDirectionW, normalW, vLightData0, vLightDirection0, vLightDiffuse0.rgb, vLightSpecular0, vLightDiffuse0.a);\n#endif\n#ifdef HEMILIGHT0\n lightingInfo info = computeHemisphericLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0.rgb, vLightSpecular0, vLightGround0);\n#endif\n#ifdef POINTDIRLIGHT0\n lightingInfo info = computeLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0.rgb, vLightSpecular0, vLightDiffuse0.a);\n#endif\n#ifdef SHADOW0\n#ifdef SHADOWVSM0\n shadow = computeShadowWithVSM(vPositionFromLight0, shadowSampler0);\n#else\n #ifdef SHADOWPCF0\n shadow = computeShadowWithPCF(vPositionFromLight0, shadowSampler0);\n #else\n shadow = computeShadow(vPositionFromLight0, shadowSampler0, darkness0);\n #endif\n#endif\n#else\n shadow = 1.;\n#endif\n diffuseBase += info.diffuse * shadow;\n specularBase += info.specular * shadow;\n#endif\n\n#ifdef LIGHT1\n#ifdef SPOTLIGHT1\n info = computeSpotLighting(viewDirectionW, normalW, vLightData1, vLightDirection1, vLightDiffuse1.rgb, vLightSpecular1, vLightDiffuse1.a);\n#endif\n#ifdef HEMILIGHT1\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightSpecular1, vLightGround1);\n#endif\n#ifdef POINTDIRLIGHT1\n info = computeLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightSpecular1, vLightDiffuse1.a);\n#endif\n#ifdef SHADOW1\n#ifdef SHADOWVSM1\n shadow = computeShadowWithVSM(vPositionFromLight1, shadowSampler1);\n#else\n #ifdef SHADOWPCF1\n shadow = computeShadowWithPCF(vPositionFromLight1, shadowSampler1);\n #else\n shadow = computeShadow(vPositionFromLight1, shadowSampler1, darkness1);\n #endif\n#endif\n#else\n shadow = 1.;\n#endif\n diffuseBase += info.diffuse * shadow;\n specularBase += info.specular * shadow;\n#endif\n\n#ifdef LIGHT2\n#ifdef SPOTLIGHT2\n info = computeSpotLighting(viewDirectionW, normalW, vLightData2, vLightDirection2, vLightDiffuse2.rgb, vLightSpecular2, vLightDiffuse2.a);\n#endif\n#ifdef HEMILIGHT2\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightSpecular2, vLightGround2);\n#endif\n#ifdef POINTDIRLIGHT2\n info = computeLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightSpecular2, vLightDiffuse2.a);\n#endif\n#ifdef SHADOW2\n#ifdef SHADOWVSM2\n shadow = computeShadowWithVSM(vPositionFromLight2, shadowSampler2);\n#else\n #ifdef SHADOWPCF2\n shadow = computeShadowWithPCF(vPositionFromLight2, shadowSampler2);\n #else\n shadow = computeShadow(vPositionFromLight2, shadowSampler2, darkness2);\n #endif \n#endif \n#else\n shadow = 1.;\n#endif\n diffuseBase += info.diffuse * shadow;\n specularBase += info.specular * shadow;\n#endif\n\n#ifdef LIGHT3\n#ifdef SPOTLIGHT3\n info = computeSpotLighting(viewDirectionW, normalW, vLightData3, vLightDirection3, vLightDiffuse3.rgb, vLightSpecular3, vLightDiffuse3.a);\n#endif\n#ifdef HEMILIGHT3\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightSpecular3, vLightGround3);\n#endif\n#ifdef POINTDIRLIGHT3\n info = computeLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightSpecular3, vLightDiffuse3.a);\n#endif\n#ifdef SHADOW3\n#ifdef SHADOWVSM3\n shadow = computeShadowWithVSM(vPositionFromLight3, shadowSampler3);\n#else\n #ifdef SHADOWPCF3\n shadow = computeShadowWithPCF(vPositionFromLight3, shadowSampler3);\n #else\n shadow = computeShadow(vPositionFromLight3, shadowSampler3, darkness3);\n #endif \n#endif \n#else\n shadow = 1.;\n#endif\n diffuseBase += info.diffuse * shadow;\n specularBase += info.specular * shadow;\n#endif\n\n // Reflection\n vec3 reflectionColor = vec3(0., 0., 0.);\n\n#ifdef REFLECTION\n vec3 vReflectionUVW = computeReflectionCoords(vReflectionInfos.x, vec4(vPositionW, 1.0), normalW);\n\n if (vReflectionInfos.z != 0.0)\n {\n reflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW).rgb * vReflectionInfos.y * shadow;\n }\n else\n {\n vec2 coords = vReflectionUVW.xy;\n\n if (vReflectionInfos.x == MAP_PROJECTION)\n {\n coords /= vReflectionUVW.z;\n }\n\n coords.y = 1.0 - coords.y;\n\n reflectionColor = texture2D(reflection2DSampler, coords).rgb * vReflectionInfos.y * shadow;\n }\n\n#ifdef REFLECTIONFRESNEL\n float reflectionFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, reflectionRightColor.a, reflectionLeftColor.a);\n\n reflectionColor *= reflectionLeftColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\n#endif\n#endif\n\n#ifdef OPACITY\n vec4 opacityMap = texture2D(opacitySampler, vOpacityUV);\n\n#ifdef OPACITYRGB\n opacityMap.rgb = opacityMap.rgb * vec3(0.3, 0.59, 0.11);\n alpha *= (opacityMap.x + opacityMap.y + opacityMap.z)* vOpacityInfos.y;\n#else\n alpha *= opacityMap.a * vOpacityInfos.y;\n#endif\n\n#endif\n\n#ifdef VERTEXALPHA\n alpha *= vColor.a;\n#endif\n\n#ifdef OPACITYFRESNEL\n float opacityFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, opacityParts.z, opacityParts.w);\n\n alpha += opacityParts.x * (1.0 - opacityFresnelTerm) + opacityFresnelTerm * opacityParts.y;\n#endif\n\n // Emissive\n vec3 emissiveColor = vEmissiveColor;\n#ifdef EMISSIVE\n emissiveColor += texture2D(emissiveSampler, vEmissiveUV).rgb * vEmissiveInfos.y;\n#endif\n\n#ifdef EMISSIVEFRESNEL\n float emissiveFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, emissiveRightColor.a, emissiveLeftColor.a);\n\n emissiveColor *= emissiveLeftColor.rgb * (1.0 - emissiveFresnelTerm) + emissiveFresnelTerm * emissiveRightColor.rgb;\n#endif\n\n // Specular map\n vec3 specularColor = vSpecularColor.rgb;\n#ifdef SPECULAR\n specularColor = texture2D(specularSampler, vSpecularUV).rgb * vSpecularInfos.y;\n#endif\n\n // Fresnel\n#ifdef DIFFUSEFRESNEL\n float diffuseFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, diffuseRightColor.a, diffuseLeftColor.a);\n\n diffuseBase *= diffuseLeftColor.rgb * (1.0 - diffuseFresnelTerm) + diffuseFresnelTerm * diffuseRightColor.rgb;\n#endif\n\n // Composition\n vec3 finalDiffuse = clamp(diffuseBase * diffuseColor + emissiveColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\n vec3 finalSpecular = specularBase * specularColor;\n\n#ifdef SPECULAROVERALPHA\n alpha = clamp(alpha + dot(finalSpecular, vec3(0.3, 0.59, 0.11)), 0., 1.);\n#endif\n\n vec4 color = vec4(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor, alpha);\n\n#ifdef FOG\n float fog = CalcFogFactor();\n color.rgb = fog * color.rgb + (1.0 - fog) * vFogColor;\n#endif\n\n gl_FragColor = color;\n}",
  12396. defaultVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Attributes\nattribute vec3 position;\nattribute vec3 normal;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#ifdef BONES\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#endif\n\n// Uniforms\n\n#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif\n\nuniform mat4 view;\nuniform mat4 viewProjection;\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n\n#ifdef SPECULAR\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec2 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n\n#ifdef BONES\nuniform mat4 mBones[BonesPerMesh];\n#endif\n\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\n// Output\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif\n\n#ifdef FOG\nvarying float fFogDistance;\n#endif\n\n#ifdef SHADOWS\n#ifdef LIGHT0\nuniform mat4 lightMatrix0;\nvarying vec4 vPositionFromLight0;\n#endif\n#ifdef LIGHT1\nuniform mat4 lightMatrix1;\nvarying vec4 vPositionFromLight1;\n#endif\n#ifdef LIGHT2\nuniform mat4 lightMatrix2;\nvarying vec4 vPositionFromLight2;\n#endif\n#ifdef LIGHT3\nuniform mat4 lightMatrix3;\nvarying vec4 vPositionFromLight3;\n#endif\n#endif\n\n#ifdef REFLECTION\nvarying vec3 vPositionUVW;\n#endif\n\nvoid main(void) {\n mat4 finalWorld;\n\n#ifdef REFLECTION\n vPositionUVW = position;\n#endif \n\n#ifdef INSTANCES\n finalWorld = mat4(world0, world1, world2, world3);\n#else\n finalWorld = world;\n#endif\n\n#ifdef BONES\n mat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\n mat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\n mat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\n\n#ifdef BONES4\n mat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\n finalWorld = finalWorld * (m0 + m1 + m2 + m3);\n#else\n finalWorld = finalWorld * (m0 + m1 + m2);\n#endif \n\n#endif\n gl_Position = viewProjection * finalWorld * vec4(position, 1.0);\n\n vec4 worldPos = finalWorld * vec4(position, 1.0);\n vPositionW = vec3(worldPos);\n vNormalW = normalize(vec3(finalWorld * vec4(normal, 0.0)));\n\n // Texture coordinates\n#ifndef UV1\n vec2 uv = vec2(0., 0.);\n#endif\n#ifndef UV2\n vec2 uv2 = vec2(0., 0.);\n#endif\n\n#ifdef DIFFUSE\n if (vDiffuseInfos.x == 0.)\n {\n vDiffuseUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vDiffuseUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef AMBIENT\n if (vAmbientInfos.x == 0.)\n {\n vAmbientUV = vec2(ambientMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vAmbientUV = vec2(ambientMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef OPACITY\n if (vOpacityInfos.x == 0.)\n {\n vOpacityUV = vec2(opacityMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vOpacityUV = vec2(opacityMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef EMISSIVE\n if (vEmissiveInfos.x == 0.)\n {\n vEmissiveUV = vec2(emissiveMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vEmissiveUV = vec2(emissiveMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef SPECULAR\n if (vSpecularInfos.x == 0.)\n {\n vSpecularUV = vec2(specularMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vSpecularUV = vec2(specularMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef BUMP\n if (vBumpInfos.x == 0.)\n {\n vBumpUV = vec2(bumpMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vBumpUV = vec2(bumpMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n // Clip plane\n#ifdef CLIPPLANE\n fClipDistance = dot(worldPos, vClipPlane);\n#endif\n\n // Fog\n#ifdef FOG\n fFogDistance = (view * worldPos).z;\n#endif\n\n // Shadows\n#ifdef SHADOWS\n#ifdef LIGHT0\n vPositionFromLight0 = lightMatrix0 * worldPos;\n#endif\n#ifdef LIGHT1\n vPositionFromLight1 = lightMatrix1 * worldPos;\n#endif\n#ifdef LIGHT2\n vPositionFromLight2 = lightMatrix2 * worldPos;\n#endif\n#ifdef LIGHT3\n vPositionFromLight3 = lightMatrix3 * worldPos;\n#endif\n#endif\n\n // Vertex color\n#ifdef VERTEXCOLOR\n vColor = color;\n#endif\n\n // Point size\n#ifdef POINTSIZE\n gl_PointSize = pointSize;\n#endif\n}",
  12397. 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}",
  12398. 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}",
  12399. 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}",
  12400. 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}",
  12401. 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}",
  12402. 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}",
  12403. 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}",
  12404. 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}",
  12405. 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}",
  12406. 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}",
  12407. 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}",
  12408. 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}",
  12409. 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}",
  12410. 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}",
  12411. 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}",
  12412. 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}",
  12413. 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}",
  12414. 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}",
  12415. 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}",
  12416. 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}",
  12417. 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}",
  12418. 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}",
  12419. 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}",
  12420. 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}",
  12421. 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}",
  12422. 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}",
  12423. 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}",
  12424. };
  12425. return Effect;
  12426. })();
  12427. BABYLON.Effect = Effect;
  12428. })(BABYLON || (BABYLON = {}));
  12429. //# sourceMappingURL=babylon.effect.js.map
  12430. var BABYLON;
  12431. (function (BABYLON) {
  12432. var Material = (function () {
  12433. function Material(name, scene, doNotAdd) {
  12434. this.name = name;
  12435. this.checkReadyOnEveryCall = true;
  12436. this.checkReadyOnlyOnce = false;
  12437. this.state = "";
  12438. this.alpha = 1.0;
  12439. this.backFaceCulling = true;
  12440. this._wasPreviouslyReady = false;
  12441. this._fillMode = Material.TriangleFillMode;
  12442. this.pointSize = 1.0;
  12443. this.id = name;
  12444. this._scene = scene;
  12445. if (!doNotAdd) {
  12446. scene.materials.push(this);
  12447. }
  12448. }
  12449. Object.defineProperty(Material, "TriangleFillMode", {
  12450. get: function () {
  12451. return Material._TriangleFillMode;
  12452. },
  12453. enumerable: true,
  12454. configurable: true
  12455. });
  12456. Object.defineProperty(Material, "WireFrameFillMode", {
  12457. get: function () {
  12458. return Material._WireFrameFillMode;
  12459. },
  12460. enumerable: true,
  12461. configurable: true
  12462. });
  12463. Object.defineProperty(Material, "PointFillMode", {
  12464. get: function () {
  12465. return Material._PointFillMode;
  12466. },
  12467. enumerable: true,
  12468. configurable: true
  12469. });
  12470. Object.defineProperty(Material.prototype, "wireframe", {
  12471. get: function () {
  12472. return this._fillMode === Material.WireFrameFillMode;
  12473. },
  12474. set: function (value) {
  12475. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  12476. },
  12477. enumerable: true,
  12478. configurable: true
  12479. });
  12480. Object.defineProperty(Material.prototype, "pointsCloud", {
  12481. get: function () {
  12482. return this._fillMode === Material.PointFillMode;
  12483. },
  12484. set: function (value) {
  12485. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  12486. },
  12487. enumerable: true,
  12488. configurable: true
  12489. });
  12490. Object.defineProperty(Material.prototype, "fillMode", {
  12491. get: function () {
  12492. return this._fillMode;
  12493. },
  12494. set: function (value) {
  12495. this._fillMode = value;
  12496. },
  12497. enumerable: true,
  12498. configurable: true
  12499. });
  12500. Material.prototype.isReady = function (mesh, useInstances) {
  12501. return true;
  12502. };
  12503. Material.prototype.getEffect = function () {
  12504. return this._effect;
  12505. };
  12506. Material.prototype.getScene = function () {
  12507. return this._scene;
  12508. };
  12509. Material.prototype.needAlphaBlending = function () {
  12510. return (this.alpha < 1.0);
  12511. };
  12512. Material.prototype.needAlphaTesting = function () {
  12513. return false;
  12514. };
  12515. Material.prototype.getAlphaTestTexture = function () {
  12516. return null;
  12517. };
  12518. Material.prototype.trackCreation = function (onCompiled, onError) {
  12519. };
  12520. Material.prototype._preBind = function () {
  12521. var engine = this._scene.getEngine();
  12522. engine.enableEffect(this._effect);
  12523. engine.setState(this.backFaceCulling);
  12524. };
  12525. Material.prototype.bind = function (world, mesh) {
  12526. this._scene._cachedMaterial = this;
  12527. if (this.onBind) {
  12528. this.onBind(this);
  12529. }
  12530. };
  12531. Material.prototype.bindOnlyWorldMatrix = function (world) {
  12532. };
  12533. Material.prototype.unbind = function () {
  12534. };
  12535. Material.prototype.dispose = function (forceDisposeEffect) {
  12536. // Remove from scene
  12537. var index = this._scene.materials.indexOf(this);
  12538. this._scene.materials.splice(index, 1);
  12539. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  12540. if (forceDisposeEffect && this._effect) {
  12541. this._scene.getEngine()._releaseEffect(this._effect);
  12542. this._effect = null;
  12543. }
  12544. // Callback
  12545. if (this.onDispose) {
  12546. this.onDispose();
  12547. }
  12548. };
  12549. Material._TriangleFillMode = 0;
  12550. Material._WireFrameFillMode = 1;
  12551. Material._PointFillMode = 2;
  12552. return Material;
  12553. })();
  12554. BABYLON.Material = Material;
  12555. })(BABYLON || (BABYLON = {}));
  12556. //# sourceMappingURL=babylon.material.js.map
  12557. var BABYLON;
  12558. (function (BABYLON) {
  12559. var maxSimultaneousLights = 4;
  12560. var FresnelParameters = (function () {
  12561. function FresnelParameters() {
  12562. this.isEnabled = true;
  12563. this.leftColor = BABYLON.Color3.White();
  12564. this.rightColor = BABYLON.Color3.Black();
  12565. this.bias = 0;
  12566. this.power = 1;
  12567. }
  12568. return FresnelParameters;
  12569. })();
  12570. BABYLON.FresnelParameters = FresnelParameters;
  12571. var StandardMaterial = (function (_super) {
  12572. __extends(StandardMaterial, _super);
  12573. function StandardMaterial(name, scene) {
  12574. var _this = this;
  12575. _super.call(this, name, scene);
  12576. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  12577. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  12578. this.specularColor = new BABYLON.Color3(1, 1, 1);
  12579. this.specularPower = 64;
  12580. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  12581. this.useAlphaFromDiffuseTexture = false;
  12582. this.useSpecularOverAlpha = true;
  12583. this.fogEnabled = true;
  12584. this._cachedDefines = null;
  12585. this._renderTargets = new BABYLON.SmartArray(16);
  12586. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  12587. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  12588. this._scaledDiffuse = new BABYLON.Color3();
  12589. this._scaledSpecular = new BABYLON.Color3();
  12590. this.getRenderTargetTextures = function () {
  12591. _this._renderTargets.reset();
  12592. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  12593. _this._renderTargets.push(_this.reflectionTexture);
  12594. }
  12595. return _this._renderTargets;
  12596. };
  12597. }
  12598. StandardMaterial.prototype.needAlphaBlending = function () {
  12599. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  12600. };
  12601. StandardMaterial.prototype.needAlphaTesting = function () {
  12602. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && !this.diffuseTexture.getAlphaFromRGB;
  12603. };
  12604. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  12605. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  12606. };
  12607. StandardMaterial.prototype.getAlphaTestTexture = function () {
  12608. return this.diffuseTexture;
  12609. };
  12610. // Methods
  12611. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  12612. if (this.checkReadyOnlyOnce) {
  12613. if (this._wasPreviouslyReady) {
  12614. return true;
  12615. }
  12616. }
  12617. var scene = this.getScene();
  12618. if (!this.checkReadyOnEveryCall) {
  12619. if (this._renderId === scene.getRenderId()) {
  12620. return true;
  12621. }
  12622. }
  12623. var engine = scene.getEngine();
  12624. var defines = [];
  12625. var fallbacks = new BABYLON.EffectFallbacks();
  12626. // Textures
  12627. if (scene.texturesEnabled) {
  12628. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  12629. if (!this.diffuseTexture.isReady()) {
  12630. return false;
  12631. } else {
  12632. defines.push("#define DIFFUSE");
  12633. }
  12634. }
  12635. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  12636. if (!this.ambientTexture.isReady()) {
  12637. return false;
  12638. } else {
  12639. defines.push("#define AMBIENT");
  12640. }
  12641. }
  12642. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  12643. if (!this.opacityTexture.isReady()) {
  12644. return false;
  12645. } else {
  12646. defines.push("#define OPACITY");
  12647. if (this.opacityTexture.getAlphaFromRGB) {
  12648. defines.push("#define OPACITYRGB");
  12649. }
  12650. }
  12651. }
  12652. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  12653. if (!this.reflectionTexture.isReady()) {
  12654. return false;
  12655. } else {
  12656. defines.push("#define REFLECTION");
  12657. fallbacks.addFallback(0, "REFLECTION");
  12658. }
  12659. }
  12660. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  12661. if (!this.emissiveTexture.isReady()) {
  12662. return false;
  12663. } else {
  12664. defines.push("#define EMISSIVE");
  12665. }
  12666. }
  12667. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  12668. if (!this.specularTexture.isReady()) {
  12669. return false;
  12670. } else {
  12671. defines.push("#define SPECULAR");
  12672. fallbacks.addFallback(0, "SPECULAR");
  12673. }
  12674. }
  12675. }
  12676. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  12677. if (!this.bumpTexture.isReady()) {
  12678. return false;
  12679. } else {
  12680. defines.push("#define BUMP");
  12681. fallbacks.addFallback(0, "BUMP");
  12682. }
  12683. }
  12684. // Effect
  12685. if (this.useSpecularOverAlpha) {
  12686. defines.push("#define SPECULAROVERALPHA");
  12687. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  12688. }
  12689. if (scene.clipPlane) {
  12690. defines.push("#define CLIPPLANE");
  12691. }
  12692. if (engine.getAlphaTesting()) {
  12693. defines.push("#define ALPHATEST");
  12694. }
  12695. if (this._shouldUseAlphaFromDiffuseTexture()) {
  12696. defines.push("#define ALPHAFROMDIFFUSE");
  12697. }
  12698. // Point size
  12699. if (this.pointsCloud || scene.forcePointsCloud) {
  12700. defines.push("#define POINTSIZE");
  12701. }
  12702. // Fog
  12703. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  12704. defines.push("#define FOG");
  12705. fallbacks.addFallback(1, "FOG");
  12706. }
  12707. var shadowsActivated = false;
  12708. var lightIndex = 0;
  12709. if (scene.lightsEnabled) {
  12710. for (var index = 0; index < scene.lights.length; index++) {
  12711. var light = scene.lights[index];
  12712. if (!light.isEnabled()) {
  12713. continue;
  12714. }
  12715. // Excluded check
  12716. if (light._excludedMeshesIds.length > 0) {
  12717. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  12718. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  12719. if (excludedMesh) {
  12720. light.excludedMeshes.push(excludedMesh);
  12721. }
  12722. }
  12723. light._excludedMeshesIds = [];
  12724. }
  12725. // Included check
  12726. if (light._includedOnlyMeshesIds.length > 0) {
  12727. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  12728. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  12729. if (includedOnlyMesh) {
  12730. light.includedOnlyMeshes.push(includedOnlyMesh);
  12731. }
  12732. }
  12733. light._includedOnlyMeshesIds = [];
  12734. }
  12735. if (!light.canAffectMesh(mesh)) {
  12736. continue;
  12737. }
  12738. defines.push("#define LIGHT" + lightIndex);
  12739. if (lightIndex > 0) {
  12740. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  12741. }
  12742. var type;
  12743. if (light instanceof BABYLON.SpotLight) {
  12744. type = "#define SPOTLIGHT" + lightIndex;
  12745. } else if (light instanceof BABYLON.HemisphericLight) {
  12746. type = "#define HEMILIGHT" + lightIndex;
  12747. } else {
  12748. type = "#define POINTDIRLIGHT" + lightIndex;
  12749. }
  12750. defines.push(type);
  12751. if (lightIndex > 0) {
  12752. fallbacks.addFallback(lightIndex, type.replace("#define ", ""));
  12753. }
  12754. // Shadows
  12755. if (scene.shadowsEnabled) {
  12756. var shadowGenerator = light.getShadowGenerator();
  12757. if (mesh && mesh.receiveShadows && shadowGenerator) {
  12758. defines.push("#define SHADOW" + lightIndex);
  12759. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  12760. if (!shadowsActivated) {
  12761. defines.push("#define SHADOWS");
  12762. shadowsActivated = true;
  12763. }
  12764. if (shadowGenerator.useVarianceShadowMap) {
  12765. defines.push("#define SHADOWVSM" + lightIndex);
  12766. if (lightIndex > 0) {
  12767. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  12768. }
  12769. }
  12770. if (shadowGenerator.usePoissonSampling) {
  12771. defines.push("#define SHADOWPCF" + lightIndex);
  12772. if (lightIndex > 0) {
  12773. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  12774. }
  12775. }
  12776. }
  12777. }
  12778. lightIndex++;
  12779. if (lightIndex === maxSimultaneousLights)
  12780. break;
  12781. }
  12782. }
  12783. if (StandardMaterial.FresnelEnabled) {
  12784. // Fresnel
  12785. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled || this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled || this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  12786. var fresnelRank = 1;
  12787. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  12788. defines.push("#define DIFFUSEFRESNEL");
  12789. fallbacks.addFallback(fresnelRank, "DIFFUSEFRESNEL");
  12790. fresnelRank++;
  12791. }
  12792. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  12793. defines.push("#define OPACITYFRESNEL");
  12794. fallbacks.addFallback(fresnelRank, "OPACITYFRESNEL");
  12795. fresnelRank++;
  12796. }
  12797. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  12798. defines.push("#define REFLECTIONFRESNEL");
  12799. fallbacks.addFallback(fresnelRank, "REFLECTIONFRESNEL");
  12800. fresnelRank++;
  12801. }
  12802. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  12803. defines.push("#define EMISSIVEFRESNEL");
  12804. fallbacks.addFallback(fresnelRank, "EMISSIVEFRESNEL");
  12805. fresnelRank++;
  12806. }
  12807. defines.push("#define FRESNEL");
  12808. fallbacks.addFallback(fresnelRank - 1, "FRESNEL");
  12809. }
  12810. }
  12811. // Attribs
  12812. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  12813. if (mesh) {
  12814. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  12815. attribs.push(BABYLON.VertexBuffer.UVKind);
  12816. defines.push("#define UV1");
  12817. }
  12818. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  12819. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  12820. defines.push("#define UV2");
  12821. }
  12822. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  12823. attribs.push(BABYLON.VertexBuffer.ColorKind);
  12824. defines.push("#define VERTEXCOLOR");
  12825. if (mesh.hasVertexAlpha) {
  12826. defines.push("#define VERTEXALPHA");
  12827. }
  12828. }
  12829. if (mesh.skeleton && scene.skeletonsEnabled && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  12830. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  12831. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  12832. defines.push("#define BONES");
  12833. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  12834. defines.push("#define BONES4");
  12835. fallbacks.addFallback(0, "BONES4");
  12836. }
  12837. // Instances
  12838. if (useInstances) {
  12839. defines.push("#define INSTANCES");
  12840. attribs.push("world0");
  12841. attribs.push("world1");
  12842. attribs.push("world2");
  12843. attribs.push("world3");
  12844. }
  12845. }
  12846. // Get correct effect
  12847. var join = defines.join("\n");
  12848. if (this._cachedDefines !== join) {
  12849. this._cachedDefines = join;
  12850. scene.resetCachedMaterial();
  12851. // Legacy browser patch
  12852. var shaderName = "default";
  12853. if (!scene.getEngine().getCaps().standardDerivatives) {
  12854. shaderName = "legacydefault";
  12855. }
  12856. this._effect = scene.getEngine().createEffect(shaderName, attribs, [
  12857. "world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  12858. "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0",
  12859. "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1",
  12860. "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2",
  12861. "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3",
  12862. "vFogInfos", "vFogColor", "pointSize",
  12863. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos",
  12864. "mBones",
  12865. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix",
  12866. "darkness0", "darkness1", "darkness2", "darkness3",
  12867. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor"
  12868. ], [
  12869. "diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler",
  12870. "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"
  12871. ], join, fallbacks, this.onCompiled, this.onError);
  12872. }
  12873. if (!this._effect.isReady()) {
  12874. return false;
  12875. }
  12876. this._renderId = scene.getRenderId();
  12877. this._wasPreviouslyReady = true;
  12878. return true;
  12879. };
  12880. StandardMaterial.prototype.unbind = function () {
  12881. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  12882. this._effect.setTexture("reflection2DSampler", null);
  12883. }
  12884. };
  12885. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  12886. this._effect.setMatrix("world", world);
  12887. };
  12888. StandardMaterial.prototype.bind = function (world, mesh) {
  12889. var scene = this.getScene();
  12890. // Matrices
  12891. this.bindOnlyWorldMatrix(world);
  12892. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  12893. // Bones
  12894. if (mesh.skeleton && scene.skeletonsEnabled && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  12895. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  12896. }
  12897. if (scene.getCachedMaterial() !== this) {
  12898. if (StandardMaterial.FresnelEnabled) {
  12899. // Fresnel
  12900. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  12901. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  12902. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  12903. }
  12904. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  12905. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  12906. }
  12907. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  12908. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  12909. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  12910. }
  12911. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  12912. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  12913. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  12914. }
  12915. }
  12916. // Textures
  12917. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  12918. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  12919. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  12920. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  12921. }
  12922. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  12923. this._effect.setTexture("ambientSampler", this.ambientTexture);
  12924. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  12925. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  12926. }
  12927. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  12928. this._effect.setTexture("opacitySampler", this.opacityTexture);
  12929. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  12930. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  12931. }
  12932. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  12933. if (this.reflectionTexture.isCube) {
  12934. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  12935. } else {
  12936. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  12937. }
  12938. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  12939. this._effect.setFloat3("vReflectionInfos", this.reflectionTexture.coordinatesMode, this.reflectionTexture.level, this.reflectionTexture.isCube ? 1 : 0);
  12940. }
  12941. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  12942. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  12943. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  12944. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  12945. }
  12946. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  12947. this._effect.setTexture("specularSampler", this.specularTexture);
  12948. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  12949. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  12950. }
  12951. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  12952. this._effect.setTexture("bumpSampler", this.bumpTexture);
  12953. this._effect.setFloat2("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level);
  12954. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  12955. }
  12956. // Clip plane
  12957. if (scene.clipPlane) {
  12958. var clipPlane = scene.clipPlane;
  12959. this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  12960. }
  12961. // Point size
  12962. if (this.pointsCloud) {
  12963. this._effect.setFloat("pointSize", this.pointSize);
  12964. }
  12965. // Colors
  12966. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  12967. // Scaling down color according to emissive
  12968. this._scaledSpecular.r = this.specularColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  12969. this._scaledSpecular.g = this.specularColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  12970. this._scaledSpecular.b = this.specularColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  12971. this._effect.setVector3("vEyePosition", scene.activeCamera.position);
  12972. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  12973. this._effect.setColor4("vSpecularColor", this._scaledSpecular, this.specularPower);
  12974. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  12975. }
  12976. // Scaling down color according to emissive
  12977. this._scaledDiffuse.r = this.diffuseColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  12978. this._scaledDiffuse.g = this.diffuseColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  12979. this._scaledDiffuse.b = this.diffuseColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  12980. this._effect.setColor4("vDiffuseColor", this._scaledDiffuse, this.alpha * mesh.visibility);
  12981. if (scene.lightsEnabled) {
  12982. var lightIndex = 0;
  12983. for (var index = 0; index < scene.lights.length; index++) {
  12984. var light = scene.lights[index];
  12985. if (!light.isEnabled()) {
  12986. continue;
  12987. }
  12988. if (!light.canAffectMesh(mesh)) {
  12989. continue;
  12990. }
  12991. if (light instanceof BABYLON.PointLight) {
  12992. // Point Light
  12993. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  12994. } else if (light instanceof BABYLON.DirectionalLight) {
  12995. // Directional Light
  12996. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  12997. } else if (light instanceof BABYLON.SpotLight) {
  12998. // Spot Light
  12999. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  13000. } else if (light instanceof BABYLON.HemisphericLight) {
  13001. // Hemispheric Light
  13002. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  13003. }
  13004. light.diffuse.scaleToRef(light.intensity, this._scaledDiffuse);
  13005. light.specular.scaleToRef(light.intensity, this._scaledSpecular);
  13006. this._effect.setColor4("vLightDiffuse" + lightIndex, this._scaledDiffuse, light.range);
  13007. this._effect.setColor3("vLightSpecular" + lightIndex, this._scaledSpecular);
  13008. // Shadows
  13009. if (scene.shadowsEnabled) {
  13010. var shadowGenerator = light.getShadowGenerator();
  13011. if (mesh.receiveShadows && shadowGenerator) {
  13012. this._effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  13013. this._effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMap());
  13014. this._effect.setFloat("darkness" + lightIndex, shadowGenerator.getDarkness());
  13015. }
  13016. }
  13017. lightIndex++;
  13018. if (lightIndex === maxSimultaneousLights)
  13019. break;
  13020. }
  13021. }
  13022. // View
  13023. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  13024. this._effect.setMatrix("view", scene.getViewMatrix());
  13025. }
  13026. // Fog
  13027. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  13028. this._effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  13029. this._effect.setColor3("vFogColor", scene.fogColor);
  13030. }
  13031. _super.prototype.bind.call(this, world, mesh);
  13032. };
  13033. StandardMaterial.prototype.getAnimatables = function () {
  13034. var results = [];
  13035. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  13036. results.push(this.diffuseTexture);
  13037. }
  13038. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  13039. results.push(this.ambientTexture);
  13040. }
  13041. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  13042. results.push(this.opacityTexture);
  13043. }
  13044. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  13045. results.push(this.reflectionTexture);
  13046. }
  13047. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  13048. results.push(this.emissiveTexture);
  13049. }
  13050. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  13051. results.push(this.specularTexture);
  13052. }
  13053. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  13054. results.push(this.bumpTexture);
  13055. }
  13056. return results;
  13057. };
  13058. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  13059. if (this.diffuseTexture) {
  13060. this.diffuseTexture.dispose();
  13061. }
  13062. if (this.ambientTexture) {
  13063. this.ambientTexture.dispose();
  13064. }
  13065. if (this.opacityTexture) {
  13066. this.opacityTexture.dispose();
  13067. }
  13068. if (this.reflectionTexture) {
  13069. this.reflectionTexture.dispose();
  13070. }
  13071. if (this.emissiveTexture) {
  13072. this.emissiveTexture.dispose();
  13073. }
  13074. if (this.specularTexture) {
  13075. this.specularTexture.dispose();
  13076. }
  13077. if (this.bumpTexture) {
  13078. this.bumpTexture.dispose();
  13079. }
  13080. _super.prototype.dispose.call(this, forceDisposeEffect);
  13081. };
  13082. StandardMaterial.prototype.clone = function (name) {
  13083. var newStandardMaterial = new StandardMaterial(name, this.getScene());
  13084. // Base material
  13085. newStandardMaterial.checkReadyOnEveryCall = this.checkReadyOnEveryCall;
  13086. newStandardMaterial.alpha = this.alpha;
  13087. newStandardMaterial.fillMode = this.fillMode;
  13088. newStandardMaterial.backFaceCulling = this.backFaceCulling;
  13089. // Standard material
  13090. if (this.diffuseTexture && this.diffuseTexture.clone) {
  13091. newStandardMaterial.diffuseTexture = this.diffuseTexture.clone();
  13092. }
  13093. if (this.ambientTexture && this.ambientTexture.clone) {
  13094. newStandardMaterial.ambientTexture = this.ambientTexture.clone();
  13095. }
  13096. if (this.opacityTexture && this.opacityTexture.clone) {
  13097. newStandardMaterial.opacityTexture = this.opacityTexture.clone();
  13098. }
  13099. if (this.reflectionTexture && this.reflectionTexture.clone) {
  13100. newStandardMaterial.reflectionTexture = this.reflectionTexture.clone();
  13101. }
  13102. if (this.emissiveTexture && this.emissiveTexture.clone) {
  13103. newStandardMaterial.emissiveTexture = this.emissiveTexture.clone();
  13104. }
  13105. if (this.specularTexture && this.specularTexture.clone) {
  13106. newStandardMaterial.specularTexture = this.specularTexture.clone();
  13107. }
  13108. if (this.bumpTexture && this.bumpTexture.clone) {
  13109. newStandardMaterial.bumpTexture = this.bumpTexture.clone();
  13110. }
  13111. newStandardMaterial.ambientColor = this.ambientColor.clone();
  13112. newStandardMaterial.diffuseColor = this.diffuseColor.clone();
  13113. newStandardMaterial.specularColor = this.specularColor.clone();
  13114. newStandardMaterial.specularPower = this.specularPower;
  13115. newStandardMaterial.emissiveColor = this.emissiveColor.clone();
  13116. return newStandardMaterial;
  13117. };
  13118. StandardMaterial.DiffuseTextureEnabled = true;
  13119. StandardMaterial.AmbientTextureEnabled = true;
  13120. StandardMaterial.OpacityTextureEnabled = true;
  13121. StandardMaterial.ReflectionTextureEnabled = true;
  13122. StandardMaterial.EmissiveTextureEnabled = true;
  13123. StandardMaterial.SpecularTextureEnabled = true;
  13124. StandardMaterial.BumpTextureEnabled = true;
  13125. StandardMaterial.FresnelEnabled = true;
  13126. return StandardMaterial;
  13127. })(BABYLON.Material);
  13128. BABYLON.StandardMaterial = StandardMaterial;
  13129. })(BABYLON || (BABYLON = {}));
  13130. //# sourceMappingURL=babylon.standardMaterial.js.map
  13131. var BABYLON;
  13132. (function (BABYLON) {
  13133. var MultiMaterial = (function (_super) {
  13134. __extends(MultiMaterial, _super);
  13135. function MultiMaterial(name, scene) {
  13136. _super.call(this, name, scene, true);
  13137. this.subMaterials = new Array();
  13138. scene.multiMaterials.push(this);
  13139. }
  13140. // Properties
  13141. MultiMaterial.prototype.getSubMaterial = function (index) {
  13142. if (index < 0 || index >= this.subMaterials.length) {
  13143. return this.getScene().defaultMaterial;
  13144. }
  13145. return this.subMaterials[index];
  13146. };
  13147. // Methods
  13148. MultiMaterial.prototype.isReady = function (mesh) {
  13149. for (var index = 0; index < this.subMaterials.length; index++) {
  13150. var subMaterial = this.subMaterials[index];
  13151. if (subMaterial) {
  13152. if (!this.subMaterials[index].isReady(mesh)) {
  13153. return false;
  13154. }
  13155. }
  13156. }
  13157. return true;
  13158. };
  13159. return MultiMaterial;
  13160. })(BABYLON.Material);
  13161. BABYLON.MultiMaterial = MultiMaterial;
  13162. })(BABYLON || (BABYLON = {}));
  13163. //# sourceMappingURL=babylon.multiMaterial.js.map
  13164. var BABYLON;
  13165. (function (BABYLON) {
  13166. var Database = (function () {
  13167. function Database(urlToScene, callbackManifestChecked) {
  13168. // Handling various flavors of prefixed version of IndexedDB
  13169. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  13170. this.callbackManifestChecked = callbackManifestChecked;
  13171. this.currentSceneUrl = BABYLON.Database.ReturnFullUrlLocation(urlToScene);
  13172. this.db = null;
  13173. this.enableSceneOffline = false;
  13174. this.enableTexturesOffline = false;
  13175. this.manifestVersionFound = 0;
  13176. this.mustUpdateRessources = false;
  13177. this.hasReachedQuota = false;
  13178. this.checkManifestFile();
  13179. }
  13180. Database.prototype.checkManifestFile = function () {
  13181. var _this = this;
  13182. function noManifestFile() {
  13183. BABYLON.Tools.Log("Valid manifest file not found. Scene & textures will be loaded directly from the web server.");
  13184. that.enableSceneOffline = false;
  13185. that.enableTexturesOffline = false;
  13186. that.callbackManifestChecked(false);
  13187. }
  13188. var that = this;
  13189. var manifestURL = this.currentSceneUrl + ".manifest";
  13190. var xhr = new XMLHttpRequest();
  13191. var manifestURLTimeStamped = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  13192. xhr.open("GET", manifestURLTimeStamped, true);
  13193. xhr.addEventListener("load", function () {
  13194. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  13195. try {
  13196. var manifestFile = JSON.parse(xhr.response);
  13197. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  13198. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  13199. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  13200. _this.manifestVersionFound = manifestFile.version;
  13201. }
  13202. if (_this.callbackManifestChecked) {
  13203. _this.callbackManifestChecked(true);
  13204. }
  13205. } catch (ex) {
  13206. noManifestFile();
  13207. }
  13208. } else {
  13209. noManifestFile();
  13210. }
  13211. }, false);
  13212. xhr.addEventListener("error", function (event) {
  13213. noManifestFile();
  13214. }, false);
  13215. try {
  13216. xhr.send();
  13217. } catch (ex) {
  13218. BABYLON.Tools.Error("Error on XHR send request.");
  13219. that.callbackManifestChecked(false);
  13220. }
  13221. };
  13222. Database.prototype.openAsync = function (successCallback, errorCallback) {
  13223. var _this = this;
  13224. function handleError() {
  13225. that.isSupported = false;
  13226. if (errorCallback)
  13227. errorCallback();
  13228. }
  13229. var that = this;
  13230. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  13231. // Your browser doesn't support IndexedDB
  13232. this.isSupported = false;
  13233. if (errorCallback)
  13234. errorCallback();
  13235. } else {
  13236. // If the DB hasn't been opened or created yet
  13237. if (!this.db) {
  13238. this.hasReachedQuota = false;
  13239. this.isSupported = true;
  13240. var request = this.idbFactory.open("babylonjs", 1);
  13241. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  13242. request.onerror = function (event) {
  13243. handleError();
  13244. };
  13245. // executes when a version change transaction cannot complete due to other active transactions
  13246. request.onblocked = function (event) {
  13247. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  13248. handleError();
  13249. };
  13250. // DB has been opened successfully
  13251. request.onsuccess = function (event) {
  13252. _this.db = request.result;
  13253. successCallback();
  13254. };
  13255. // Initialization of the DB. Creating Scenes & Textures stores
  13256. request.onupgradeneeded = function (event) {
  13257. _this.db = (event.target).result;
  13258. try {
  13259. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  13260. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  13261. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  13262. } catch (ex) {
  13263. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  13264. handleError();
  13265. }
  13266. };
  13267. } else {
  13268. if (successCallback)
  13269. successCallback();
  13270. }
  13271. }
  13272. };
  13273. Database.prototype.loadImageFromDB = function (url, image) {
  13274. var _this = this;
  13275. var completeURL = BABYLON.Database.ReturnFullUrlLocation(url);
  13276. var saveAndLoadImage = function () {
  13277. if (!_this.hasReachedQuota && _this.db !== null) {
  13278. // the texture is not yet in the DB, let's try to save it
  13279. _this._saveImageIntoDBAsync(completeURL, image);
  13280. } else {
  13281. image.src = url;
  13282. }
  13283. };
  13284. if (!this.mustUpdateRessources) {
  13285. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  13286. } else {
  13287. saveAndLoadImage();
  13288. }
  13289. };
  13290. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  13291. if (this.isSupported && this.db !== null) {
  13292. var texture;
  13293. var transaction = this.db.transaction(["textures"]);
  13294. transaction.onabort = function (event) {
  13295. image.src = url;
  13296. };
  13297. transaction.oncomplete = function (event) {
  13298. var blobTextureURL;
  13299. if (texture) {
  13300. var URL = window.URL || window.webkitURL;
  13301. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  13302. image.onerror = function () {
  13303. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  13304. image.src = url;
  13305. };
  13306. image.src = blobTextureURL;
  13307. } else {
  13308. notInDBCallback();
  13309. }
  13310. };
  13311. var getRequest = transaction.objectStore("textures").get(url);
  13312. getRequest.onsuccess = function (event) {
  13313. texture = (event.target).result;
  13314. };
  13315. getRequest.onerror = function (event) {
  13316. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  13317. image.src = url;
  13318. };
  13319. } else {
  13320. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  13321. image.src = url;
  13322. }
  13323. };
  13324. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  13325. var _this = this;
  13326. if (this.isSupported) {
  13327. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  13328. var generateBlobUrl = function () {
  13329. var blobTextureURL;
  13330. if (blob) {
  13331. var URL = window.URL || window.webkitURL;
  13332. try {
  13333. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  13334. } catch (ex) {
  13335. blobTextureURL = URL.createObjectURL(blob);
  13336. }
  13337. }
  13338. image.src = blobTextureURL;
  13339. };
  13340. if (BABYLON.Database.isUASupportingBlobStorage) {
  13341. var xhr = new XMLHttpRequest(), blob;
  13342. xhr.open("GET", url, true);
  13343. xhr.responseType = "blob";
  13344. xhr.addEventListener("load", function () {
  13345. if (xhr.status === 200) {
  13346. // Blob as response (XHR2)
  13347. blob = xhr.response;
  13348. var transaction = _this.db.transaction(["textures"], "readwrite");
  13349. // the transaction could abort because of a QuotaExceededError error
  13350. transaction.onabort = function (event) {
  13351. try {
  13352. if (event.srcElement.error.name === "QuotaExceededError") {
  13353. this.hasReachedQuota = true;
  13354. }
  13355. } catch (ex) {
  13356. }
  13357. generateBlobUrl();
  13358. };
  13359. transaction.oncomplete = function (event) {
  13360. generateBlobUrl();
  13361. };
  13362. var newTexture = { textureUrl: url, data: blob };
  13363. try {
  13364. // Put the blob into the dabase
  13365. var addRequest = transaction.objectStore("textures").put(newTexture);
  13366. addRequest.onsuccess = function (event) {
  13367. };
  13368. addRequest.onerror = function (event) {
  13369. generateBlobUrl();
  13370. };
  13371. } catch (ex) {
  13372. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  13373. if (ex.code === 25) {
  13374. BABYLON.Database.isUASupportingBlobStorage = false;
  13375. }
  13376. image.src = url;
  13377. }
  13378. } else {
  13379. image.src = url;
  13380. }
  13381. }, false);
  13382. xhr.addEventListener("error", function (event) {
  13383. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  13384. image.src = url;
  13385. }, false);
  13386. xhr.send();
  13387. } else {
  13388. image.src = url;
  13389. }
  13390. } else {
  13391. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  13392. image.src = url;
  13393. }
  13394. };
  13395. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  13396. var _this = this;
  13397. var updateVersion = function (event) {
  13398. // the version is not yet in the DB or we need to update it
  13399. _this._saveVersionIntoDBAsync(url, versionLoaded);
  13400. };
  13401. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  13402. };
  13403. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  13404. var _this = this;
  13405. if (this.isSupported) {
  13406. var version;
  13407. try {
  13408. var transaction = this.db.transaction(["versions"]);
  13409. transaction.oncomplete = function (event) {
  13410. if (version) {
  13411. // If the version in the JSON file is > than the version in DB
  13412. if (_this.manifestVersionFound > version.data) {
  13413. _this.mustUpdateRessources = true;
  13414. updateInDBCallback();
  13415. } else {
  13416. callback(version.data);
  13417. }
  13418. } else {
  13419. _this.mustUpdateRessources = true;
  13420. updateInDBCallback();
  13421. }
  13422. };
  13423. transaction.onabort = function (event) {
  13424. callback(-1);
  13425. };
  13426. var getRequest = transaction.objectStore("versions").get(url);
  13427. getRequest.onsuccess = function (event) {
  13428. version = (event.target).result;
  13429. };
  13430. getRequest.onerror = function (event) {
  13431. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  13432. callback(-1);
  13433. };
  13434. } catch (ex) {
  13435. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  13436. callback(-1);
  13437. }
  13438. } else {
  13439. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  13440. callback(-1);
  13441. }
  13442. };
  13443. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  13444. var _this = this;
  13445. if (this.isSupported && !this.hasReachedQuota) {
  13446. try {
  13447. // Open a transaction to the database
  13448. var transaction = this.db.transaction(["versions"], "readwrite");
  13449. // the transaction could abort because of a QuotaExceededError error
  13450. transaction.onabort = function (event) {
  13451. try {
  13452. if (event.srcElement.error.name === "QuotaExceededError") {
  13453. _this.hasReachedQuota = true;
  13454. }
  13455. } catch (ex) {
  13456. }
  13457. callback(-1);
  13458. };
  13459. transaction.oncomplete = function (event) {
  13460. callback(_this.manifestVersionFound);
  13461. };
  13462. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  13463. // Put the scene into the database
  13464. var addRequest = transaction.objectStore("versions").put(newVersion);
  13465. addRequest.onsuccess = function (event) {
  13466. };
  13467. addRequest.onerror = function (event) {
  13468. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  13469. };
  13470. } catch (ex) {
  13471. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  13472. callback(-1);
  13473. }
  13474. } else {
  13475. callback(-1);
  13476. }
  13477. };
  13478. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  13479. var _this = this;
  13480. var completeUrl = BABYLON.Database.ReturnFullUrlLocation(url);
  13481. var saveAndLoadFile = function (event) {
  13482. // the scene is not yet in the DB, let's try to save it
  13483. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  13484. };
  13485. this._checkVersionFromDB(completeUrl, function (version) {
  13486. if (version !== -1) {
  13487. if (!_this.mustUpdateRessources) {
  13488. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  13489. } else {
  13490. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  13491. }
  13492. } else {
  13493. errorCallback();
  13494. }
  13495. });
  13496. };
  13497. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  13498. if (this.isSupported) {
  13499. var targetStore;
  13500. if (url.indexOf(".babylon") !== -1) {
  13501. targetStore = "scenes";
  13502. } else {
  13503. targetStore = "textures";
  13504. }
  13505. var file;
  13506. var transaction = this.db.transaction([targetStore]);
  13507. transaction.oncomplete = function (event) {
  13508. if (file) {
  13509. callback(file.data);
  13510. } else {
  13511. notInDBCallback();
  13512. }
  13513. };
  13514. transaction.onabort = function (event) {
  13515. notInDBCallback();
  13516. };
  13517. var getRequest = transaction.objectStore(targetStore).get(url);
  13518. getRequest.onsuccess = function (event) {
  13519. file = (event.target).result;
  13520. };
  13521. getRequest.onerror = function (event) {
  13522. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  13523. notInDBCallback();
  13524. };
  13525. } else {
  13526. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  13527. callback();
  13528. }
  13529. };
  13530. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  13531. var _this = this;
  13532. if (this.isSupported) {
  13533. var targetStore;
  13534. if (url.indexOf(".babylon") !== -1) {
  13535. targetStore = "scenes";
  13536. } else {
  13537. targetStore = "textures";
  13538. }
  13539. // Create XHR
  13540. var xhr = new XMLHttpRequest(), fileData;
  13541. xhr.open("GET", url, true);
  13542. if (useArrayBuffer) {
  13543. xhr.responseType = "arraybuffer";
  13544. }
  13545. xhr.onprogress = progressCallback;
  13546. xhr.addEventListener("load", function () {
  13547. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  13548. // Blob as response (XHR2)
  13549. //fileData = xhr.responseText;
  13550. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  13551. if (!_this.hasReachedQuota) {
  13552. // Open a transaction to the database
  13553. var transaction = _this.db.transaction([targetStore], "readwrite");
  13554. // the transaction could abort because of a QuotaExceededError error
  13555. transaction.onabort = function (event) {
  13556. try {
  13557. if (event.srcElement.error.name === "QuotaExceededError") {
  13558. this.hasReachedQuota = true;
  13559. }
  13560. } catch (ex) {
  13561. }
  13562. callback(fileData);
  13563. };
  13564. transaction.oncomplete = function (event) {
  13565. callback(fileData);
  13566. };
  13567. var newFile;
  13568. if (targetStore === "scenes") {
  13569. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  13570. } else {
  13571. newFile = { textureUrl: url, data: fileData };
  13572. }
  13573. try {
  13574. // Put the scene into the database
  13575. var addRequest = transaction.objectStore(targetStore).put(newFile);
  13576. addRequest.onsuccess = function (event) {
  13577. };
  13578. addRequest.onerror = function (event) {
  13579. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  13580. };
  13581. } catch (ex) {
  13582. callback(fileData);
  13583. }
  13584. } else {
  13585. callback(fileData);
  13586. }
  13587. } else {
  13588. callback();
  13589. }
  13590. }, false);
  13591. xhr.addEventListener("error", function (event) {
  13592. BABYLON.Tools.Error("error on XHR request.");
  13593. callback();
  13594. }, false);
  13595. xhr.send();
  13596. } else {
  13597. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  13598. callback();
  13599. }
  13600. };
  13601. Database.isUASupportingBlobStorage = true;
  13602. Database.parseURL = function (url) {
  13603. var a = document.createElement('a');
  13604. a.href = url;
  13605. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  13606. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  13607. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  13608. return absLocation;
  13609. };
  13610. Database.ReturnFullUrlLocation = function (url) {
  13611. if (url.indexOf("http:/") === -1) {
  13612. return (BABYLON.Database.parseURL(window.location.href) + url);
  13613. } else {
  13614. return url;
  13615. }
  13616. };
  13617. return Database;
  13618. })();
  13619. BABYLON.Database = Database;
  13620. })(BABYLON || (BABYLON = {}));
  13621. //# sourceMappingURL=babylon.database.js.map
  13622. var BABYLON;
  13623. (function (BABYLON) {
  13624. var SpriteManager = (function () {
  13625. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon) {
  13626. this.name = name;
  13627. this.cellSize = cellSize;
  13628. this.sprites = new Array();
  13629. this.renderingGroupId = 0;
  13630. this.fogEnabled = true;
  13631. this._vertexDeclaration = [3, 4, 4, 4];
  13632. this._vertexStrideSize = 15 * 4;
  13633. this._capacity = capacity;
  13634. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false);
  13635. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  13636. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  13637. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  13638. this._scene = scene;
  13639. this._scene.spriteManagers.push(this);
  13640. // VBO
  13641. this._vertexDeclaration = [3, 4, 4, 4];
  13642. this._vertexStrideSize = 15 * 4;
  13643. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  13644. var indices = [];
  13645. var index = 0;
  13646. for (var count = 0; count < capacity; count++) {
  13647. indices.push(index);
  13648. indices.push(index + 1);
  13649. indices.push(index + 2);
  13650. indices.push(index);
  13651. indices.push(index + 2);
  13652. indices.push(index + 3);
  13653. index += 4;
  13654. }
  13655. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  13656. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  13657. // Effects
  13658. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  13659. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  13660. }
  13661. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  13662. var arrayOffset = index * 15;
  13663. if (offsetX == 0)
  13664. offsetX = this._epsilon;
  13665. else if (offsetX == 1)
  13666. offsetX = 1 - this._epsilon;
  13667. if (offsetY == 0)
  13668. offsetY = this._epsilon;
  13669. else if (offsetY == 1)
  13670. offsetY = 1 - this._epsilon;
  13671. this._vertices[arrayOffset] = sprite.position.x;
  13672. this._vertices[arrayOffset + 1] = sprite.position.y;
  13673. this._vertices[arrayOffset + 2] = sprite.position.z;
  13674. this._vertices[arrayOffset + 3] = sprite.angle;
  13675. this._vertices[arrayOffset + 4] = sprite.size;
  13676. this._vertices[arrayOffset + 5] = offsetX;
  13677. this._vertices[arrayOffset + 6] = offsetY;
  13678. this._vertices[arrayOffset + 7] = sprite.invertU ? 1 : 0;
  13679. this._vertices[arrayOffset + 8] = sprite.invertV ? 1 : 0;
  13680. var offset = (sprite.cellIndex / rowSize) >> 0;
  13681. this._vertices[arrayOffset + 9] = sprite.cellIndex - offset * rowSize;
  13682. this._vertices[arrayOffset + 10] = offset;
  13683. // Color
  13684. this._vertices[arrayOffset + 11] = sprite.color.r;
  13685. this._vertices[arrayOffset + 12] = sprite.color.g;
  13686. this._vertices[arrayOffset + 13] = sprite.color.b;
  13687. this._vertices[arrayOffset + 14] = sprite.color.a;
  13688. };
  13689. SpriteManager.prototype.render = function () {
  13690. // Check
  13691. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  13692. return;
  13693. var engine = this._scene.getEngine();
  13694. var baseSize = this._spriteTexture.getBaseSize();
  13695. // Sprites
  13696. var deltaTime = engine.getDeltaTime();
  13697. var max = Math.min(this._capacity, this.sprites.length);
  13698. var rowSize = baseSize.width / this.cellSize;
  13699. var offset = 0;
  13700. for (var index = 0; index < max; index++) {
  13701. var sprite = this.sprites[index];
  13702. if (!sprite) {
  13703. continue;
  13704. }
  13705. sprite._animate(deltaTime);
  13706. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  13707. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  13708. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  13709. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  13710. }
  13711. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  13712. // Render
  13713. var effect = this._effectBase;
  13714. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  13715. effect = this._effectFog;
  13716. }
  13717. engine.enableEffect(effect);
  13718. var viewMatrix = this._scene.getViewMatrix();
  13719. effect.setTexture("diffuseSampler", this._spriteTexture);
  13720. effect.setMatrix("view", viewMatrix);
  13721. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  13722. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  13723. // Fog
  13724. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  13725. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  13726. effect.setColor3("vFogColor", this._scene.fogColor);
  13727. }
  13728. // VBOs
  13729. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  13730. // Draw order
  13731. effect.setBool("alphaTest", true);
  13732. engine.setColorWrite(false);
  13733. engine.draw(true, 0, max * 6);
  13734. engine.setColorWrite(true);
  13735. effect.setBool("alphaTest", false);
  13736. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  13737. engine.draw(true, 0, max * 6);
  13738. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  13739. };
  13740. SpriteManager.prototype.dispose = function () {
  13741. if (this._vertexBuffer) {
  13742. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  13743. this._vertexBuffer = null;
  13744. }
  13745. if (this._indexBuffer) {
  13746. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  13747. this._indexBuffer = null;
  13748. }
  13749. if (this._spriteTexture) {
  13750. this._spriteTexture.dispose();
  13751. this._spriteTexture = null;
  13752. }
  13753. // Remove from scene
  13754. var index = this._scene.spriteManagers.indexOf(this);
  13755. this._scene.spriteManagers.splice(index, 1);
  13756. // Callback
  13757. if (this.onDispose) {
  13758. this.onDispose();
  13759. }
  13760. };
  13761. return SpriteManager;
  13762. })();
  13763. BABYLON.SpriteManager = SpriteManager;
  13764. })(BABYLON || (BABYLON = {}));
  13765. //# sourceMappingURL=babylon.spriteManager.js.map
  13766. var BABYLON;
  13767. (function (BABYLON) {
  13768. var Sprite = (function () {
  13769. function Sprite(name, manager) {
  13770. this.name = name;
  13771. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  13772. this.size = 1.0;
  13773. this.angle = 0;
  13774. this.cellIndex = 0;
  13775. this.invertU = 0;
  13776. this.invertV = 0;
  13777. this.animations = new Array();
  13778. this._animationStarted = false;
  13779. this._loopAnimation = false;
  13780. this._fromIndex = 0;
  13781. this._toIndex = 0;
  13782. this._delay = 0;
  13783. this._direction = 1;
  13784. this._frameCount = 0;
  13785. this._time = 0;
  13786. this._manager = manager;
  13787. this._manager.sprites.push(this);
  13788. this.position = BABYLON.Vector3.Zero();
  13789. }
  13790. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  13791. this._fromIndex = from;
  13792. this._toIndex = to;
  13793. this._loopAnimation = loop;
  13794. this._delay = delay;
  13795. this._animationStarted = true;
  13796. this._direction = from < to ? 1 : -1;
  13797. this.cellIndex = from;
  13798. this._time = 0;
  13799. };
  13800. Sprite.prototype.stopAnimation = function () {
  13801. this._animationStarted = false;
  13802. };
  13803. Sprite.prototype._animate = function (deltaTime) {
  13804. if (!this._animationStarted)
  13805. return;
  13806. this._time += deltaTime;
  13807. if (this._time > this._delay) {
  13808. this._time = this._time % this._delay;
  13809. this.cellIndex += this._direction;
  13810. if (this.cellIndex == this._toIndex) {
  13811. if (this._loopAnimation) {
  13812. this.cellIndex = this._fromIndex;
  13813. } else {
  13814. this._animationStarted = false;
  13815. if (this.disposeWhenFinishedAnimating) {
  13816. this.dispose();
  13817. }
  13818. }
  13819. }
  13820. }
  13821. };
  13822. Sprite.prototype.dispose = function () {
  13823. for (var i = 0; i < this._manager.sprites.length; i++) {
  13824. if (this._manager.sprites[i] == this) {
  13825. this._manager.sprites.splice(i, 1);
  13826. }
  13827. }
  13828. };
  13829. return Sprite;
  13830. })();
  13831. BABYLON.Sprite = Sprite;
  13832. })(BABYLON || (BABYLON = {}));
  13833. //# sourceMappingURL=babylon.sprite.js.map
  13834. var BABYLON;
  13835. (function (BABYLON) {
  13836. var Layer = (function () {
  13837. function Layer(name, imgUrl, scene, isBackground, color) {
  13838. this.name = name;
  13839. this._vertexDeclaration = [2];
  13840. this._vertexStrideSize = 2 * 4;
  13841. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  13842. this.isBackground = isBackground === undefined ? true : isBackground;
  13843. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  13844. this._scene = scene;
  13845. this._scene.layers.push(this);
  13846. // VBO
  13847. var vertices = [];
  13848. vertices.push(1, 1);
  13849. vertices.push(-1, 1);
  13850. vertices.push(-1, -1);
  13851. vertices.push(1, -1);
  13852. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  13853. // Indices
  13854. var indices = [];
  13855. indices.push(0);
  13856. indices.push(1);
  13857. indices.push(2);
  13858. indices.push(0);
  13859. indices.push(2);
  13860. indices.push(3);
  13861. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  13862. // Effects
  13863. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color"], ["textureSampler"], "");
  13864. }
  13865. Layer.prototype.render = function () {
  13866. // Check
  13867. if (!this._effect.isReady() || !this.texture || !this.texture.isReady())
  13868. return;
  13869. var engine = this._scene.getEngine();
  13870. // Render
  13871. engine.enableEffect(this._effect);
  13872. engine.setState(false);
  13873. // Texture
  13874. this._effect.setTexture("textureSampler", this.texture);
  13875. this._effect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  13876. // Color
  13877. this._effect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  13878. // VBOs
  13879. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  13880. // Draw order
  13881. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  13882. engine.draw(true, 0, 6);
  13883. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  13884. };
  13885. Layer.prototype.dispose = function () {
  13886. if (this._vertexBuffer) {
  13887. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  13888. this._vertexBuffer = null;
  13889. }
  13890. if (this._indexBuffer) {
  13891. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  13892. this._indexBuffer = null;
  13893. }
  13894. if (this.texture) {
  13895. this.texture.dispose();
  13896. this.texture = null;
  13897. }
  13898. // Remove from scene
  13899. var index = this._scene.layers.indexOf(this);
  13900. this._scene.layers.splice(index, 1);
  13901. // Callback
  13902. if (this.onDispose) {
  13903. this.onDispose();
  13904. }
  13905. };
  13906. return Layer;
  13907. })();
  13908. BABYLON.Layer = Layer;
  13909. })(BABYLON || (BABYLON = {}));
  13910. //# sourceMappingURL=babylon.layer.js.map
  13911. var BABYLON;
  13912. (function (BABYLON) {
  13913. var Particle = (function () {
  13914. function Particle() {
  13915. this.position = BABYLON.Vector3.Zero();
  13916. this.direction = BABYLON.Vector3.Zero();
  13917. this.color = new BABYLON.Color4(0, 0, 0, 0);
  13918. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  13919. this.lifeTime = 1.0;
  13920. this.age = 0;
  13921. this.size = 0;
  13922. this.angle = 0;
  13923. this.angularSpeed = 0;
  13924. }
  13925. return Particle;
  13926. })();
  13927. BABYLON.Particle = Particle;
  13928. })(BABYLON || (BABYLON = {}));
  13929. //# sourceMappingURL=babylon.particle.js.map
  13930. var BABYLON;
  13931. (function (BABYLON) {
  13932. var randomNumber = function (min, max) {
  13933. if (min === max) {
  13934. return (min);
  13935. }
  13936. var random = Math.random();
  13937. return ((random * (max - min)) + min);
  13938. };
  13939. var ParticleSystem = (function () {
  13940. function ParticleSystem(name, capacity, scene, customEffect) {
  13941. var _this = this;
  13942. this.name = name;
  13943. this.renderingGroupId = 0;
  13944. this.emitter = null;
  13945. this.emitRate = 10;
  13946. this.manualEmitCount = -1;
  13947. this.updateSpeed = 0.01;
  13948. this.targetStopDuration = 0;
  13949. this.disposeOnStop = false;
  13950. this.minEmitPower = 1;
  13951. this.maxEmitPower = 1;
  13952. this.minLifeTime = 1;
  13953. this.maxLifeTime = 1;
  13954. this.minSize = 1;
  13955. this.maxSize = 1;
  13956. this.minAngularSpeed = 0;
  13957. this.maxAngularSpeed = 0;
  13958. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  13959. this.forceDepthWrite = false;
  13960. this.gravity = BABYLON.Vector3.Zero();
  13961. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  13962. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  13963. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  13964. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  13965. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  13966. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  13967. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  13968. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  13969. this.particles = new Array();
  13970. this._vertexDeclaration = [3, 4, 4];
  13971. this._vertexStrideSize = 11 * 4;
  13972. this._stockParticles = new Array();
  13973. this._newPartsExcess = 0;
  13974. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  13975. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  13976. this._scaledDirection = BABYLON.Vector3.Zero();
  13977. this._scaledGravity = BABYLON.Vector3.Zero();
  13978. this._currentRenderId = -1;
  13979. this._started = false;
  13980. this._stopped = false;
  13981. this._actualFrame = 0;
  13982. this.id = name;
  13983. this._capacity = capacity;
  13984. this._scene = scene;
  13985. this._customEffect = customEffect;
  13986. scene.particleSystems.push(this);
  13987. // VBO
  13988. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  13989. var indices = [];
  13990. var index = 0;
  13991. for (var count = 0; count < capacity; count++) {
  13992. indices.push(index);
  13993. indices.push(index + 1);
  13994. indices.push(index + 2);
  13995. indices.push(index);
  13996. indices.push(index + 2);
  13997. indices.push(index + 3);
  13998. index += 4;
  13999. }
  14000. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  14001. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  14002. // Default behaviors
  14003. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate) {
  14004. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  14005. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  14006. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  14007. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  14008. };
  14009. this.startPositionFunction = function (worldMatrix, positionToUpdate) {
  14010. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  14011. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  14012. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  14013. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  14014. };
  14015. this.updateFunction = function (particles) {
  14016. for (var index = 0; index < particles.length; index++) {
  14017. var particle = particles[index];
  14018. particle.age += _this._scaledUpdateSpeed;
  14019. if (particle.age >= particle.lifeTime) {
  14020. particles.splice(index, 1);
  14021. _this._stockParticles.push(particle);
  14022. index--;
  14023. continue;
  14024. } else {
  14025. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  14026. particle.color.addInPlace(_this._scaledColorStep);
  14027. if (particle.color.a < 0)
  14028. particle.color.a = 0;
  14029. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  14030. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  14031. particle.position.addInPlace(_this._scaledDirection);
  14032. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  14033. particle.direction.addInPlace(_this._scaledGravity);
  14034. }
  14035. }
  14036. };
  14037. }
  14038. ParticleSystem.prototype.getCapacity = function () {
  14039. return this._capacity;
  14040. };
  14041. ParticleSystem.prototype.isAlive = function () {
  14042. return this._alive;
  14043. };
  14044. ParticleSystem.prototype.isStarted = function () {
  14045. return this._started;
  14046. };
  14047. ParticleSystem.prototype.start = function () {
  14048. this._started = true;
  14049. this._stopped = false;
  14050. this._actualFrame = 0;
  14051. };
  14052. ParticleSystem.prototype.stop = function () {
  14053. this._stopped = true;
  14054. };
  14055. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  14056. var offset = index * 11;
  14057. this._vertices[offset] = particle.position.x;
  14058. this._vertices[offset + 1] = particle.position.y;
  14059. this._vertices[offset + 2] = particle.position.z;
  14060. this._vertices[offset + 3] = particle.color.r;
  14061. this._vertices[offset + 4] = particle.color.g;
  14062. this._vertices[offset + 5] = particle.color.b;
  14063. this._vertices[offset + 6] = particle.color.a;
  14064. this._vertices[offset + 7] = particle.angle;
  14065. this._vertices[offset + 8] = particle.size;
  14066. this._vertices[offset + 9] = offsetX;
  14067. this._vertices[offset + 10] = offsetY;
  14068. };
  14069. ParticleSystem.prototype._update = function (newParticles) {
  14070. // Update current
  14071. this._alive = this.particles.length > 0;
  14072. this.updateFunction(this.particles);
  14073. // Add new ones
  14074. var worldMatrix;
  14075. if (this.emitter.position) {
  14076. worldMatrix = this.emitter.getWorldMatrix();
  14077. } else {
  14078. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  14079. }
  14080. for (var index = 0; index < newParticles; index++) {
  14081. if (this.particles.length === this._capacity) {
  14082. break;
  14083. }
  14084. if (this._stockParticles.length !== 0) {
  14085. var particle = this._stockParticles.pop();
  14086. particle.age = 0;
  14087. } else {
  14088. particle = new BABYLON.Particle();
  14089. }
  14090. this.particles.push(particle);
  14091. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  14092. this.startDirectionFunction(emitPower, worldMatrix, particle.direction);
  14093. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  14094. particle.size = randomNumber(this.minSize, this.maxSize);
  14095. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  14096. this.startPositionFunction(worldMatrix, particle.position);
  14097. var step = randomNumber(0, 1.0);
  14098. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  14099. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  14100. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  14101. }
  14102. };
  14103. ParticleSystem.prototype._getEffect = function () {
  14104. if (this._customEffect) {
  14105. return this._customEffect;
  14106. }
  14107. ;
  14108. var defines = [];
  14109. if (this._scene.clipPlane) {
  14110. defines.push("#define CLIPPLANE");
  14111. }
  14112. // Effect
  14113. var join = defines.join("\n");
  14114. if (this._cachedDefines !== join) {
  14115. this._cachedDefines = join;
  14116. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  14117. }
  14118. return this._effect;
  14119. };
  14120. ParticleSystem.prototype.animate = function () {
  14121. if (!this._started)
  14122. return;
  14123. var effect = this._getEffect();
  14124. // Check
  14125. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  14126. return;
  14127. if (this._currentRenderId === this._scene.getRenderId()) {
  14128. return;
  14129. }
  14130. this._currentRenderId = this._scene.getRenderId();
  14131. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  14132. // determine the number of particles we need to create
  14133. var emitCout;
  14134. if (this.manualEmitCount > -1) {
  14135. emitCout = this.manualEmitCount;
  14136. this.manualEmitCount = 0;
  14137. } else {
  14138. emitCout = this.emitRate;
  14139. }
  14140. var newParticles = ((emitCout * this._scaledUpdateSpeed) >> 0);
  14141. this._newPartsExcess += emitCout * this._scaledUpdateSpeed - newParticles;
  14142. if (this._newPartsExcess > 1.0) {
  14143. newParticles += this._newPartsExcess >> 0;
  14144. this._newPartsExcess -= this._newPartsExcess >> 0;
  14145. }
  14146. this._alive = false;
  14147. if (!this._stopped) {
  14148. this._actualFrame += this._scaledUpdateSpeed;
  14149. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  14150. this.stop();
  14151. } else {
  14152. newParticles = 0;
  14153. }
  14154. this._update(newParticles);
  14155. // Stopped?
  14156. if (this._stopped) {
  14157. if (!this._alive) {
  14158. this._started = false;
  14159. if (this.disposeOnStop) {
  14160. this._scene._toBeDisposed.push(this);
  14161. }
  14162. }
  14163. }
  14164. // Update VBO
  14165. var offset = 0;
  14166. for (var index = 0; index < this.particles.length; index++) {
  14167. var particle = this.particles[index];
  14168. this._appendParticleVertex(offset++, particle, 0, 0);
  14169. this._appendParticleVertex(offset++, particle, 1, 0);
  14170. this._appendParticleVertex(offset++, particle, 1, 1);
  14171. this._appendParticleVertex(offset++, particle, 0, 1);
  14172. }
  14173. var engine = this._scene.getEngine();
  14174. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  14175. };
  14176. ParticleSystem.prototype.render = function () {
  14177. var effect = this._getEffect();
  14178. // Check
  14179. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  14180. return 0;
  14181. var engine = this._scene.getEngine();
  14182. // Render
  14183. engine.enableEffect(effect);
  14184. engine.setState(false);
  14185. var viewMatrix = this._scene.getViewMatrix();
  14186. effect.setTexture("diffuseSampler", this.particleTexture);
  14187. effect.setMatrix("view", viewMatrix);
  14188. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  14189. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  14190. if (this._scene.clipPlane) {
  14191. var clipPlane = this._scene.clipPlane;
  14192. var invView = viewMatrix.clone();
  14193. invView.invert();
  14194. effect.setMatrix("invView", invView);
  14195. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  14196. }
  14197. // VBOs
  14198. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  14199. // Draw order
  14200. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  14201. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  14202. } else {
  14203. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  14204. }
  14205. if (this.forceDepthWrite) {
  14206. engine.setDepthWrite(true);
  14207. }
  14208. engine.draw(true, 0, this.particles.length * 6);
  14209. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  14210. return this.particles.length;
  14211. };
  14212. ParticleSystem.prototype.dispose = function () {
  14213. if (this._vertexBuffer) {
  14214. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  14215. this._vertexBuffer = null;
  14216. }
  14217. if (this._indexBuffer) {
  14218. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  14219. this._indexBuffer = null;
  14220. }
  14221. if (this.particleTexture) {
  14222. this.particleTexture.dispose();
  14223. this.particleTexture = null;
  14224. }
  14225. // Remove from scene
  14226. var index = this._scene.particleSystems.indexOf(this);
  14227. this._scene.particleSystems.splice(index, 1);
  14228. // Callback
  14229. if (this.onDispose) {
  14230. this.onDispose();
  14231. }
  14232. };
  14233. // Clone
  14234. ParticleSystem.prototype.clone = function (name, newEmitter) {
  14235. var result = new ParticleSystem(name, this._capacity, this._scene);
  14236. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  14237. if (newEmitter === undefined) {
  14238. newEmitter = this.emitter;
  14239. }
  14240. result.emitter = newEmitter;
  14241. if (this.particleTexture) {
  14242. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  14243. }
  14244. result.start();
  14245. return result;
  14246. };
  14247. ParticleSystem.BLENDMODE_ONEONE = 0;
  14248. ParticleSystem.BLENDMODE_STANDARD = 1;
  14249. return ParticleSystem;
  14250. })();
  14251. BABYLON.ParticleSystem = ParticleSystem;
  14252. })(BABYLON || (BABYLON = {}));
  14253. //# sourceMappingURL=babylon.particleSystem.js.map
  14254. var BABYLON;
  14255. (function (BABYLON) {
  14256. var Animation = (function () {
  14257. function Animation(name, targetProperty, framePerSecond, dataType, loopMode) {
  14258. this.name = name;
  14259. this.targetProperty = targetProperty;
  14260. this.framePerSecond = framePerSecond;
  14261. this.dataType = dataType;
  14262. this.loopMode = loopMode;
  14263. this._offsetsCache = {};
  14264. this._highLimitsCache = {};
  14265. this._stopped = false;
  14266. this.targetPropertyPath = targetProperty.split(".");
  14267. this.dataType = dataType;
  14268. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  14269. }
  14270. Animation.CreateAndStartAnimation = function (name, mesh, tartgetProperty, framePerSecond, totalFrame, from, to, loopMode) {
  14271. var dataType = undefined;
  14272. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  14273. dataType = Animation.ANIMATIONTYPE_FLOAT;
  14274. } else if (from instanceof BABYLON.Quaternion) {
  14275. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  14276. } else if (from instanceof BABYLON.Vector3) {
  14277. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  14278. } else if (from instanceof BABYLON.Vector2) {
  14279. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  14280. } else if (from instanceof BABYLON.Color3) {
  14281. dataType = Animation.ANIMATIONTYPE_COLOR3;
  14282. }
  14283. if (dataType == undefined) {
  14284. return;
  14285. }
  14286. var animation = new Animation(name, tartgetProperty, framePerSecond, dataType, loopMode);
  14287. var keys = [];
  14288. keys.push({ frame: 0, value: from });
  14289. keys.push({ frame: totalFrame, value: to });
  14290. animation.setKeys(keys);
  14291. mesh.animations.push(animation);
  14292. mesh.getScene().beginAnimation(mesh, 0, totalFrame, (animation.loopMode === 1));
  14293. };
  14294. // Methods
  14295. Animation.prototype.isStopped = function () {
  14296. return this._stopped;
  14297. };
  14298. Animation.prototype.getKeys = function () {
  14299. return this._keys;
  14300. };
  14301. Animation.prototype.getEasingFunction = function () {
  14302. return this._easingFunction;
  14303. };
  14304. Animation.prototype.setEasingFunction = function (easingFunction) {
  14305. this._easingFunction = easingFunction;
  14306. };
  14307. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  14308. return startValue + (endValue - startValue) * gradient;
  14309. };
  14310. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  14311. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  14312. };
  14313. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  14314. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  14315. };
  14316. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  14317. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  14318. };
  14319. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  14320. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  14321. };
  14322. Animation.prototype.clone = function () {
  14323. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  14324. clone.setKeys(this._keys);
  14325. return clone;
  14326. };
  14327. Animation.prototype.setKeys = function (values) {
  14328. this._keys = values.slice(0);
  14329. this._offsetsCache = {};
  14330. this._highLimitsCache = {};
  14331. };
  14332. Animation.prototype._getKeyValue = function (value) {
  14333. if (typeof value === "function") {
  14334. return value();
  14335. }
  14336. return value;
  14337. };
  14338. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  14339. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  14340. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  14341. }
  14342. this.currentFrame = currentFrame;
  14343. for (var key = 0; key < this._keys.length; key++) {
  14344. // for each frame, we need the key just before the frame superior
  14345. if (this._keys[key + 1].frame >= currentFrame) {
  14346. var startValue = this._getKeyValue(this._keys[key].value);
  14347. var endValue = this._getKeyValue(this._keys[key + 1].value);
  14348. // gradient : percent of currentFrame between the frame inf and the frame sup
  14349. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  14350. // check for easingFunction and correction of gradient
  14351. if (this._easingFunction != null) {
  14352. gradient = this._easingFunction.ease(gradient);
  14353. }
  14354. switch (this.dataType) {
  14355. case Animation.ANIMATIONTYPE_FLOAT:
  14356. switch (loopMode) {
  14357. case Animation.ANIMATIONLOOPMODE_CYCLE:
  14358. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  14359. return this.floatInterpolateFunction(startValue, endValue, gradient);
  14360. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  14361. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  14362. }
  14363. break;
  14364. case Animation.ANIMATIONTYPE_QUATERNION:
  14365. var quaternion = null;
  14366. switch (loopMode) {
  14367. case Animation.ANIMATIONLOOPMODE_CYCLE:
  14368. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  14369. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  14370. break;
  14371. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  14372. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  14373. break;
  14374. }
  14375. return quaternion;
  14376. case Animation.ANIMATIONTYPE_VECTOR3:
  14377. switch (loopMode) {
  14378. case Animation.ANIMATIONLOOPMODE_CYCLE:
  14379. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  14380. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  14381. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  14382. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  14383. }
  14384. case Animation.ANIMATIONTYPE_VECTOR2:
  14385. switch (loopMode) {
  14386. case Animation.ANIMATIONLOOPMODE_CYCLE:
  14387. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  14388. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  14389. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  14390. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  14391. }
  14392. case Animation.ANIMATIONTYPE_COLOR3:
  14393. switch (loopMode) {
  14394. case Animation.ANIMATIONLOOPMODE_CYCLE:
  14395. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  14396. return this.color3InterpolateFunction(startValue, endValue, gradient);
  14397. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  14398. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  14399. }
  14400. case Animation.ANIMATIONTYPE_MATRIX:
  14401. switch (loopMode) {
  14402. case Animation.ANIMATIONLOOPMODE_CYCLE:
  14403. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  14404. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  14405. return startValue;
  14406. }
  14407. default:
  14408. break;
  14409. }
  14410. break;
  14411. }
  14412. }
  14413. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  14414. };
  14415. Animation.prototype.animate = function (delay, from, to, loop, speedRatio) {
  14416. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  14417. this._stopped = true;
  14418. return false;
  14419. }
  14420. var returnValue = true;
  14421. // Adding a start key at frame 0 if missing
  14422. if (this._keys[0].frame !== 0) {
  14423. var newKey = { frame: 0, value: this._keys[0].value };
  14424. this._keys.splice(0, 0, newKey);
  14425. }
  14426. // Check limits
  14427. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  14428. from = this._keys[0].frame;
  14429. }
  14430. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  14431. to = this._keys[this._keys.length - 1].frame;
  14432. }
  14433. // Compute ratio
  14434. var range = to - from;
  14435. var offsetValue;
  14436. // ratio represents the frame delta between from and to
  14437. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  14438. var highLimitValue = 0;
  14439. if (ratio > range && !loop) {
  14440. returnValue = false;
  14441. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  14442. } else {
  14443. // Get max value if required
  14444. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  14445. var keyOffset = to.toString() + from.toString();
  14446. if (!this._offsetsCache[keyOffset]) {
  14447. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  14448. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  14449. switch (this.dataType) {
  14450. case Animation.ANIMATIONTYPE_FLOAT:
  14451. this._offsetsCache[keyOffset] = toValue - fromValue;
  14452. break;
  14453. case Animation.ANIMATIONTYPE_QUATERNION:
  14454. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  14455. break;
  14456. case Animation.ANIMATIONTYPE_VECTOR3:
  14457. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  14458. case Animation.ANIMATIONTYPE_VECTOR2:
  14459. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  14460. case Animation.ANIMATIONTYPE_COLOR3:
  14461. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  14462. default:
  14463. break;
  14464. }
  14465. this._highLimitsCache[keyOffset] = toValue;
  14466. }
  14467. highLimitValue = this._highLimitsCache[keyOffset];
  14468. offsetValue = this._offsetsCache[keyOffset];
  14469. }
  14470. }
  14471. if (offsetValue === undefined) {
  14472. switch (this.dataType) {
  14473. case Animation.ANIMATIONTYPE_FLOAT:
  14474. offsetValue = 0;
  14475. break;
  14476. case Animation.ANIMATIONTYPE_QUATERNION:
  14477. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  14478. break;
  14479. case Animation.ANIMATIONTYPE_VECTOR3:
  14480. offsetValue = BABYLON.Vector3.Zero();
  14481. break;
  14482. case Animation.ANIMATIONTYPE_VECTOR2:
  14483. offsetValue = BABYLON.Vector2.Zero();
  14484. break;
  14485. case Animation.ANIMATIONTYPE_COLOR3:
  14486. offsetValue = BABYLON.Color3.Black();
  14487. }
  14488. }
  14489. // Compute value
  14490. var repeatCount = (ratio / range) >> 0;
  14491. var currentFrame = returnValue ? from + ratio % range : to;
  14492. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  14493. // Set value
  14494. if (this.targetPropertyPath.length > 1) {
  14495. var property = this._target[this.targetPropertyPath[0]];
  14496. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  14497. property = property[this.targetPropertyPath[index]];
  14498. }
  14499. property[this.targetPropertyPath[this.targetPropertyPath.length - 1]] = currentValue;
  14500. } else {
  14501. this._target[this.targetPropertyPath[0]] = currentValue;
  14502. }
  14503. if (this._target.markAsDirty) {
  14504. this._target.markAsDirty(this.targetProperty);
  14505. }
  14506. if (!returnValue) {
  14507. this._stopped = true;
  14508. }
  14509. return returnValue;
  14510. };
  14511. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  14512. get: function () {
  14513. return Animation._ANIMATIONTYPE_FLOAT;
  14514. },
  14515. enumerable: true,
  14516. configurable: true
  14517. });
  14518. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  14519. get: function () {
  14520. return Animation._ANIMATIONTYPE_VECTOR3;
  14521. },
  14522. enumerable: true,
  14523. configurable: true
  14524. });
  14525. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  14526. get: function () {
  14527. return Animation._ANIMATIONTYPE_VECTOR2;
  14528. },
  14529. enumerable: true,
  14530. configurable: true
  14531. });
  14532. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  14533. get: function () {
  14534. return Animation._ANIMATIONTYPE_QUATERNION;
  14535. },
  14536. enumerable: true,
  14537. configurable: true
  14538. });
  14539. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  14540. get: function () {
  14541. return Animation._ANIMATIONTYPE_MATRIX;
  14542. },
  14543. enumerable: true,
  14544. configurable: true
  14545. });
  14546. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  14547. get: function () {
  14548. return Animation._ANIMATIONTYPE_COLOR3;
  14549. },
  14550. enumerable: true,
  14551. configurable: true
  14552. });
  14553. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  14554. get: function () {
  14555. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  14556. },
  14557. enumerable: true,
  14558. configurable: true
  14559. });
  14560. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  14561. get: function () {
  14562. return Animation._ANIMATIONLOOPMODE_CYCLE;
  14563. },
  14564. enumerable: true,
  14565. configurable: true
  14566. });
  14567. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  14568. get: function () {
  14569. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  14570. },
  14571. enumerable: true,
  14572. configurable: true
  14573. });
  14574. Animation._ANIMATIONTYPE_FLOAT = 0;
  14575. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  14576. Animation._ANIMATIONTYPE_QUATERNION = 2;
  14577. Animation._ANIMATIONTYPE_MATRIX = 3;
  14578. Animation._ANIMATIONTYPE_COLOR3 = 4;
  14579. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  14580. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  14581. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  14582. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  14583. return Animation;
  14584. })();
  14585. BABYLON.Animation = Animation;
  14586. })(BABYLON || (BABYLON = {}));
  14587. //# sourceMappingURL=babylon.animation.js.map
  14588. var BABYLON;
  14589. (function (BABYLON) {
  14590. var Animatable = (function () {
  14591. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  14592. if (typeof fromFrame === "undefined") { fromFrame = 0; }
  14593. if (typeof toFrame === "undefined") { toFrame = 100; }
  14594. if (typeof loopAnimation === "undefined") { loopAnimation = false; }
  14595. if (typeof speedRatio === "undefined") { speedRatio = 1.0; }
  14596. this.target = target;
  14597. this.fromFrame = fromFrame;
  14598. this.toFrame = toFrame;
  14599. this.loopAnimation = loopAnimation;
  14600. this.speedRatio = speedRatio;
  14601. this.onAnimationEnd = onAnimationEnd;
  14602. this._animations = new Array();
  14603. this._paused = false;
  14604. this.animationStarted = false;
  14605. if (animations) {
  14606. this.appendAnimations(target, animations);
  14607. }
  14608. this._scene = scene;
  14609. scene._activeAnimatables.push(this);
  14610. }
  14611. // Methods
  14612. Animatable.prototype.appendAnimations = function (target, animations) {
  14613. for (var index = 0; index < animations.length; index++) {
  14614. var animation = animations[index];
  14615. animation._target = target;
  14616. this._animations.push(animation);
  14617. }
  14618. };
  14619. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  14620. var animations = this._animations;
  14621. for (var index = 0; index < animations.length; index++) {
  14622. if (animations[index].targetProperty === property) {
  14623. return animations[index];
  14624. }
  14625. }
  14626. return null;
  14627. };
  14628. Animatable.prototype.pause = function () {
  14629. if (this._paused) {
  14630. return;
  14631. }
  14632. this._paused = true;
  14633. };
  14634. Animatable.prototype.restart = function () {
  14635. this._paused = false;
  14636. };
  14637. Animatable.prototype.stop = function () {
  14638. var index = this._scene._activeAnimatables.indexOf(this);
  14639. if (index > -1) {
  14640. this._scene._activeAnimatables.splice(index, 1);
  14641. }
  14642. if (this.onAnimationEnd) {
  14643. this.onAnimationEnd();
  14644. }
  14645. };
  14646. Animatable.prototype._animate = function (delay) {
  14647. if (this._paused) {
  14648. if (!this._pausedDelay) {
  14649. this._pausedDelay = delay;
  14650. }
  14651. return true;
  14652. }
  14653. if (!this._localDelayOffset) {
  14654. this._localDelayOffset = delay;
  14655. } else if (this._pausedDelay) {
  14656. this._localDelayOffset += delay - this._pausedDelay;
  14657. this._pausedDelay = null;
  14658. }
  14659. // Animating
  14660. var running = false;
  14661. var animations = this._animations;
  14662. for (var index = 0; index < animations.length; index++) {
  14663. var animation = animations[index];
  14664. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  14665. running = running || isRunning;
  14666. }
  14667. if (!running && this.onAnimationEnd) {
  14668. this.onAnimationEnd();
  14669. }
  14670. return running;
  14671. };
  14672. return Animatable;
  14673. })();
  14674. BABYLON.Animatable = Animatable;
  14675. })(BABYLON || (BABYLON = {}));
  14676. //# sourceMappingURL=babylon.animatable.js.map
  14677. var BABYLON;
  14678. (function (BABYLON) {
  14679. var EasingFunction = (function () {
  14680. function EasingFunction() {
  14681. // Properties
  14682. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  14683. }
  14684. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  14685. get: function () {
  14686. return EasingFunction._EASINGMODE_EASEIN;
  14687. },
  14688. enumerable: true,
  14689. configurable: true
  14690. });
  14691. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  14692. get: function () {
  14693. return EasingFunction._EASINGMODE_EASEOUT;
  14694. },
  14695. enumerable: true,
  14696. configurable: true
  14697. });
  14698. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  14699. get: function () {
  14700. return EasingFunction._EASINGMODE_EASEINOUT;
  14701. },
  14702. enumerable: true,
  14703. configurable: true
  14704. });
  14705. EasingFunction.prototype.setEasingMode = function (easingMode) {
  14706. var n = Math.min(Math.max(easingMode, 0), 2);
  14707. this._easingMode = n;
  14708. };
  14709. EasingFunction.prototype.getEasingMode = function () {
  14710. return this._easingMode;
  14711. };
  14712. EasingFunction.prototype.easeInCore = function (gradient) {
  14713. throw new Error('You must implement this method');
  14714. };
  14715. EasingFunction.prototype.ease = function (gradient) {
  14716. switch (this._easingMode) {
  14717. case EasingFunction.EASINGMODE_EASEIN:
  14718. return this.easeInCore(gradient);
  14719. case EasingFunction.EASINGMODE_EASEOUT:
  14720. return (1 - this.easeInCore(1 - gradient));
  14721. }
  14722. if (gradient >= 0.5) {
  14723. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  14724. }
  14725. return (this.easeInCore(gradient * 2) * 0.5);
  14726. };
  14727. EasingFunction._EASINGMODE_EASEIN = 0;
  14728. EasingFunction._EASINGMODE_EASEOUT = 1;
  14729. EasingFunction._EASINGMODE_EASEINOUT = 2;
  14730. return EasingFunction;
  14731. })();
  14732. BABYLON.EasingFunction = EasingFunction;
  14733. var CircleEase = (function (_super) {
  14734. __extends(CircleEase, _super);
  14735. function CircleEase() {
  14736. _super.apply(this, arguments);
  14737. }
  14738. CircleEase.prototype.easeInCore = function (gradient) {
  14739. gradient = Math.max(0, Math.min(1, gradient));
  14740. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  14741. };
  14742. return CircleEase;
  14743. })(EasingFunction);
  14744. BABYLON.CircleEase = CircleEase;
  14745. var BackEase = (function (_super) {
  14746. __extends(BackEase, _super);
  14747. function BackEase(amplitude) {
  14748. if (typeof amplitude === "undefined") { amplitude = 1; }
  14749. _super.call(this);
  14750. this.amplitude = amplitude;
  14751. }
  14752. BackEase.prototype.easeInCore = function (gradient) {
  14753. var num = Math.max(0, this.amplitude);
  14754. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  14755. };
  14756. return BackEase;
  14757. })(EasingFunction);
  14758. BABYLON.BackEase = BackEase;
  14759. var BounceEase = (function (_super) {
  14760. __extends(BounceEase, _super);
  14761. function BounceEase(bounces, bounciness) {
  14762. if (typeof bounces === "undefined") { bounces = 3; }
  14763. if (typeof bounciness === "undefined") { bounciness = 2; }
  14764. _super.call(this);
  14765. this.bounces = bounces;
  14766. this.bounciness = bounciness;
  14767. }
  14768. BounceEase.prototype.easeInCore = function (gradient) {
  14769. var y = Math.max(0.0, this.bounces);
  14770. var bounciness = this.bounciness;
  14771. if (bounciness <= 1.0) {
  14772. bounciness = 1.001;
  14773. }
  14774. var num9 = Math.pow(bounciness, y);
  14775. var num5 = 1.0 - bounciness;
  14776. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  14777. var num15 = gradient * num4;
  14778. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  14779. var num3 = Math.floor(num65);
  14780. var num13 = num3 + 1.0;
  14781. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  14782. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  14783. var num7 = (num8 + num12) * 0.5;
  14784. var num6 = gradient - num7;
  14785. var num2 = num7 - num8;
  14786. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  14787. };
  14788. return BounceEase;
  14789. })(EasingFunction);
  14790. BABYLON.BounceEase = BounceEase;
  14791. var CubicEase = (function (_super) {
  14792. __extends(CubicEase, _super);
  14793. function CubicEase() {
  14794. _super.apply(this, arguments);
  14795. }
  14796. CubicEase.prototype.easeInCore = function (gradient) {
  14797. return (gradient * gradient * gradient);
  14798. };
  14799. return CubicEase;
  14800. })(EasingFunction);
  14801. BABYLON.CubicEase = CubicEase;
  14802. var ElasticEase = (function (_super) {
  14803. __extends(ElasticEase, _super);
  14804. function ElasticEase(oscillations, springiness) {
  14805. if (typeof oscillations === "undefined") { oscillations = 3; }
  14806. if (typeof springiness === "undefined") { springiness = 3; }
  14807. _super.call(this);
  14808. this.oscillations = oscillations;
  14809. this.springiness = springiness;
  14810. }
  14811. ElasticEase.prototype.easeInCore = function (gradient) {
  14812. var num2;
  14813. var num3 = Math.max(0.0, this.oscillations);
  14814. var num = Math.max(0.0, this.springiness);
  14815. if (num == 0) {
  14816. num2 = gradient;
  14817. } else {
  14818. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  14819. }
  14820. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  14821. };
  14822. return ElasticEase;
  14823. })(EasingFunction);
  14824. BABYLON.ElasticEase = ElasticEase;
  14825. var ExponentialEase = (function (_super) {
  14826. __extends(ExponentialEase, _super);
  14827. function ExponentialEase(exponent) {
  14828. if (typeof exponent === "undefined") { exponent = 2; }
  14829. _super.call(this);
  14830. this.exponent = exponent;
  14831. }
  14832. ExponentialEase.prototype.easeInCore = function (gradient) {
  14833. if (this.exponent <= 0) {
  14834. return gradient;
  14835. }
  14836. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  14837. };
  14838. return ExponentialEase;
  14839. })(EasingFunction);
  14840. BABYLON.ExponentialEase = ExponentialEase;
  14841. var PowerEase = (function (_super) {
  14842. __extends(PowerEase, _super);
  14843. function PowerEase(power) {
  14844. if (typeof power === "undefined") { power = 2; }
  14845. _super.call(this);
  14846. this.power = power;
  14847. }
  14848. PowerEase.prototype.easeInCore = function (gradient) {
  14849. var y = Math.max(0.0, this.power);
  14850. return Math.pow(gradient, y);
  14851. };
  14852. return PowerEase;
  14853. })(EasingFunction);
  14854. BABYLON.PowerEase = PowerEase;
  14855. var QuadraticEase = (function (_super) {
  14856. __extends(QuadraticEase, _super);
  14857. function QuadraticEase() {
  14858. _super.apply(this, arguments);
  14859. }
  14860. QuadraticEase.prototype.easeInCore = function (gradient) {
  14861. return (gradient * gradient);
  14862. };
  14863. return QuadraticEase;
  14864. })(EasingFunction);
  14865. BABYLON.QuadraticEase = QuadraticEase;
  14866. var QuarticEase = (function (_super) {
  14867. __extends(QuarticEase, _super);
  14868. function QuarticEase() {
  14869. _super.apply(this, arguments);
  14870. }
  14871. QuarticEase.prototype.easeInCore = function (gradient) {
  14872. return (gradient * gradient * gradient * gradient);
  14873. };
  14874. return QuarticEase;
  14875. })(EasingFunction);
  14876. BABYLON.QuarticEase = QuarticEase;
  14877. var QuinticEase = (function (_super) {
  14878. __extends(QuinticEase, _super);
  14879. function QuinticEase() {
  14880. _super.apply(this, arguments);
  14881. }
  14882. QuinticEase.prototype.easeInCore = function (gradient) {
  14883. return (gradient * gradient * gradient * gradient * gradient);
  14884. };
  14885. return QuinticEase;
  14886. })(EasingFunction);
  14887. BABYLON.QuinticEase = QuinticEase;
  14888. var SineEase = (function (_super) {
  14889. __extends(SineEase, _super);
  14890. function SineEase() {
  14891. _super.apply(this, arguments);
  14892. }
  14893. SineEase.prototype.easeInCore = function (gradient) {
  14894. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  14895. };
  14896. return SineEase;
  14897. })(EasingFunction);
  14898. BABYLON.SineEase = SineEase;
  14899. var BezierCurveEase = (function (_super) {
  14900. __extends(BezierCurveEase, _super);
  14901. function BezierCurveEase(x1, y1, x2, y2) {
  14902. if (typeof x1 === "undefined") { x1 = 0; }
  14903. if (typeof y1 === "undefined") { y1 = 0; }
  14904. if (typeof x2 === "undefined") { x2 = 1; }
  14905. if (typeof y2 === "undefined") { y2 = 1; }
  14906. _super.call(this);
  14907. this.x1 = x1;
  14908. this.y1 = y1;
  14909. this.x2 = x2;
  14910. this.y2 = y2;
  14911. }
  14912. BezierCurveEase.prototype.easeInCore = function (gradient) {
  14913. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  14914. };
  14915. return BezierCurveEase;
  14916. })(EasingFunction);
  14917. BABYLON.BezierCurveEase = BezierCurveEase;
  14918. })(BABYLON || (BABYLON = {}));
  14919. //# sourceMappingURL=babylon.easing.js.map
  14920. var BABYLON;
  14921. (function (BABYLON) {
  14922. var Octree = (function () {
  14923. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  14924. if (typeof maxDepth === "undefined") { maxDepth = 2; }
  14925. this.maxDepth = maxDepth;
  14926. this.dynamicContent = new Array();
  14927. this._maxBlockCapacity = maxBlockCapacity || 64;
  14928. this._selectionContent = new BABYLON.SmartArray(1024);
  14929. this._creationFunc = creationFunc;
  14930. }
  14931. // Methods
  14932. Octree.prototype.update = function (worldMin, worldMax, entries) {
  14933. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  14934. };
  14935. Octree.prototype.addMesh = function (entry) {
  14936. for (var index = 0; index < this.blocks.length; index++) {
  14937. var block = this.blocks[index];
  14938. block.addEntry(entry);
  14939. }
  14940. };
  14941. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  14942. this._selectionContent.reset();
  14943. for (var index = 0; index < this.blocks.length; index++) {
  14944. var block = this.blocks[index];
  14945. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  14946. }
  14947. if (allowDuplicate) {
  14948. this._selectionContent.concat(this.dynamicContent);
  14949. } else {
  14950. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  14951. }
  14952. return this._selectionContent;
  14953. };
  14954. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  14955. this._selectionContent.reset();
  14956. for (var index = 0; index < this.blocks.length; index++) {
  14957. var block = this.blocks[index];
  14958. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  14959. }
  14960. if (allowDuplicate) {
  14961. this._selectionContent.concat(this.dynamicContent);
  14962. } else {
  14963. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  14964. }
  14965. return this._selectionContent;
  14966. };
  14967. Octree.prototype.intersectsRay = function (ray) {
  14968. this._selectionContent.reset();
  14969. for (var index = 0; index < this.blocks.length; index++) {
  14970. var block = this.blocks[index];
  14971. block.intersectsRay(ray, this._selectionContent);
  14972. }
  14973. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  14974. return this._selectionContent;
  14975. };
  14976. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  14977. target.blocks = new Array();
  14978. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  14979. for (var x = 0; x < 2; x++) {
  14980. for (var y = 0; y < 2; y++) {
  14981. for (var z = 0; z < 2; z++) {
  14982. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  14983. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  14984. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  14985. block.addEntries(entries);
  14986. target.blocks.push(block);
  14987. }
  14988. }
  14989. }
  14990. };
  14991. Octree.CreationFuncForMeshes = function (entry, block) {
  14992. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  14993. block.entries.push(entry);
  14994. }
  14995. };
  14996. Octree.CreationFuncForSubMeshes = function (entry, block) {
  14997. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  14998. block.entries.push(entry);
  14999. }
  15000. };
  15001. return Octree;
  15002. })();
  15003. BABYLON.Octree = Octree;
  15004. })(BABYLON || (BABYLON = {}));
  15005. //# sourceMappingURL=babylon.octree.js.map
  15006. var BABYLON;
  15007. (function (BABYLON) {
  15008. var OctreeBlock = (function () {
  15009. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  15010. this.entries = new Array();
  15011. this._boundingVectors = new Array();
  15012. this._capacity = capacity;
  15013. this._depth = depth;
  15014. this._maxDepth = maxDepth;
  15015. this._creationFunc = creationFunc;
  15016. this._minPoint = minPoint;
  15017. this._maxPoint = maxPoint;
  15018. this._boundingVectors.push(minPoint.clone());
  15019. this._boundingVectors.push(maxPoint.clone());
  15020. this._boundingVectors.push(minPoint.clone());
  15021. this._boundingVectors[2].x = maxPoint.x;
  15022. this._boundingVectors.push(minPoint.clone());
  15023. this._boundingVectors[3].y = maxPoint.y;
  15024. this._boundingVectors.push(minPoint.clone());
  15025. this._boundingVectors[4].z = maxPoint.z;
  15026. this._boundingVectors.push(maxPoint.clone());
  15027. this._boundingVectors[5].z = minPoint.z;
  15028. this._boundingVectors.push(maxPoint.clone());
  15029. this._boundingVectors[6].x = minPoint.x;
  15030. this._boundingVectors.push(maxPoint.clone());
  15031. this._boundingVectors[7].y = minPoint.y;
  15032. }
  15033. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  15034. // Property
  15035. get: function () {
  15036. return this._capacity;
  15037. },
  15038. enumerable: true,
  15039. configurable: true
  15040. });
  15041. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  15042. get: function () {
  15043. return this._minPoint;
  15044. },
  15045. enumerable: true,
  15046. configurable: true
  15047. });
  15048. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  15049. get: function () {
  15050. return this._maxPoint;
  15051. },
  15052. enumerable: true,
  15053. configurable: true
  15054. });
  15055. // Methods
  15056. OctreeBlock.prototype.addEntry = function (entry) {
  15057. if (this.blocks) {
  15058. for (var index = 0; index < this.blocks.length; index++) {
  15059. var block = this.blocks[index];
  15060. block.addEntry(entry);
  15061. }
  15062. return;
  15063. }
  15064. this._creationFunc(entry, this);
  15065. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  15066. this.createInnerBlocks();
  15067. }
  15068. };
  15069. OctreeBlock.prototype.addEntries = function (entries) {
  15070. for (var index = 0; index < entries.length; index++) {
  15071. var mesh = entries[index];
  15072. this.addEntry(mesh);
  15073. }
  15074. };
  15075. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  15076. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  15077. if (this.blocks) {
  15078. for (var index = 0; index < this.blocks.length; index++) {
  15079. var block = this.blocks[index];
  15080. block.select(frustumPlanes, selection, allowDuplicate);
  15081. }
  15082. return;
  15083. }
  15084. if (allowDuplicate) {
  15085. selection.concat(this.entries);
  15086. } else {
  15087. selection.concatWithNoDuplicate(this.entries);
  15088. }
  15089. }
  15090. };
  15091. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  15092. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  15093. if (this.blocks) {
  15094. for (var index = 0; index < this.blocks.length; index++) {
  15095. var block = this.blocks[index];
  15096. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  15097. }
  15098. return;
  15099. }
  15100. if (allowDuplicate) {
  15101. selection.concat(this.entries);
  15102. } else {
  15103. selection.concatWithNoDuplicate(this.entries);
  15104. }
  15105. }
  15106. };
  15107. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  15108. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  15109. if (this.blocks) {
  15110. for (var index = 0; index < this.blocks.length; index++) {
  15111. var block = this.blocks[index];
  15112. block.intersectsRay(ray, selection);
  15113. }
  15114. return;
  15115. }
  15116. selection.concatWithNoDuplicate(this.entries);
  15117. }
  15118. };
  15119. OctreeBlock.prototype.createInnerBlocks = function () {
  15120. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  15121. };
  15122. return OctreeBlock;
  15123. })();
  15124. BABYLON.OctreeBlock = OctreeBlock;
  15125. })(BABYLON || (BABYLON = {}));
  15126. //# sourceMappingURL=babylon.octreeBlock.js.map
  15127. var BABYLON;
  15128. (function (BABYLON) {
  15129. var Bone = (function () {
  15130. function Bone(name, skeleton, parentBone, matrix) {
  15131. this.name = name;
  15132. this.children = new Array();
  15133. this.animations = new Array();
  15134. this._worldTransform = new BABYLON.Matrix();
  15135. this._absoluteTransform = new BABYLON.Matrix();
  15136. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  15137. this._skeleton = skeleton;
  15138. this._matrix = matrix;
  15139. this._baseMatrix = matrix;
  15140. skeleton.bones.push(this);
  15141. if (parentBone) {
  15142. this._parent = parentBone;
  15143. parentBone.children.push(this);
  15144. } else {
  15145. this._parent = null;
  15146. }
  15147. this._updateDifferenceMatrix();
  15148. }
  15149. // Members
  15150. Bone.prototype.getParent = function () {
  15151. return this._parent;
  15152. };
  15153. Bone.prototype.getLocalMatrix = function () {
  15154. return this._matrix;
  15155. };
  15156. Bone.prototype.getBaseMatrix = function () {
  15157. return this._baseMatrix;
  15158. };
  15159. Bone.prototype.getWorldMatrix = function () {
  15160. return this._worldTransform;
  15161. };
  15162. Bone.prototype.getInvertedAbsoluteTransform = function () {
  15163. return this._invertedAbsoluteTransform;
  15164. };
  15165. Bone.prototype.getAbsoluteMatrix = function () {
  15166. var matrix = this._matrix.clone();
  15167. var parent = this._parent;
  15168. while (parent) {
  15169. matrix = matrix.multiply(parent.getLocalMatrix());
  15170. parent = parent.getParent();
  15171. }
  15172. return matrix;
  15173. };
  15174. // Methods
  15175. Bone.prototype.updateMatrix = function (matrix) {
  15176. this._matrix = matrix;
  15177. this._skeleton._markAsDirty();
  15178. this._updateDifferenceMatrix();
  15179. };
  15180. Bone.prototype._updateDifferenceMatrix = function () {
  15181. if (this._parent) {
  15182. this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  15183. } else {
  15184. this._absoluteTransform.copyFrom(this._matrix);
  15185. }
  15186. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  15187. for (var index = 0; index < this.children.length; index++) {
  15188. this.children[index]._updateDifferenceMatrix();
  15189. }
  15190. };
  15191. Bone.prototype.markAsDirty = function () {
  15192. this._skeleton._markAsDirty();
  15193. };
  15194. return Bone;
  15195. })();
  15196. BABYLON.Bone = Bone;
  15197. })(BABYLON || (BABYLON = {}));
  15198. //# sourceMappingURL=babylon.bone.js.map
  15199. var BABYLON;
  15200. (function (BABYLON) {
  15201. var Skeleton = (function () {
  15202. function Skeleton(name, id, scene) {
  15203. this.name = name;
  15204. this.id = id;
  15205. this.bones = new Array();
  15206. this._isDirty = true;
  15207. this._identity = BABYLON.Matrix.Identity();
  15208. this.bones = [];
  15209. this._scene = scene;
  15210. scene.skeletons.push(this);
  15211. }
  15212. // Members
  15213. Skeleton.prototype.getTransformMatrices = function () {
  15214. return this._transformMatrices;
  15215. };
  15216. // Methods
  15217. Skeleton.prototype._markAsDirty = function () {
  15218. this._isDirty = true;
  15219. };
  15220. Skeleton.prototype.prepare = function () {
  15221. if (!this._isDirty) {
  15222. return;
  15223. }
  15224. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  15225. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  15226. }
  15227. for (var index = 0; index < this.bones.length; index++) {
  15228. var bone = this.bones[index];
  15229. var parentBone = bone.getParent();
  15230. if (parentBone) {
  15231. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  15232. } else {
  15233. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  15234. }
  15235. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), this._transformMatrices, index * 16);
  15236. }
  15237. this._identity.copyToArray(this._transformMatrices, this.bones.length * 16);
  15238. this._isDirty = false;
  15239. };
  15240. Skeleton.prototype.getAnimatables = function () {
  15241. if (!this._animatables || this._animatables.length != this.bones.length) {
  15242. this._animatables = [];
  15243. for (var index = 0; index < this.bones.length; index++) {
  15244. this._animatables.push(this.bones[index]);
  15245. }
  15246. }
  15247. return this._animatables;
  15248. };
  15249. Skeleton.prototype.clone = function (name, id) {
  15250. var result = new BABYLON.Skeleton(name, id || name, this._scene);
  15251. for (var index = 0; index < this.bones.length; index++) {
  15252. var source = this.bones[index];
  15253. var parentBone = null;
  15254. if (source.getParent()) {
  15255. var parentIndex = this.bones.indexOf(source.getParent());
  15256. parentBone = result.bones[parentIndex];
  15257. }
  15258. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix());
  15259. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  15260. }
  15261. return result;
  15262. };
  15263. return Skeleton;
  15264. })();
  15265. BABYLON.Skeleton = Skeleton;
  15266. })(BABYLON || (BABYLON = {}));
  15267. //# sourceMappingURL=babylon.skeleton.js.map
  15268. var BABYLON;
  15269. (function (BABYLON) {
  15270. var PostProcess = (function () {
  15271. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable) {
  15272. this.name = name;
  15273. this.width = -1;
  15274. this.height = -1;
  15275. this._reusable = false;
  15276. this._textures = new BABYLON.SmartArray(2);
  15277. this._currentRenderTextureInd = 0;
  15278. if (camera != null) {
  15279. this._camera = camera;
  15280. this._scene = camera.getScene();
  15281. camera.attachPostProcess(this);
  15282. this._engine = this._scene.getEngine();
  15283. } else {
  15284. this._engine = engine;
  15285. }
  15286. this._renderRatio = ratio;
  15287. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15288. this._reusable = reusable || false;
  15289. samplers = samplers || [];
  15290. samplers.push("textureSampler");
  15291. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: fragmentUrl }, ["position"], parameters || [], samplers, "");
  15292. }
  15293. PostProcess.prototype.isReusable = function () {
  15294. return this._reusable;
  15295. };
  15296. PostProcess.prototype.activate = function (camera, sourceTexture) {
  15297. camera = camera || this._camera;
  15298. var scene = camera.getScene();
  15299. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  15300. var desiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  15301. var desiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  15302. desiredWidth = BABYLON.Tools.GetExponantOfTwo(desiredWidth, maxSize);
  15303. desiredHeight = BABYLON.Tools.GetExponantOfTwo(desiredHeight, maxSize);
  15304. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  15305. if (this._textures.length > 0) {
  15306. for (var i = 0; i < this._textures.length; i++) {
  15307. this._engine._releaseTexture(this._textures.data[i]);
  15308. }
  15309. this._textures.reset();
  15310. }
  15311. this.width = desiredWidth;
  15312. this.height = desiredHeight;
  15313. 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 }));
  15314. if (this._reusable) {
  15315. 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 }));
  15316. }
  15317. if (this.onSizeChanged) {
  15318. this.onSizeChanged();
  15319. }
  15320. }
  15321. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  15322. if (this.onActivate) {
  15323. this.onActivate(camera);
  15324. }
  15325. // Clear
  15326. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  15327. if (this._reusable) {
  15328. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  15329. }
  15330. };
  15331. PostProcess.prototype.apply = function () {
  15332. // Check
  15333. if (!this._effect.isReady())
  15334. return null;
  15335. // States
  15336. this._engine.enableEffect(this._effect);
  15337. this._engine.setState(false);
  15338. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  15339. this._engine.setDepthBuffer(false);
  15340. this._engine.setDepthWrite(false);
  15341. // Texture
  15342. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  15343. // Parameters
  15344. if (this.onApply) {
  15345. this.onApply(this._effect);
  15346. }
  15347. return this._effect;
  15348. };
  15349. PostProcess.prototype.dispose = function (camera) {
  15350. camera = camera || this._camera;
  15351. if (this._textures.length > 0) {
  15352. for (var i = 0; i < this._textures.length; i++) {
  15353. this._engine._releaseTexture(this._textures.data[i]);
  15354. }
  15355. this._textures.reset();
  15356. }
  15357. camera.detachPostProcess(this);
  15358. var index = camera._postProcesses.indexOf(this);
  15359. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  15360. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1; // invalidate frameBuffer to hint the postprocess to create a depth buffer
  15361. }
  15362. };
  15363. return PostProcess;
  15364. })();
  15365. BABYLON.PostProcess = PostProcess;
  15366. })(BABYLON || (BABYLON = {}));
  15367. //# sourceMappingURL=babylon.postProcess.js.map
  15368. var BABYLON;
  15369. (function (BABYLON) {
  15370. var PostProcessManager = (function () {
  15371. function PostProcessManager(scene) {
  15372. this._vertexDeclaration = [2];
  15373. this._vertexStrideSize = 2 * 4;
  15374. this._scene = scene;
  15375. // VBO
  15376. var vertices = [];
  15377. vertices.push(1, 1);
  15378. vertices.push(-1, 1);
  15379. vertices.push(-1, -1);
  15380. vertices.push(1, -1);
  15381. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  15382. // Indices
  15383. var indices = [];
  15384. indices.push(0);
  15385. indices.push(1);
  15386. indices.push(2);
  15387. indices.push(0);
  15388. indices.push(2);
  15389. indices.push(3);
  15390. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  15391. }
  15392. // Methods
  15393. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  15394. var postProcesses = this._scene.activeCamera._postProcesses;
  15395. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  15396. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  15397. return false;
  15398. }
  15399. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  15400. return true;
  15401. };
  15402. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture) {
  15403. var postProcesses = this._scene.activeCamera._postProcesses;
  15404. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  15405. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  15406. return;
  15407. }
  15408. var engine = this._scene.getEngine();
  15409. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  15410. if (index < postProcessesTakenIndices.length - 1) {
  15411. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera);
  15412. } else {
  15413. if (targetTexture) {
  15414. engine.bindFramebuffer(targetTexture);
  15415. } else {
  15416. engine.restoreDefaultFramebuffer();
  15417. }
  15418. }
  15419. if (doNotPresent) {
  15420. break;
  15421. }
  15422. var pp = postProcesses[postProcessesTakenIndices[index]];
  15423. var effect = pp.apply();
  15424. if (effect) {
  15425. if (pp.onBeforeRender) {
  15426. pp.onBeforeRender(effect);
  15427. }
  15428. // VBOs
  15429. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  15430. // Draw order
  15431. engine.draw(true, 0, 6);
  15432. }
  15433. }
  15434. // Restore depth buffer
  15435. engine.setDepthBuffer(true);
  15436. engine.setDepthWrite(true);
  15437. };
  15438. PostProcessManager.prototype.dispose = function () {
  15439. if (this._vertexBuffer) {
  15440. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  15441. this._vertexBuffer = null;
  15442. }
  15443. if (this._indexBuffer) {
  15444. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  15445. this._indexBuffer = null;
  15446. }
  15447. };
  15448. return PostProcessManager;
  15449. })();
  15450. BABYLON.PostProcessManager = PostProcessManager;
  15451. })(BABYLON || (BABYLON = {}));
  15452. //# sourceMappingURL=babylon.postProcessManager.js.map
  15453. var BABYLON;
  15454. (function (BABYLON) {
  15455. var PassPostProcess = (function (_super) {
  15456. __extends(PassPostProcess, _super);
  15457. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  15458. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  15459. }
  15460. return PassPostProcess;
  15461. })(BABYLON.PostProcess);
  15462. BABYLON.PassPostProcess = PassPostProcess;
  15463. })(BABYLON || (BABYLON = {}));
  15464. //# sourceMappingURL=babylon.passPostProcess.js.map
  15465. var BABYLON;
  15466. (function (BABYLON) {
  15467. var BlurPostProcess = (function (_super) {
  15468. __extends(BlurPostProcess, _super);
  15469. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  15470. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  15471. var _this = this;
  15472. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  15473. this.direction = direction;
  15474. this.blurWidth = blurWidth;
  15475. this.onApply = function (effect) {
  15476. effect.setFloat2("screenSize", _this.width, _this.height);
  15477. effect.setVector2("direction", _this.direction);
  15478. effect.setFloat("blurWidth", _this.blurWidth);
  15479. };
  15480. }
  15481. return BlurPostProcess;
  15482. })(BABYLON.PostProcess);
  15483. BABYLON.BlurPostProcess = BlurPostProcess;
  15484. })(BABYLON || (BABYLON = {}));
  15485. //# sourceMappingURL=babylon.blurPostProcess.js.map
  15486. var BABYLON;
  15487. (function (BABYLON) {
  15488. var FilterPostProcess = (function (_super) {
  15489. __extends(FilterPostProcess, _super);
  15490. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  15491. var _this = this;
  15492. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  15493. this.kernelMatrix = kernelMatrix;
  15494. this.onApply = function (effect) {
  15495. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  15496. };
  15497. }
  15498. return FilterPostProcess;
  15499. })(BABYLON.PostProcess);
  15500. BABYLON.FilterPostProcess = FilterPostProcess;
  15501. })(BABYLON || (BABYLON = {}));
  15502. //# sourceMappingURL=babylon.filterPostProcess.js.map
  15503. var BABYLON;
  15504. (function (BABYLON) {
  15505. var RefractionPostProcess = (function (_super) {
  15506. __extends(RefractionPostProcess, _super);
  15507. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  15508. var _this = this;
  15509. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  15510. this.color = color;
  15511. this.depth = depth;
  15512. this.colorLevel = colorLevel;
  15513. this.onActivate = function (cam) {
  15514. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  15515. };
  15516. this.onApply = function (effect) {
  15517. effect.setColor3("baseColor", _this.color);
  15518. effect.setFloat("depth", _this.depth);
  15519. effect.setFloat("colorLevel", _this.colorLevel);
  15520. effect.setTexture("refractionSampler", _this._refRexture);
  15521. };
  15522. }
  15523. // Methods
  15524. RefractionPostProcess.prototype.dispose = function (camera) {
  15525. if (this._refRexture) {
  15526. this._refRexture.dispose();
  15527. }
  15528. _super.prototype.dispose.call(this, camera);
  15529. };
  15530. return RefractionPostProcess;
  15531. })(BABYLON.PostProcess);
  15532. BABYLON.RefractionPostProcess = RefractionPostProcess;
  15533. })(BABYLON || (BABYLON = {}));
  15534. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  15535. var BABYLON;
  15536. (function (BABYLON) {
  15537. var BlackAndWhitePostProcess = (function (_super) {
  15538. __extends(BlackAndWhitePostProcess, _super);
  15539. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  15540. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  15541. }
  15542. return BlackAndWhitePostProcess;
  15543. })(BABYLON.PostProcess);
  15544. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  15545. })(BABYLON || (BABYLON = {}));
  15546. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  15547. var BABYLON;
  15548. (function (BABYLON) {
  15549. var ConvolutionPostProcess = (function (_super) {
  15550. __extends(ConvolutionPostProcess, _super);
  15551. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  15552. var _this = this;
  15553. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  15554. this.kernel = kernel;
  15555. this.onApply = function (effect) {
  15556. effect.setFloat2("screenSize", _this.width, _this.height);
  15557. effect.setArray("kernel", _this.kernel);
  15558. };
  15559. }
  15560. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  15561. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  15562. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  15563. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  15564. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  15565. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  15566. return ConvolutionPostProcess;
  15567. })(BABYLON.PostProcess);
  15568. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  15569. })(BABYLON || (BABYLON = {}));
  15570. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  15571. var BABYLON;
  15572. (function (BABYLON) {
  15573. var FxaaPostProcess = (function (_super) {
  15574. __extends(FxaaPostProcess, _super);
  15575. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  15576. var _this = this;
  15577. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  15578. this.onSizeChanged = function () {
  15579. _this.texelWidth = 1.0 / _this.width;
  15580. _this.texelHeight = 1.0 / _this.height;
  15581. };
  15582. this.onApply = function (effect) {
  15583. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  15584. };
  15585. }
  15586. return FxaaPostProcess;
  15587. })(BABYLON.PostProcess);
  15588. BABYLON.FxaaPostProcess = FxaaPostProcess;
  15589. })(BABYLON || (BABYLON = {}));
  15590. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  15591. var BABYLON;
  15592. (function (BABYLON) {
  15593. var LensFlare = (function () {
  15594. function LensFlare(size, position, color, imgUrl, system) {
  15595. this.size = size;
  15596. this.position = position;
  15597. this.dispose = function () {
  15598. if (this.texture) {
  15599. this.texture.dispose();
  15600. }
  15601. // Remove from scene
  15602. var index = this._system.lensFlares.indexOf(this);
  15603. this._system.lensFlares.splice(index, 1);
  15604. };
  15605. this.color = color || new BABYLON.Color3(1, 1, 1);
  15606. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  15607. this._system = system;
  15608. system.lensFlares.push(this);
  15609. }
  15610. return LensFlare;
  15611. })();
  15612. BABYLON.LensFlare = LensFlare;
  15613. })(BABYLON || (BABYLON = {}));
  15614. //# sourceMappingURL=babylon.lensFlare.js.map
  15615. var BABYLON;
  15616. (function (BABYLON) {
  15617. var LensFlareSystem = (function () {
  15618. function LensFlareSystem(name, emitter, scene) {
  15619. this.name = name;
  15620. this.lensFlares = new Array();
  15621. this.borderLimit = 300;
  15622. this._vertexDeclaration = [2];
  15623. this._vertexStrideSize = 2 * 4;
  15624. this._isEnabled = true;
  15625. this._scene = scene;
  15626. this._emitter = emitter;
  15627. scene.lensFlareSystems.push(this);
  15628. this.meshesSelectionPredicate = function (m) {
  15629. return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0);
  15630. };
  15631. // VBO
  15632. var vertices = [];
  15633. vertices.push(1, 1);
  15634. vertices.push(-1, 1);
  15635. vertices.push(-1, -1);
  15636. vertices.push(1, -1);
  15637. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  15638. // Indices
  15639. var indices = [];
  15640. indices.push(0);
  15641. indices.push(1);
  15642. indices.push(2);
  15643. indices.push(0);
  15644. indices.push(2);
  15645. indices.push(3);
  15646. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  15647. // Effects
  15648. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  15649. }
  15650. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  15651. get: function () {
  15652. return this._isEnabled;
  15653. },
  15654. set: function (value) {
  15655. this._isEnabled = value;
  15656. },
  15657. enumerable: true,
  15658. configurable: true
  15659. });
  15660. LensFlareSystem.prototype.getScene = function () {
  15661. return this._scene;
  15662. };
  15663. LensFlareSystem.prototype.getEmitter = function () {
  15664. return this._emitter;
  15665. };
  15666. LensFlareSystem.prototype.getEmitterPosition = function () {
  15667. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  15668. };
  15669. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  15670. var position = this.getEmitterPosition();
  15671. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  15672. this._positionX = position.x;
  15673. this._positionY = position.y;
  15674. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  15675. if (position.z > 0) {
  15676. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  15677. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  15678. return true;
  15679. }
  15680. }
  15681. return false;
  15682. };
  15683. LensFlareSystem.prototype._isVisible = function () {
  15684. if (!this._isEnabled) {
  15685. return false;
  15686. }
  15687. var emitterPosition = this.getEmitterPosition();
  15688. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  15689. var distance = direction.length();
  15690. direction.normalize();
  15691. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  15692. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  15693. return !pickInfo.hit || pickInfo.distance > distance;
  15694. };
  15695. LensFlareSystem.prototype.render = function () {
  15696. if (!this._effect.isReady())
  15697. return false;
  15698. var engine = this._scene.getEngine();
  15699. var viewport = this._scene.activeCamera.viewport;
  15700. var globalViewport = viewport.toGlobal(engine);
  15701. // Position
  15702. if (!this.computeEffectivePosition(globalViewport)) {
  15703. return false;
  15704. }
  15705. // Visibility
  15706. if (!this._isVisible()) {
  15707. return false;
  15708. }
  15709. // Intensity
  15710. var awayX;
  15711. var awayY;
  15712. if (this._positionX < this.borderLimit + globalViewport.x) {
  15713. awayX = this.borderLimit + globalViewport.x - this._positionX;
  15714. } else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  15715. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  15716. } else {
  15717. awayX = 0;
  15718. }
  15719. if (this._positionY < this.borderLimit + globalViewport.y) {
  15720. awayY = this.borderLimit + globalViewport.y - this._positionY;
  15721. } else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  15722. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  15723. } else {
  15724. awayY = 0;
  15725. }
  15726. var away = (awayX > awayY) ? awayX : awayY;
  15727. if (away > this.borderLimit) {
  15728. away = this.borderLimit;
  15729. }
  15730. var intensity = 1.0 - (away / this.borderLimit);
  15731. if (intensity < 0) {
  15732. return false;
  15733. }
  15734. if (intensity > 1.0) {
  15735. intensity = 1.0;
  15736. }
  15737. // Position
  15738. var centerX = globalViewport.x + globalViewport.width / 2;
  15739. var centerY = globalViewport.y + globalViewport.height / 2;
  15740. var distX = centerX - this._positionX;
  15741. var distY = centerY - this._positionY;
  15742. // Effects
  15743. engine.enableEffect(this._effect);
  15744. engine.setState(false);
  15745. engine.setDepthBuffer(false);
  15746. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  15747. // VBOs
  15748. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  15749. for (var index = 0; index < this.lensFlares.length; index++) {
  15750. var flare = this.lensFlares[index];
  15751. var x = centerX - (distX * flare.position);
  15752. var y = centerY - (distY * flare.position);
  15753. var cw = flare.size;
  15754. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera);
  15755. var cx = 2 * (x / globalViewport.width) - 1.0;
  15756. var cy = 1.0 - 2 * (y / globalViewport.height);
  15757. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  15758. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  15759. // Texture
  15760. this._effect.setTexture("textureSampler", flare.texture);
  15761. // Color
  15762. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  15763. // Draw order
  15764. engine.draw(true, 0, 6);
  15765. }
  15766. engine.setDepthBuffer(true);
  15767. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  15768. return true;
  15769. };
  15770. LensFlareSystem.prototype.dispose = function () {
  15771. if (this._vertexBuffer) {
  15772. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  15773. this._vertexBuffer = null;
  15774. }
  15775. if (this._indexBuffer) {
  15776. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  15777. this._indexBuffer = null;
  15778. }
  15779. while (this.lensFlares.length) {
  15780. this.lensFlares[0].dispose();
  15781. }
  15782. // Remove from scene
  15783. var index = this._scene.lensFlareSystems.indexOf(this);
  15784. this._scene.lensFlareSystems.splice(index, 1);
  15785. };
  15786. return LensFlareSystem;
  15787. })();
  15788. BABYLON.LensFlareSystem = LensFlareSystem;
  15789. })(BABYLON || (BABYLON = {}));
  15790. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  15791. var BABYLON;
  15792. (function (BABYLON) {
  15793. var IntersectionInfo = (function () {
  15794. function IntersectionInfo(bu, bv, distance) {
  15795. this.bu = bu;
  15796. this.bv = bv;
  15797. this.distance = distance;
  15798. this.faceId = 0;
  15799. }
  15800. return IntersectionInfo;
  15801. })();
  15802. BABYLON.IntersectionInfo = IntersectionInfo;
  15803. var PickingInfo = (function () {
  15804. function PickingInfo() {
  15805. this.hit = false;
  15806. this.distance = 0;
  15807. this.pickedPoint = null;
  15808. this.pickedMesh = null;
  15809. this.bu = 0;
  15810. this.bv = 0;
  15811. this.faceId = -1;
  15812. }
  15813. // Methods
  15814. PickingInfo.prototype.getNormal = function () {
  15815. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  15816. return null;
  15817. }
  15818. var indices = this.pickedMesh.getIndices();
  15819. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15820. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  15821. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  15822. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  15823. normal0 = normal0.scale(this.bu);
  15824. normal1 = normal1.scale(this.bv);
  15825. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  15826. return new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  15827. };
  15828. PickingInfo.prototype.getTextureCoordinates = function () {
  15829. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  15830. return null;
  15831. }
  15832. var indices = this.pickedMesh.getIndices();
  15833. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  15834. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  15835. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  15836. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  15837. uv0 = uv0.scale(this.bu);
  15838. uv1 = uv1.scale(this.bv);
  15839. uv2 = uv2.scale(1.0 - this.bu - this.bv);
  15840. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  15841. };
  15842. return PickingInfo;
  15843. })();
  15844. BABYLON.PickingInfo = PickingInfo;
  15845. })(BABYLON || (BABYLON = {}));
  15846. //# sourceMappingURL=babylon.pickingInfo.js.map
  15847. var BABYLON;
  15848. (function (BABYLON) {
  15849. var FilesInput = (function () {
  15850. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  15851. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  15852. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  15853. this.engine = p_engine;
  15854. this.canvas = p_canvas;
  15855. this.currentScene = p_scene;
  15856. this.sceneLoadedCallback = p_sceneLoadedCallback;
  15857. this.progressCallback = p_progressCallback;
  15858. this.additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  15859. this.textureLoadingCallback = p_textureLoadingCallback;
  15860. this.startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  15861. }
  15862. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  15863. var _this = this;
  15864. if (p_elementToMonitor) {
  15865. this.elementToMonitor = p_elementToMonitor;
  15866. this.elementToMonitor.addEventListener("dragenter", function (e) {
  15867. _this.drag(e);
  15868. }, false);
  15869. this.elementToMonitor.addEventListener("dragover", function (e) {
  15870. _this.drag(e);
  15871. }, false);
  15872. this.elementToMonitor.addEventListener("drop", function (e) {
  15873. _this.drop(e);
  15874. }, false);
  15875. }
  15876. };
  15877. FilesInput.prototype.renderFunction = function () {
  15878. if (this.additionnalRenderLoopLogicCallback) {
  15879. this.additionnalRenderLoopLogicCallback();
  15880. }
  15881. if (this.currentScene) {
  15882. if (this.textureLoadingCallback) {
  15883. var remaining = this.currentScene.getWaitingItemsCount();
  15884. if (remaining > 0) {
  15885. this.textureLoadingCallback(remaining);
  15886. }
  15887. }
  15888. this.currentScene.render();
  15889. }
  15890. };
  15891. FilesInput.prototype.drag = function (e) {
  15892. e.stopPropagation();
  15893. e.preventDefault();
  15894. };
  15895. FilesInput.prototype.drop = function (eventDrop) {
  15896. eventDrop.stopPropagation();
  15897. eventDrop.preventDefault();
  15898. this.loadFiles(eventDrop);
  15899. };
  15900. FilesInput.prototype.loadFiles = function (event) {
  15901. var _this = this;
  15902. var that = this;
  15903. if (this.startingProcessingFilesCallback)
  15904. this.startingProcessingFilesCallback();
  15905. var sceneFileToLoad;
  15906. var filesToLoad;
  15907. // Handling data transfer via drag'n'drop
  15908. if (event && event.dataTransfer && event.dataTransfer.files) {
  15909. filesToLoad = event.dataTransfer.files;
  15910. }
  15911. // Handling files from input files
  15912. if (event && event.target && event.target.files) {
  15913. filesToLoad = event.target.files;
  15914. }
  15915. if (filesToLoad && filesToLoad.length > 0) {
  15916. for (var i = 0; i < filesToLoad.length; i++) {
  15917. switch (filesToLoad[i].type) {
  15918. case "image/jpeg":
  15919. case "image/png":
  15920. BABYLON.FilesInput.FilesTextures[filesToLoad[i].name] = filesToLoad[i];
  15921. break;
  15922. case "image/targa":
  15923. case "image/vnd.ms-dds":
  15924. BABYLON.FilesInput.FilesToLoad[filesToLoad[i].name] = filesToLoad[i];
  15925. break;
  15926. default:
  15927. 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) {
  15928. sceneFileToLoad = filesToLoad[i];
  15929. }
  15930. break;
  15931. }
  15932. }
  15933. // If a ".babylon" file has been provided
  15934. if (sceneFileToLoad) {
  15935. if (this.currentScene) {
  15936. this.engine.stopRenderLoop();
  15937. this.currentScene.dispose();
  15938. }
  15939. BABYLON.SceneLoader.Load("file:", sceneFileToLoad, this.engine, function (newScene) {
  15940. that.currentScene = newScene;
  15941. // Wait for textures and shaders to be ready
  15942. that.currentScene.executeWhenReady(function () {
  15943. // Attach camera to canvas inputs
  15944. if (that.currentScene.activeCamera) {
  15945. that.currentScene.activeCamera.attachControl(that.canvas);
  15946. }
  15947. if (that.sceneLoadedCallback) {
  15948. that.sceneLoadedCallback(sceneFileToLoad, that.currentScene);
  15949. }
  15950. that.engine.runRenderLoop(function () {
  15951. that.renderFunction();
  15952. });
  15953. });
  15954. }, function (progress) {
  15955. if (_this.progressCallback) {
  15956. _this.progressCallback(progress);
  15957. }
  15958. });
  15959. } else {
  15960. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  15961. }
  15962. }
  15963. };
  15964. FilesInput.FilesTextures = new Array();
  15965. FilesInput.FilesToLoad = new Array();
  15966. return FilesInput;
  15967. })();
  15968. BABYLON.FilesInput = FilesInput;
  15969. })(BABYLON || (BABYLON = {}));
  15970. //# sourceMappingURL=babylon.filesInput.js.map
  15971. var BABYLON;
  15972. (function (BABYLON) {
  15973. var OimoJSPlugin = (function () {
  15974. function OimoJSPlugin() {
  15975. this._registeredMeshes = [];
  15976. /**
  15977. * Update the body position according to the mesh position
  15978. * @param mesh
  15979. */
  15980. this.updateBodyPosition = function (mesh) {
  15981. for (var index = 0; index < this._registeredMeshes.length; index++) {
  15982. var registeredMesh = this._registeredMeshes[index];
  15983. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  15984. var body = registeredMesh.body.body;
  15985. mesh.computeWorldMatrix(true);
  15986. var center = mesh.getBoundingInfo().boundingBox.center;
  15987. body.setPosition(center.x, center.y, center.z);
  15988. body.setOrientation(mesh.rotation.x, mesh.rotation.y, mesh.rotation.z);
  15989. return;
  15990. }
  15991. // Case where the parent has been updated
  15992. if (registeredMesh.mesh.parent === mesh) {
  15993. mesh.computeWorldMatrix(true);
  15994. registeredMesh.mesh.computeWorldMatrix(true);
  15995. var absolutePosition = registeredMesh.mesh.getAbsolutePosition();
  15996. var absoluteRotation = mesh.rotation;
  15997. body = registeredMesh.body.body;
  15998. body.setPosition(absolutePosition.x, absolutePosition.y, absolutePosition.z);
  15999. body.setOrientation(absoluteRotation.x, absoluteRotation.y, absoluteRotation.z);
  16000. return;
  16001. }
  16002. }
  16003. };
  16004. }
  16005. OimoJSPlugin.prototype._checkWithEpsilon = function (value) {
  16006. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  16007. };
  16008. OimoJSPlugin.prototype.initialize = function (iterations) {
  16009. this._world = new OIMO.World();
  16010. this._world.clear();
  16011. };
  16012. OimoJSPlugin.prototype.setGravity = function (gravity) {
  16013. this._world.gravity = gravity;
  16014. };
  16015. OimoJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  16016. var body = null;
  16017. this.unregisterMesh(mesh);
  16018. mesh.computeWorldMatrix(true);
  16019. switch (impostor) {
  16020. case BABYLON.PhysicsEngine.SphereImpostor:
  16021. var initialRotation = null;
  16022. if (mesh.rotationQuaternion) {
  16023. initialRotation = mesh.rotationQuaternion.clone();
  16024. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  16025. mesh.computeWorldMatrix(true);
  16026. }
  16027. var bbox = mesh.getBoundingInfo().boundingBox;
  16028. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  16029. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  16030. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  16031. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  16032. // The delta between the mesh position and the mesh bounding box center
  16033. var deltaPosition = mesh.position.subtract(bbox.center);
  16034. // Transform delta position with the rotation
  16035. if (initialRotation) {
  16036. var m = new BABYLON.Matrix();
  16037. initialRotation.toRotationMatrix(m);
  16038. deltaPosition = BABYLON.Vector3.TransformCoordinates(deltaPosition, m);
  16039. }
  16040. body = new OIMO.Body({
  16041. type: 'sphere',
  16042. size: [size],
  16043. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  16044. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  16045. move: options.mass != 0,
  16046. config: [options.mass, options.friction, options.restitution],
  16047. world: this._world
  16048. });
  16049. // Restore rotation
  16050. if (initialRotation) {
  16051. body.setQuaternion(initialRotation);
  16052. }
  16053. this._registeredMeshes.push({
  16054. mesh: mesh,
  16055. body: body,
  16056. delta: deltaPosition
  16057. });
  16058. break;
  16059. case BABYLON.PhysicsEngine.PlaneImpostor:
  16060. case BABYLON.PhysicsEngine.BoxImpostor:
  16061. initialRotation = null;
  16062. if (mesh.rotationQuaternion) {
  16063. initialRotation = mesh.rotationQuaternion.clone();
  16064. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  16065. mesh.computeWorldMatrix(true);
  16066. }
  16067. bbox = mesh.getBoundingInfo().boundingBox;
  16068. var min = bbox.minimumWorld;
  16069. var max = bbox.maximumWorld;
  16070. var box = max.subtract(min);
  16071. var sizeX = this._checkWithEpsilon(box.x);
  16072. var sizeY = this._checkWithEpsilon(box.y);
  16073. var sizeZ = this._checkWithEpsilon(box.z);
  16074. // The delta between the mesh position and the mesh boudning box center
  16075. deltaPosition = mesh.position.subtract(bbox.center);
  16076. // Transform delta position with the rotation
  16077. if (initialRotation) {
  16078. m = new BABYLON.Matrix();
  16079. initialRotation.toRotationMatrix(m);
  16080. deltaPosition = BABYLON.Vector3.TransformCoordinates(deltaPosition, m);
  16081. }
  16082. body = new OIMO.Body({
  16083. type: 'box',
  16084. size: [sizeX, sizeY, sizeZ],
  16085. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  16086. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  16087. move: options.mass != 0,
  16088. config: [options.mass, options.friction, options.restitution],
  16089. world: this._world
  16090. });
  16091. if (initialRotation) {
  16092. body.setQuaternion(initialRotation);
  16093. }
  16094. this._registeredMeshes.push({
  16095. mesh: mesh,
  16096. body: body,
  16097. delta: deltaPosition
  16098. });
  16099. break;
  16100. }
  16101. return body;
  16102. };
  16103. OimoJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  16104. var types = [], sizes = [], positions = [], rotations = [];
  16105. var initialMesh = parts[0].mesh;
  16106. for (var index = 0; index < parts.length; index++) {
  16107. var part = parts[index];
  16108. var bodyParameters = this._createBodyAsCompound(part, options, initialMesh);
  16109. types.push(bodyParameters.type);
  16110. sizes.push.apply(sizes, bodyParameters.size);
  16111. positions.push.apply(positions, bodyParameters.pos);
  16112. rotations.push.apply(rotations, bodyParameters.rot);
  16113. }
  16114. var body = new OIMO.Body({
  16115. type: types,
  16116. size: sizes,
  16117. pos: positions,
  16118. rot: rotations,
  16119. move: options.mass != 0,
  16120. config: [options.mass, options.friction, options.restitution],
  16121. world: this._world
  16122. });
  16123. this._registeredMeshes.push({
  16124. mesh: initialMesh,
  16125. body: body
  16126. });
  16127. return body;
  16128. };
  16129. OimoJSPlugin.prototype._createBodyAsCompound = function (part, options, initialMesh) {
  16130. var bodyParameters = null;
  16131. var mesh = part.mesh;
  16132. switch (part.impostor) {
  16133. case BABYLON.PhysicsEngine.SphereImpostor:
  16134. var bbox = mesh.getBoundingInfo().boundingBox;
  16135. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  16136. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  16137. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  16138. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  16139. bodyParameters = {
  16140. type: 'sphere',
  16141. /* bug with oimo : sphere needs 3 sizes in this case */
  16142. size: [size, -1, -1],
  16143. pos: [mesh.position.x, mesh.position.y, mesh.position.z],
  16144. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  16145. };
  16146. break;
  16147. case BABYLON.PhysicsEngine.PlaneImpostor:
  16148. case BABYLON.PhysicsEngine.BoxImpostor:
  16149. bbox = mesh.getBoundingInfo().boundingBox;
  16150. var min = bbox.minimumWorld;
  16151. var max = bbox.maximumWorld;
  16152. var box = max.subtract(min);
  16153. var sizeX = this._checkWithEpsilon(box.x);
  16154. var sizeY = this._checkWithEpsilon(box.y);
  16155. var sizeZ = this._checkWithEpsilon(box.z);
  16156. var relativePosition = mesh.position;
  16157. bodyParameters = {
  16158. type: 'box',
  16159. size: [sizeX, sizeY, sizeZ],
  16160. pos: [relativePosition.x, relativePosition.y, relativePosition.z],
  16161. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  16162. };
  16163. break;
  16164. }
  16165. return bodyParameters;
  16166. };
  16167. OimoJSPlugin.prototype.unregisterMesh = function (mesh) {
  16168. for (var index = 0; index < this._registeredMeshes.length; index++) {
  16169. var registeredMesh = this._registeredMeshes[index];
  16170. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  16171. if (registeredMesh.body) {
  16172. this._world.removeRigidBody(registeredMesh.body.body);
  16173. this._unbindBody(registeredMesh.body);
  16174. }
  16175. this._registeredMeshes.splice(index, 1);
  16176. return;
  16177. }
  16178. }
  16179. };
  16180. OimoJSPlugin.prototype._unbindBody = function (body) {
  16181. for (var index = 0; index < this._registeredMeshes.length; index++) {
  16182. var registeredMesh = this._registeredMeshes[index];
  16183. if (registeredMesh.body === body) {
  16184. registeredMesh.body = null;
  16185. }
  16186. }
  16187. };
  16188. OimoJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  16189. for (var index = 0; index < this._registeredMeshes.length; index++) {
  16190. var registeredMesh = this._registeredMeshes[index];
  16191. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  16192. // Get object mass to have a behaviour similar to cannon.js
  16193. var mass = registeredMesh.body.body.massInfo.mass;
  16194. // The force is scaled with the mass of object
  16195. registeredMesh.body.body.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  16196. return;
  16197. }
  16198. }
  16199. };
  16200. OimoJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  16201. var body1 = null, body2 = null;
  16202. for (var index = 0; index < this._registeredMeshes.length; index++) {
  16203. var registeredMesh = this._registeredMeshes[index];
  16204. if (registeredMesh.mesh === mesh1) {
  16205. body1 = registeredMesh.body.body;
  16206. } else if (registeredMesh.mesh === mesh2) {
  16207. body2 = registeredMesh.body.body;
  16208. }
  16209. }
  16210. if (!body1 || !body2) {
  16211. return false;
  16212. }
  16213. if (!options) {
  16214. options = {};
  16215. }
  16216. new OIMO.Link({
  16217. type: options.type,
  16218. body1: body1,
  16219. body2: body2,
  16220. min: options.min,
  16221. max: options.max,
  16222. axe1: options.axe1,
  16223. axe2: options.axe2,
  16224. pos1: [pivot1.x, pivot1.y, pivot1.z],
  16225. pos2: [pivot2.x, pivot2.y, pivot2.z],
  16226. collision: options.collision,
  16227. spring: options.spring,
  16228. world: this._world
  16229. });
  16230. return true;
  16231. };
  16232. OimoJSPlugin.prototype.dispose = function () {
  16233. this._world.clear();
  16234. while (this._registeredMeshes.length) {
  16235. this.unregisterMesh(this._registeredMeshes[0].mesh);
  16236. }
  16237. };
  16238. OimoJSPlugin.prototype.isSupported = function () {
  16239. return OIMO !== undefined;
  16240. };
  16241. OimoJSPlugin.prototype._getLastShape = function (body) {
  16242. var lastShape = body.shapes;
  16243. while (lastShape.next) {
  16244. lastShape = lastShape.next;
  16245. }
  16246. return lastShape;
  16247. };
  16248. OimoJSPlugin.prototype.runOneStep = function (time) {
  16249. this._world.step();
  16250. // Update the position of all registered meshes
  16251. var i = this._registeredMeshes.length;
  16252. var m;
  16253. while (i--) {
  16254. var body = this._registeredMeshes[i].body.body;
  16255. var mesh = this._registeredMeshes[i].mesh;
  16256. var delta = this._registeredMeshes[i].delta;
  16257. if (!body.sleeping) {
  16258. if (body.shapes.next) {
  16259. var parentShape = this._getLastShape(body);
  16260. mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  16261. mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  16262. mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  16263. var mtx = BABYLON.Matrix.FromArray(body.getMatrix());
  16264. if (!mesh.rotationQuaternion) {
  16265. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  16266. }
  16267. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  16268. mesh.computeWorldMatrix();
  16269. } else {
  16270. m = body.getMatrix();
  16271. mtx = BABYLON.Matrix.FromArray(m);
  16272. // Body position
  16273. var bodyX = mtx.m[12], bodyY = mtx.m[13], bodyZ = mtx.m[14];
  16274. if (!delta) {
  16275. mesh.position.x = bodyX;
  16276. mesh.position.y = bodyY;
  16277. mesh.position.z = bodyZ;
  16278. } else {
  16279. mesh.position.x = bodyX + delta.x;
  16280. mesh.position.y = bodyY + delta.y;
  16281. mesh.position.z = bodyZ + delta.z;
  16282. }
  16283. if (!mesh.rotationQuaternion) {
  16284. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  16285. }
  16286. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  16287. mesh.computeWorldMatrix();
  16288. }
  16289. }
  16290. }
  16291. };
  16292. return OimoJSPlugin;
  16293. })();
  16294. BABYLON.OimoJSPlugin = OimoJSPlugin;
  16295. })(BABYLON || (BABYLON = {}));
  16296. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  16297. var BABYLON;
  16298. (function (BABYLON) {
  16299. var PhysicsEngine = (function () {
  16300. function PhysicsEngine(plugin) {
  16301. this._currentPlugin = plugin || new BABYLON.OimoJSPlugin();
  16302. }
  16303. PhysicsEngine.prototype._initialize = function (gravity) {
  16304. this._currentPlugin.initialize();
  16305. this._setGravity(gravity);
  16306. };
  16307. PhysicsEngine.prototype._runOneStep = function (delta) {
  16308. if (delta > 0.1) {
  16309. delta = 0.1;
  16310. } else if (delta <= 0) {
  16311. delta = 1.0 / 60.0;
  16312. }
  16313. this._currentPlugin.runOneStep(delta);
  16314. };
  16315. PhysicsEngine.prototype._setGravity = function (gravity) {
  16316. this.gravity = gravity || new BABYLON.Vector3(0, -9.82, 0);
  16317. this._currentPlugin.setGravity(this.gravity);
  16318. };
  16319. PhysicsEngine.prototype._registerMesh = function (mesh, impostor, options) {
  16320. return this._currentPlugin.registerMesh(mesh, impostor, options);
  16321. };
  16322. PhysicsEngine.prototype._registerMeshesAsCompound = function (parts, options) {
  16323. return this._currentPlugin.registerMeshesAsCompound(parts, options);
  16324. };
  16325. PhysicsEngine.prototype._unregisterMesh = function (mesh) {
  16326. this._currentPlugin.unregisterMesh(mesh);
  16327. };
  16328. PhysicsEngine.prototype._applyImpulse = function (mesh, force, contactPoint) {
  16329. this._currentPlugin.applyImpulse(mesh, force, contactPoint);
  16330. };
  16331. PhysicsEngine.prototype._createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  16332. return this._currentPlugin.createLink(mesh1, mesh2, pivot1, pivot2, options);
  16333. };
  16334. PhysicsEngine.prototype._updateBodyPosition = function (mesh) {
  16335. this._currentPlugin.updateBodyPosition(mesh);
  16336. };
  16337. PhysicsEngine.prototype.dispose = function () {
  16338. this._currentPlugin.dispose();
  16339. };
  16340. PhysicsEngine.prototype.isSupported = function () {
  16341. return this._currentPlugin.isSupported();
  16342. };
  16343. PhysicsEngine.NoImpostor = 0;
  16344. PhysicsEngine.SphereImpostor = 1;
  16345. PhysicsEngine.BoxImpostor = 2;
  16346. PhysicsEngine.PlaneImpostor = 3;
  16347. PhysicsEngine.MeshImpostor = 4;
  16348. PhysicsEngine.CapsuleImpostor = 5;
  16349. PhysicsEngine.ConeImpostor = 6;
  16350. PhysicsEngine.CylinderImpostor = 7;
  16351. PhysicsEngine.ConvexHullImpostor = 8;
  16352. PhysicsEngine.Epsilon = 0.001;
  16353. return PhysicsEngine;
  16354. })();
  16355. BABYLON.PhysicsEngine = PhysicsEngine;
  16356. })(BABYLON || (BABYLON = {}));
  16357. //# sourceMappingURL=babylon.physicsEngine.js.map
  16358. var BABYLON;
  16359. (function (BABYLON) {
  16360. var serializeLight = function (light) {
  16361. var serializationObject = {};
  16362. serializationObject.name = light.name;
  16363. serializationObject.id = light.id;
  16364. serializationObject.tags = BABYLON.Tags.GetTags(light);
  16365. if (light instanceof BABYLON.PointLight) {
  16366. serializationObject.type = 0;
  16367. serializationObject.position = light.position.asArray();
  16368. } else if (light instanceof BABYLON.DirectionalLight) {
  16369. serializationObject.type = 1;
  16370. var directionalLight = light;
  16371. serializationObject.position = directionalLight.position.asArray();
  16372. serializationObject.direction = directionalLight.direction.asArray();
  16373. } else if (light instanceof BABYLON.SpotLight) {
  16374. serializationObject.type = 2;
  16375. var spotLight = light;
  16376. serializationObject.position = spotLight.position.asArray();
  16377. serializationObject.direction = spotLight.position.asArray();
  16378. serializationObject.angle = spotLight.angle;
  16379. serializationObject.exponent = spotLight.exponent;
  16380. } else if (light instanceof BABYLON.HemisphericLight) {
  16381. serializationObject.type = 3;
  16382. var hemisphericLight = light;
  16383. serializationObject.direction = hemisphericLight.direction.asArray();
  16384. serializationObject.groundColor = hemisphericLight.groundColor.asArray();
  16385. }
  16386. if (light.intensity) {
  16387. serializationObject.intensity = light.intensity;
  16388. }
  16389. serializationObject.range = light.range;
  16390. serializationObject.diffuse = light.diffuse.asArray();
  16391. serializationObject.specular = light.specular.asArray();
  16392. return serializationObject;
  16393. };
  16394. var serializeFresnelParameter = function (fresnelParameter) {
  16395. var serializationObject = {};
  16396. serializationObject.isEnabled = fresnelParameter.isEnabled;
  16397. serializationObject.leftColor = fresnelParameter.leftColor;
  16398. serializationObject.rightColor = fresnelParameter.rightColor;
  16399. serializationObject.bias = fresnelParameter.bias;
  16400. serializationObject.power = fresnelParameter.power;
  16401. return serializationObject;
  16402. };
  16403. var serializeCamera = function (camera) {
  16404. var serializationObject = {};
  16405. serializationObject.name = camera.name;
  16406. serializationObject.tags = BABYLON.Tags.GetTags(camera);
  16407. serializationObject.id = camera.id;
  16408. serializationObject.position = camera.position.asArray();
  16409. // Parent
  16410. if (camera.parent) {
  16411. serializationObject.parentId = camera.parent.id;
  16412. }
  16413. // Target
  16414. serializationObject.rotation = camera.rotation.asArray();
  16415. // Locked target
  16416. if (camera.lockedTarget && camera.lockedTarget.id) {
  16417. serializationObject.lockedTargetId = camera.lockedTarget.id;
  16418. }
  16419. serializationObject.fov = camera.fov;
  16420. serializationObject.minZ = camera.minZ;
  16421. serializationObject.maxZ = camera.maxZ;
  16422. serializationObject.speed = camera.speed;
  16423. serializationObject.inertia = camera.inertia;
  16424. serializationObject.checkCollisions = camera.checkCollisions;
  16425. serializationObject.applyGravity = camera.applyGravity;
  16426. if (camera.ellipsoid) {
  16427. serializationObject.ellipsoid = camera.ellipsoid.asArray();
  16428. }
  16429. // Animations
  16430. appendAnimations(camera, serializationObject);
  16431. // Layer mask
  16432. serializationObject.layerMask = camera.layerMask;
  16433. return serializationObject;
  16434. };
  16435. var appendAnimations = function (source, destination) {
  16436. if (source.animations) {
  16437. destination.animations = [];
  16438. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  16439. var animation = source.animations[animationIndex];
  16440. destination.animations.push(serializeAnimation(animation));
  16441. }
  16442. }
  16443. };
  16444. var serializeAnimation = function (animation) {
  16445. var serializationObject = {};
  16446. serializationObject.name = animation.name;
  16447. serializationObject.property = animation.targetProperty;
  16448. serializationObject.framePerSecond = animation.framePerSecond;
  16449. serializationObject.dataType = animation.dataType;
  16450. serializationObject.loopBehavior = animation.loopMode;
  16451. var dataType = animation.dataType;
  16452. serializationObject.keys = [];
  16453. var keys = animation.getKeys();
  16454. for (var index = 0; index < keys.length; index++) {
  16455. var animationKey = keys[index];
  16456. var key = {};
  16457. key.frame = animationKey.frame;
  16458. switch (dataType) {
  16459. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  16460. key.values = [animationKey.value];
  16461. break;
  16462. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  16463. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  16464. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  16465. key.values = animationKey.value.asArray();
  16466. break;
  16467. }
  16468. serializationObject.keys.push(key);
  16469. }
  16470. return serializationObject;
  16471. };
  16472. var serializeMultiMaterial = function (material) {
  16473. var serializationObject = {};
  16474. serializationObject.name = material.name;
  16475. serializationObject.id = material.id;
  16476. serializationObject.tags = BABYLON.Tags.GetTags(material);
  16477. serializationObject.materials = [];
  16478. for (var matIndex = 0; matIndex < material.subMaterials.length; matIndex++) {
  16479. var subMat = material.subMaterials[matIndex];
  16480. if (subMat) {
  16481. serializationObject.materials.push(subMat.id);
  16482. } else {
  16483. serializationObject.materials.push(null);
  16484. }
  16485. }
  16486. return serializationObject;
  16487. };
  16488. var serializeMaterial = function (material) {
  16489. var serializationObject = {};
  16490. serializationObject.name = material.name;
  16491. serializationObject.ambient = material.ambientColor.asArray();
  16492. serializationObject.diffuse = material.diffuseColor.asArray();
  16493. serializationObject.specular = material.specularColor.asArray();
  16494. serializationObject.specularPower = material.specularPower;
  16495. serializationObject.emissive = material.emissiveColor.asArray();
  16496. serializationObject.alpha = material.alpha;
  16497. serializationObject.id = material.id;
  16498. serializationObject.tags = BABYLON.Tags.GetTags(material);
  16499. serializationObject.backFaceCulling = material.backFaceCulling;
  16500. if (material.diffuseTexture) {
  16501. serializationObject.diffuseTexture = serializeTexture(material.diffuseTexture);
  16502. }
  16503. if (material.diffuseFresnelParameters) {
  16504. serializationObject.diffuseFresnelParameters = serializeFresnelParameter(material.diffuseFresnelParameters);
  16505. }
  16506. if (material.ambientTexture) {
  16507. serializationObject.ambientTexture = serializeTexture(material.ambientTexture);
  16508. }
  16509. if (material.opacityTexture) {
  16510. serializationObject.opacityTexture = serializeTexture(material.opacityTexture);
  16511. }
  16512. if (material.opacityFresnelParameters) {
  16513. serializationObject.opacityFresnelParameters = serializeFresnelParameter(material.opacityFresnelParameters);
  16514. }
  16515. if (material.reflectionTexture) {
  16516. serializationObject.reflectionTexture = serializeTexture(material.reflectionTexture);
  16517. }
  16518. if (material.reflectionFresnelParameters) {
  16519. serializationObject.reflectionFresnelParameters = serializeFresnelParameter(material.reflectionFresnelParameters);
  16520. }
  16521. if (material.emissiveTexture) {
  16522. serializationObject.emissiveTexture = serializeTexture(material.emissiveTexture);
  16523. }
  16524. if (material.emissiveFresnelParameters) {
  16525. serializationObject.emissiveFresnelParameters = serializeFresnelParameter(material.emissiveFresnelParameters);
  16526. }
  16527. if (material.specularTexture) {
  16528. serializationObject.specularTexture = serializeTexture(material.specularTexture);
  16529. }
  16530. if (material.bumpTexture) {
  16531. serializationObject.bumpTexture = serializeTexture(material.bumpTexture);
  16532. }
  16533. return serializationObject;
  16534. };
  16535. var serializeTexture = function (texture) {
  16536. var serializationObject = {};
  16537. if (!texture.name) {
  16538. return null;
  16539. }
  16540. if (texture instanceof BABYLON.CubeTexture) {
  16541. serializationObject.name = texture.name;
  16542. serializationObject.hasAlpha = texture.hasAlpha;
  16543. serializationObject.level = texture.level;
  16544. serializationObject.coordinatesMode = texture.coordinatesMode;
  16545. return serializationObject;
  16546. }
  16547. if (texture instanceof BABYLON.MirrorTexture) {
  16548. var mirrorTexture = texture;
  16549. serializationObject.renderTargetSize = mirrorTexture.getRenderSize();
  16550. serializationObject.renderList = [];
  16551. for (var index = 0; index < mirrorTexture.renderList.length; index++) {
  16552. serializationObject.renderList.push(mirrorTexture.renderList[index].id);
  16553. }
  16554. serializationObject.mirrorPlane = mirrorTexture.mirrorPlane.asArray();
  16555. } else if (texture instanceof BABYLON.RenderTargetTexture) {
  16556. var renderTargetTexture = texture;
  16557. serializationObject.renderTargetSize = renderTargetTexture.getRenderSize();
  16558. serializationObject.renderList = [];
  16559. for (index = 0; index < renderTargetTexture.renderList.length; index++) {
  16560. serializationObject.renderList.push(renderTargetTexture.renderList[index].id);
  16561. }
  16562. }
  16563. var regularTexture = texture;
  16564. serializationObject.name = texture.name;
  16565. serializationObject.hasAlpha = texture.hasAlpha;
  16566. serializationObject.level = texture.level;
  16567. serializationObject.coordinatesIndex = texture.coordinatesIndex;
  16568. serializationObject.coordinatesMode = texture.coordinatesMode;
  16569. serializationObject.uOffset = regularTexture.uOffset;
  16570. serializationObject.vOffset = regularTexture.vOffset;
  16571. serializationObject.uScale = regularTexture.uScale;
  16572. serializationObject.vScale = regularTexture.vScale;
  16573. serializationObject.uAng = regularTexture.uAng;
  16574. serializationObject.vAng = regularTexture.vAng;
  16575. serializationObject.wAng = regularTexture.wAng;
  16576. serializationObject.wrapU = texture.wrapU;
  16577. serializationObject.wrapV = texture.wrapV;
  16578. // Animations
  16579. appendAnimations(texture, serializationObject);
  16580. return serializationObject;
  16581. };
  16582. var serializeSkeleton = function (skeleton) {
  16583. var serializationObject = {};
  16584. serializationObject.name = skeleton.name;
  16585. serializationObject.id = skeleton.id;
  16586. serializationObject.bones = [];
  16587. for (var index = 0; index < skeleton.bones.length; index++) {
  16588. var bone = skeleton.bones[index];
  16589. var serializedBone = {
  16590. parentBoneIndex: bone.getParent() ? skeleton.bones.indexOf(bone.getParent()) : -1,
  16591. name: bone.name,
  16592. matrix: bone.getLocalMatrix().toArray()
  16593. };
  16594. serializationObject.bones.push(serializedBone);
  16595. if (bone.animations && bone.animations.length > 0) {
  16596. serializedBone.animation = serializeAnimation(bone.animations[0]);
  16597. }
  16598. }
  16599. return serializationObject;
  16600. };
  16601. var serializeParticleSystem = function (particleSystem) {
  16602. var serializationObject = {};
  16603. serializationObject.emitterId = particleSystem.emitter.id;
  16604. serializationObject.capacity = particleSystem.getCapacity();
  16605. if (particleSystem.particleTexture) {
  16606. serializationObject.textureName = particleSystem.particleTexture.name;
  16607. }
  16608. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  16609. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  16610. serializationObject.minSize = particleSystem.minSize;
  16611. serializationObject.maxSize = particleSystem.maxSize;
  16612. serializationObject.minLifeTime = particleSystem.minLifeTime;
  16613. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  16614. serializationObject.emitRate = particleSystem.emitRate;
  16615. serializationObject.minEmitBox = particleSystem.minEmitBox.asArray();
  16616. serializationObject.maxEmitBox = particleSystem.maxEmitBox.asArray();
  16617. serializationObject.gravity = particleSystem.gravity.asArray();
  16618. serializationObject.direction1 = particleSystem.direction1.asArray();
  16619. serializationObject.direction2 = particleSystem.direction2.asArray();
  16620. serializationObject.color1 = particleSystem.color1.asArray();
  16621. serializationObject.color2 = particleSystem.color2.asArray();
  16622. serializationObject.colorDead = particleSystem.colorDead.asArray();
  16623. serializationObject.updateSpeed = particleSystem.updateSpeed;
  16624. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  16625. serializationObject.textureMask = particleSystem.textureMask.asArray();
  16626. serializationObject.blendMode = particleSystem.blendMode;
  16627. return serializationObject;
  16628. };
  16629. var serializeLensFlareSystem = function (lensFlareSystem) {
  16630. var serializationObject = {};
  16631. serializationObject.emitterId = lensFlareSystem.getEmitter().id;
  16632. serializationObject.borderLimit = lensFlareSystem.borderLimit;
  16633. serializationObject.flares = [];
  16634. for (var index = 0; index < lensFlareSystem.lensFlares.length; index++) {
  16635. var flare = lensFlareSystem.lensFlares[index];
  16636. serializationObject.flares.push({
  16637. size: flare.size,
  16638. position: flare.position,
  16639. color: flare.color.asArray(),
  16640. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  16641. });
  16642. }
  16643. return serializationObject;
  16644. };
  16645. var serializeShadowGenerator = function (light) {
  16646. var serializationObject = {};
  16647. var shadowGenerator = light.getShadowGenerator();
  16648. serializationObject.lightId = light.id;
  16649. serializationObject.mapSize = shadowGenerator.getShadowMap().getRenderSize();
  16650. serializationObject.useVarianceShadowMap = shadowGenerator.useVarianceShadowMap;
  16651. serializationObject.usePoissonSampling = shadowGenerator.usePoissonSampling;
  16652. serializationObject.renderList = [];
  16653. for (var meshIndex = 0; meshIndex < shadowGenerator.getShadowMap().renderList.length; meshIndex++) {
  16654. var mesh = shadowGenerator.getShadowMap().renderList[meshIndex];
  16655. serializationObject.renderList.push(mesh.id);
  16656. }
  16657. return serializationObject;
  16658. };
  16659. var serializedGeometries = [];
  16660. var serializeGeometry = function (geometry, serializationGeometries) {
  16661. if (serializedGeometries[geometry.id]) {
  16662. return;
  16663. }
  16664. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  16665. serializationGeometries.boxes.push(serializeBox(geometry));
  16666. } else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  16667. serializationGeometries.spheres.push(serializeSphere(geometry));
  16668. } else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  16669. serializationGeometries.cylinders.push(serializeCylinder(geometry));
  16670. } else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  16671. serializationGeometries.toruses.push(serializeTorus(geometry));
  16672. } else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  16673. serializationGeometries.grounds.push(serializeGround(geometry));
  16674. } else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  16675. serializationGeometries.planes.push(serializePlane(geometry));
  16676. } else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  16677. serializationGeometries.torusKnots.push(serializeTorusKnot(geometry));
  16678. } else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  16679. throw new Error("Unknow primitive type");
  16680. } else {
  16681. serializationGeometries.vertexData.push(serializeVertexData(geometry));
  16682. }
  16683. serializedGeometries[geometry.id] = true;
  16684. };
  16685. var serializeGeometryBase = function (geometry) {
  16686. var serializationObject = {};
  16687. serializationObject.id = geometry.id;
  16688. if (BABYLON.Tags.HasTags(geometry)) {
  16689. serializationObject.tags = BABYLON.Tags.GetTags(geometry);
  16690. }
  16691. return serializationObject;
  16692. };
  16693. var serializeVertexData = function (vertexData) {
  16694. var serializationObject = serializeGeometryBase(vertexData);
  16695. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  16696. serializationObject.positions = vertexData.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16697. }
  16698. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  16699. serializationObject.normals = vertexData.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16700. }
  16701. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  16702. serializationObject.uvs = vertexData.getVerticesData(BABYLON.VertexBuffer.UVKind);
  16703. }
  16704. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  16705. serializationObject.uvs2 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  16706. }
  16707. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  16708. serializationObject.colors = vertexData.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  16709. }
  16710. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  16711. serializationObject.matricesIndices = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  16712. serializationObject.matricesIndices._isExpanded = true;
  16713. }
  16714. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  16715. serializationObject.matricesWeights = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  16716. }
  16717. serializationObject.indices = vertexData.getIndices();
  16718. return serializationObject;
  16719. };
  16720. var serializePrimitive = function (primitive) {
  16721. var serializationObject = serializeGeometryBase(primitive);
  16722. serializationObject.canBeRegenerated = primitive.canBeRegenerated();
  16723. return serializationObject;
  16724. };
  16725. var serializeBox = function (box) {
  16726. var serializationObject = serializePrimitive(box);
  16727. serializationObject.size = box.size;
  16728. return serializationObject;
  16729. };
  16730. var serializeSphere = function (sphere) {
  16731. var serializationObject = serializePrimitive(sphere);
  16732. serializationObject.segments = sphere.segments;
  16733. serializationObject.diameter = sphere.diameter;
  16734. return serializationObject;
  16735. };
  16736. var serializeCylinder = function (cylinder) {
  16737. var serializationObject = serializePrimitive(cylinder);
  16738. serializationObject.height = cylinder.height;
  16739. serializationObject.diameterTop = cylinder.diameterTop;
  16740. serializationObject.diameterBottom = cylinder.diameterBottom;
  16741. serializationObject.tessellation = cylinder.tessellation;
  16742. return serializationObject;
  16743. };
  16744. var serializeTorus = function (torus) {
  16745. var serializationObject = serializePrimitive(torus);
  16746. serializationObject.diameter = torus.diameter;
  16747. serializationObject.thickness = torus.thickness;
  16748. serializationObject.tessellation = torus.tessellation;
  16749. return serializationObject;
  16750. };
  16751. var serializeGround = function (ground) {
  16752. var serializationObject = serializePrimitive(ground);
  16753. serializationObject.width = ground.width;
  16754. serializationObject.height = ground.height;
  16755. serializationObject.subdivisions = ground.subdivisions;
  16756. return serializationObject;
  16757. };
  16758. var serializePlane = function (plane) {
  16759. var serializationObject = serializePrimitive(plane);
  16760. serializationObject.size = plane.size;
  16761. return serializationObject;
  16762. };
  16763. var serializeTorusKnot = function (torusKnot) {
  16764. var serializationObject = serializePrimitive(torusKnot);
  16765. serializationObject.radius = torusKnot.radius;
  16766. serializationObject.tube = torusKnot.tube;
  16767. serializationObject.radialSegments = torusKnot.radialSegments;
  16768. serializationObject.tubularSegments = torusKnot.tubularSegments;
  16769. serializationObject.p = torusKnot.p;
  16770. serializationObject.q = torusKnot.q;
  16771. return serializationObject;
  16772. };
  16773. var serializeMesh = function (mesh, serializationScene) {
  16774. var serializationObject = {};
  16775. serializationObject.name = mesh.name;
  16776. serializationObject.id = mesh.id;
  16777. if (BABYLON.Tags.HasTags(mesh)) {
  16778. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  16779. }
  16780. serializationObject.position = mesh.position.asArray();
  16781. if (mesh.rotationQuaternion) {
  16782. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  16783. } else if (mesh.rotation) {
  16784. serializationObject.rotation = mesh.rotation.asArray();
  16785. }
  16786. serializationObject.scaling = mesh.scaling.asArray();
  16787. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  16788. serializationObject.isEnabled = mesh.isEnabled();
  16789. serializationObject.isVisible = mesh.isVisible;
  16790. serializationObject.infiniteDistance = mesh.infiniteDistance;
  16791. serializationObject.pickable = mesh.isPickable;
  16792. serializationObject.receiveShadows = mesh.receiveShadows;
  16793. serializationObject.billboardMode = mesh.billboardMode;
  16794. serializationObject.visibility = mesh.visibility;
  16795. serializationObject.checkCollisions = mesh.checkCollisions;
  16796. // Parent
  16797. if (mesh.parent) {
  16798. serializationObject.parentId = mesh.parent.id;
  16799. }
  16800. // Geometry
  16801. var geometry = mesh._geometry;
  16802. if (geometry) {
  16803. var geometryId = geometry.id;
  16804. serializationObject.geometryId = geometryId;
  16805. if (!mesh.getScene().getGeometryByID(geometryId)) {
  16806. // 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
  16807. serializeGeometry(geometry, serializationScene.geometries);
  16808. }
  16809. // SubMeshes
  16810. serializationObject.subMeshes = [];
  16811. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  16812. var subMesh = mesh.subMeshes[subIndex];
  16813. serializationObject.subMeshes.push({
  16814. materialIndex: subMesh.materialIndex,
  16815. verticesStart: subMesh.verticesStart,
  16816. verticesCount: subMesh.verticesCount,
  16817. indexStart: subMesh.indexStart,
  16818. indexCount: subMesh.indexCount
  16819. });
  16820. }
  16821. }
  16822. // Material
  16823. if (mesh.material) {
  16824. serializationObject.materialId = mesh.material.id;
  16825. } else {
  16826. mesh.material = null;
  16827. }
  16828. // Skeleton
  16829. if (mesh.skeleton) {
  16830. serializationObject.skeletonId = mesh.skeleton.id;
  16831. }
  16832. // Physics
  16833. if (mesh.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  16834. serializationObject.physicsMass = mesh.getPhysicsMass();
  16835. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  16836. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  16837. switch (mesh.getPhysicsImpostor()) {
  16838. case BABYLON.PhysicsEngine.BoxImpostor:
  16839. serializationObject.physicsImpostor = 1;
  16840. break;
  16841. case BABYLON.PhysicsEngine.SphereImpostor:
  16842. serializationObject.physicsImpostor = 2;
  16843. break;
  16844. }
  16845. }
  16846. // Instances
  16847. serializationObject.instances = [];
  16848. for (var index = 0; index < mesh.instances.length; index++) {
  16849. var instance = mesh.instances[index];
  16850. var serializationInstance = {
  16851. name: instance.name,
  16852. position: instance.position,
  16853. rotation: instance.rotation,
  16854. rotationQuaternion: instance.rotationQuaternion,
  16855. scaling: instance.scaling
  16856. };
  16857. serializationObject.instances.push(serializationInstance);
  16858. // Animations
  16859. appendAnimations(instance, serializationInstance);
  16860. }
  16861. // Animations
  16862. appendAnimations(mesh, serializationObject);
  16863. // Layer mask
  16864. serializationObject.layerMask = mesh.layerMask;
  16865. return serializationObject;
  16866. };
  16867. var SceneSerializer = (function () {
  16868. function SceneSerializer() {
  16869. }
  16870. SceneSerializer.Serialize = function (scene) {
  16871. var serializationObject = {};
  16872. // Scene
  16873. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  16874. serializationObject.autoClear = scene.autoClear;
  16875. serializationObject.clearColor = scene.clearColor.asArray();
  16876. serializationObject.ambientColor = scene.ambientColor.asArray();
  16877. serializationObject.gravity = scene.gravity.asArray();
  16878. // Fog
  16879. if (scene.fogMode && scene.fogMode !== 0) {
  16880. serializationObject.fogMode = scene.fogMode;
  16881. serializationObject.fogColor = scene.fogColor.asArray();
  16882. serializationObject.fogStart = scene.fogStart;
  16883. serializationObject.fogEnd = scene.fogEnd;
  16884. serializationObject.fogDensity = scene.fogDensity;
  16885. }
  16886. // Lights
  16887. serializationObject.lights = [];
  16888. for (var index = 0; index < scene.lights.length; index++) {
  16889. var light = scene.lights[index];
  16890. serializationObject.lights.push(serializeLight(light));
  16891. }
  16892. // Cameras
  16893. serializationObject.cameras = [];
  16894. for (index = 0; index < scene.cameras.length; index++) {
  16895. var camera = scene.cameras[index];
  16896. if (camera instanceof BABYLON.FreeCamera) {
  16897. serializationObject.cameras.push(serializeCamera(camera));
  16898. }
  16899. }
  16900. if (scene.activeCamera) {
  16901. serializationObject.activeCameraID = scene.activeCamera.id;
  16902. }
  16903. // Materials
  16904. serializationObject.materials = [];
  16905. serializationObject.multiMaterials = [];
  16906. for (index = 0; index < scene.materials.length; index++) {
  16907. var material = scene.materials[index];
  16908. if (material instanceof BABYLON.StandardMaterial) {
  16909. serializationObject.materials.push(serializeMaterial(material));
  16910. } else if (material instanceof BABYLON.MultiMaterial) {
  16911. serializationObject.multiMaterials.push(serializeMultiMaterial(material));
  16912. }
  16913. }
  16914. // Skeletons
  16915. serializationObject.skeletons = [];
  16916. for (index = 0; index < scene.skeletons.length; index++) {
  16917. serializationObject.skeletons.push(serializeSkeleton(scene.skeletons[index]));
  16918. }
  16919. // Geometries
  16920. serializationObject.geometries = {};
  16921. serializationObject.geometries.boxes = [];
  16922. serializationObject.geometries.spheres = [];
  16923. serializationObject.geometries.cylinders = [];
  16924. serializationObject.geometries.toruses = [];
  16925. serializationObject.geometries.grounds = [];
  16926. serializationObject.geometries.planes = [];
  16927. serializationObject.geometries.torusKnots = [];
  16928. serializationObject.geometries.vertexData = [];
  16929. serializedGeometries = [];
  16930. var geometries = scene.getGeometries();
  16931. for (var index = 0; index < geometries.length; index++) {
  16932. var geometry = geometries[index];
  16933. if (geometry.isReady()) {
  16934. serializeGeometry(geometry, serializationObject.geometries);
  16935. }
  16936. }
  16937. // Meshes
  16938. serializationObject.meshes = [];
  16939. for (index = 0; index < scene.meshes.length; index++) {
  16940. var abstractMesh = scene.meshes[index];
  16941. if (abstractMesh instanceof BABYLON.Mesh) {
  16942. var mesh = abstractMesh;
  16943. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  16944. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  16945. }
  16946. }
  16947. }
  16948. // Particles Systems
  16949. serializationObject.particleSystems = [];
  16950. for (index = 0; index < scene.particleSystems.length; index++) {
  16951. serializationObject.particleSystems.push(serializeParticleSystem(scene.particleSystems[index]));
  16952. }
  16953. // Lens flares
  16954. serializationObject.lensFlareSystems = [];
  16955. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  16956. serializationObject.lensFlareSystems.push(serializeLensFlareSystem(scene.lensFlareSystems[index]));
  16957. }
  16958. // Shadows
  16959. serializationObject.shadowGenerators = [];
  16960. for (index = 0; index < scene.lights.length; index++) {
  16961. light = scene.lights[index];
  16962. if (light.getShadowGenerator()) {
  16963. serializationObject.shadowGenerators.push(serializeShadowGenerator(light));
  16964. }
  16965. }
  16966. return serializationObject;
  16967. };
  16968. return SceneSerializer;
  16969. })();
  16970. BABYLON.SceneSerializer = SceneSerializer;
  16971. })(BABYLON || (BABYLON = {}));
  16972. //# sourceMappingURL=babylon.sceneSerializer.js.map
  16973. var BABYLON;
  16974. (function (BABYLON) {
  16975. var SceneLoader = (function () {
  16976. function SceneLoader() {
  16977. }
  16978. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  16979. get: function () {
  16980. return SceneLoader._ForceFullSceneLoadingForIncremental;
  16981. },
  16982. set: function (value) {
  16983. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  16984. },
  16985. enumerable: true,
  16986. configurable: true
  16987. });
  16988. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  16989. get: function () {
  16990. return SceneLoader._ShowLoadingScreen;
  16991. },
  16992. set: function (value) {
  16993. SceneLoader._ShowLoadingScreen = value;
  16994. },
  16995. enumerable: true,
  16996. configurable: true
  16997. });
  16998. SceneLoader._getPluginForFilename = function (sceneFilename) {
  16999. var dotPosition = sceneFilename.lastIndexOf(".");
  17000. var queryStringPosition = sceneFilename.indexOf("?");
  17001. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  17002. for (var index = 0; index < this._registeredPlugins.length; index++) {
  17003. var plugin = this._registeredPlugins[index];
  17004. if (plugin.extensions.indexOf(extension) !== -1) {
  17005. return plugin;
  17006. }
  17007. }
  17008. return this._registeredPlugins[this._registeredPlugins.length - 1];
  17009. };
  17010. // Public functions
  17011. SceneLoader.RegisterPlugin = function (plugin) {
  17012. plugin.extensions = plugin.extensions.toLowerCase();
  17013. SceneLoader._registeredPlugins.push(plugin);
  17014. };
  17015. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  17016. var manifestChecked = function (success) {
  17017. scene.database = database;
  17018. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  17019. var importMeshFromData = function (data) {
  17020. var meshes = [];
  17021. var particleSystems = [];
  17022. var skeletons = [];
  17023. try {
  17024. if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  17025. if (onerror) {
  17026. onerror(scene, 'unable to load the scene');
  17027. }
  17028. return;
  17029. }
  17030. } catch (e) {
  17031. if (onerror) {
  17032. onerror(scene, e);
  17033. }
  17034. return;
  17035. }
  17036. if (onsuccess) {
  17037. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  17038. onsuccess(meshes, particleSystems, skeletons);
  17039. }
  17040. };
  17041. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  17042. // Direct load
  17043. importMeshFromData(sceneFilename.substr(5));
  17044. return;
  17045. }
  17046. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  17047. importMeshFromData(data);
  17048. }, progressCallBack, database);
  17049. };
  17050. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  17051. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  17052. };
  17053. /**
  17054. * Load a scene
  17055. * @param rootUrl a string that defines the root url for scene and resources
  17056. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  17057. * @param engine is the instance of BABYLON.Engine to use to create the scene
  17058. */
  17059. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  17060. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  17061. };
  17062. /**
  17063. * Append a scene
  17064. * @param rootUrl a string that defines the root url for scene and resources
  17065. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  17066. * @param scene is the instance of BABYLON.Scene to append to
  17067. */
  17068. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  17069. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  17070. var database;
  17071. if (SceneLoader.ShowLoadingScreen) {
  17072. scene.getEngine().displayLoadingUI();
  17073. }
  17074. var loadSceneFromData = function (data) {
  17075. scene.database = database;
  17076. if (!plugin.load(scene, data, rootUrl)) {
  17077. if (onerror) {
  17078. onerror(scene);
  17079. }
  17080. scene.getEngine().hideLoadingUI();
  17081. return;
  17082. }
  17083. if (onsuccess) {
  17084. onsuccess(scene);
  17085. }
  17086. if (SceneLoader.ShowLoadingScreen) {
  17087. scene.executeWhenReady(function () {
  17088. scene.getEngine().hideLoadingUI();
  17089. });
  17090. }
  17091. };
  17092. var manifestChecked = function (success) {
  17093. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  17094. };
  17095. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  17096. // Direct load
  17097. loadSceneFromData(sceneFilename.substr(5));
  17098. return;
  17099. }
  17100. if (rootUrl.indexOf("file:") === -1) {
  17101. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  17102. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  17103. } else {
  17104. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  17105. }
  17106. };
  17107. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  17108. SceneLoader._ShowLoadingScreen = true;
  17109. SceneLoader._registeredPlugins = new Array();
  17110. return SceneLoader;
  17111. })();
  17112. BABYLON.SceneLoader = SceneLoader;
  17113. ;
  17114. })(BABYLON || (BABYLON = {}));
  17115. //# sourceMappingURL=babylon.sceneLoader.js.map
  17116. var BABYLON;
  17117. (function (BABYLON) {
  17118. (function (Internals) {
  17119. var checkColors4 = function (colors, count) {
  17120. // Check if color3 was used
  17121. if (colors.length === count * 3) {
  17122. var colors4 = [];
  17123. for (var index = 0; index < colors.length; index += 3) {
  17124. var newIndex = (index / 3) * 4;
  17125. colors4[newIndex] = colors[index];
  17126. colors4[newIndex + 1] = colors[index + 1];
  17127. colors4[newIndex + 2] = colors[index + 2];
  17128. colors4[newIndex + 3] = 1.0;
  17129. }
  17130. return colors4;
  17131. }
  17132. return colors;
  17133. };
  17134. var loadCubeTexture = function (rootUrl, parsedTexture, scene) {
  17135. var texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene);
  17136. texture.name = parsedTexture.name;
  17137. texture.hasAlpha = parsedTexture.hasAlpha;
  17138. texture.level = parsedTexture.level;
  17139. texture.coordinatesMode = parsedTexture.coordinatesMode;
  17140. return texture;
  17141. };
  17142. var loadTexture = function (rootUrl, parsedTexture, scene) {
  17143. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  17144. return null;
  17145. }
  17146. if (parsedTexture.isCube) {
  17147. return loadCubeTexture(rootUrl, parsedTexture, scene);
  17148. }
  17149. var texture;
  17150. if (parsedTexture.mirrorPlane) {
  17151. texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  17152. texture._waitingRenderList = parsedTexture.renderList;
  17153. texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  17154. } else if (parsedTexture.isRenderTarget) {
  17155. texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  17156. texture._waitingRenderList = parsedTexture.renderList;
  17157. } else {
  17158. texture = new BABYLON.Texture(rootUrl + parsedTexture.name, scene);
  17159. }
  17160. texture.name = parsedTexture.name;
  17161. texture.hasAlpha = parsedTexture.hasAlpha;
  17162. texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
  17163. texture.level = parsedTexture.level;
  17164. texture.coordinatesIndex = parsedTexture.coordinatesIndex;
  17165. texture.coordinatesMode = parsedTexture.coordinatesMode;
  17166. texture.uOffset = parsedTexture.uOffset;
  17167. texture.vOffset = parsedTexture.vOffset;
  17168. texture.uScale = parsedTexture.uScale;
  17169. texture.vScale = parsedTexture.vScale;
  17170. texture.uAng = parsedTexture.uAng;
  17171. texture.vAng = parsedTexture.vAng;
  17172. texture.wAng = parsedTexture.wAng;
  17173. texture.wrapU = parsedTexture.wrapU;
  17174. texture.wrapV = parsedTexture.wrapV;
  17175. // Animations
  17176. if (parsedTexture.animations) {
  17177. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  17178. var parsedAnimation = parsedTexture.animations[animationIndex];
  17179. texture.animations.push(parseAnimation(parsedAnimation));
  17180. }
  17181. }
  17182. return texture;
  17183. };
  17184. var parseSkeleton = function (parsedSkeleton, scene) {
  17185. var skeleton = new BABYLON.Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  17186. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  17187. var parsedBone = parsedSkeleton.bones[index];
  17188. var parentBone = null;
  17189. if (parsedBone.parentBoneIndex > -1) {
  17190. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  17191. }
  17192. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix));
  17193. if (parsedBone.animation) {
  17194. bone.animations.push(parseAnimation(parsedBone.animation));
  17195. }
  17196. }
  17197. return skeleton;
  17198. };
  17199. var parseFresnelParameters = function (parsedFresnelParameters) {
  17200. var fresnelParameters = new BABYLON.FresnelParameters();
  17201. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  17202. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  17203. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  17204. fresnelParameters.bias = parsedFresnelParameters.bias;
  17205. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  17206. return fresnelParameters;
  17207. };
  17208. var parseMaterial = function (parsedMaterial, scene, rootUrl) {
  17209. var material;
  17210. material = new BABYLON.StandardMaterial(parsedMaterial.name, scene);
  17211. material.ambientColor = BABYLON.Color3.FromArray(parsedMaterial.ambient);
  17212. material.diffuseColor = BABYLON.Color3.FromArray(parsedMaterial.diffuse);
  17213. material.specularColor = BABYLON.Color3.FromArray(parsedMaterial.specular);
  17214. material.specularPower = parsedMaterial.specularPower;
  17215. material.emissiveColor = BABYLON.Color3.FromArray(parsedMaterial.emissive);
  17216. material.alpha = parsedMaterial.alpha;
  17217. material.id = parsedMaterial.id;
  17218. BABYLON.Tags.AddTagsTo(material, parsedMaterial.tags);
  17219. material.backFaceCulling = parsedMaterial.backFaceCulling;
  17220. material.wireframe = parsedMaterial.wireframe;
  17221. if (parsedMaterial.diffuseTexture) {
  17222. material.diffuseTexture = loadTexture(rootUrl, parsedMaterial.diffuseTexture, scene);
  17223. }
  17224. if (parsedMaterial.diffuseFresnelParameters) {
  17225. material.diffuseFresnelParameters = parseFresnelParameters(parsedMaterial.diffuseFresnelParameters);
  17226. }
  17227. if (parsedMaterial.ambientTexture) {
  17228. material.ambientTexture = loadTexture(rootUrl, parsedMaterial.ambientTexture, scene);
  17229. }
  17230. if (parsedMaterial.opacityTexture) {
  17231. material.opacityTexture = loadTexture(rootUrl, parsedMaterial.opacityTexture, scene);
  17232. }
  17233. if (parsedMaterial.opacityFresnelParameters) {
  17234. material.opacityFresnelParameters = parseFresnelParameters(parsedMaterial.opacityFresnelParameters);
  17235. }
  17236. if (parsedMaterial.reflectionTexture) {
  17237. material.reflectionTexture = loadTexture(rootUrl, parsedMaterial.reflectionTexture, scene);
  17238. }
  17239. if (parsedMaterial.reflectionFresnelParameters) {
  17240. material.reflectionFresnelParameters = parseFresnelParameters(parsedMaterial.reflectionFresnelParameters);
  17241. }
  17242. if (parsedMaterial.emissiveTexture) {
  17243. material.emissiveTexture = loadTexture(rootUrl, parsedMaterial.emissiveTexture, scene);
  17244. }
  17245. if (parsedMaterial.emissiveFresnelParameters) {
  17246. material.emissiveFresnelParameters = parseFresnelParameters(parsedMaterial.emissiveFresnelParameters);
  17247. }
  17248. if (parsedMaterial.specularTexture) {
  17249. material.specularTexture = loadTexture(rootUrl, parsedMaterial.specularTexture, scene);
  17250. }
  17251. if (parsedMaterial.bumpTexture) {
  17252. material.bumpTexture = loadTexture(rootUrl, parsedMaterial.bumpTexture, scene);
  17253. }
  17254. return material;
  17255. };
  17256. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  17257. for (var index = 0; index < parsedData.materials.length; index++) {
  17258. var parsedMaterial = parsedData.materials[index];
  17259. if (parsedMaterial.id === id) {
  17260. return parseMaterial(parsedMaterial, scene, rootUrl);
  17261. }
  17262. }
  17263. return null;
  17264. };
  17265. var parseMultiMaterial = function (parsedMultiMaterial, scene) {
  17266. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  17267. multiMaterial.id = parsedMultiMaterial.id;
  17268. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  17269. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  17270. var subMatId = parsedMultiMaterial.materials[matIndex];
  17271. if (subMatId) {
  17272. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  17273. } else {
  17274. multiMaterial.subMaterials.push(null);
  17275. }
  17276. }
  17277. return multiMaterial;
  17278. };
  17279. var parseLensFlareSystem = function (parsedLensFlareSystem, scene, rootUrl) {
  17280. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  17281. var lensFlareSystem = new BABYLON.LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  17282. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  17283. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  17284. var parsedFlare = parsedLensFlareSystem.flares[index];
  17285. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  17286. }
  17287. return lensFlareSystem;
  17288. };
  17289. var parseParticleSystem = function (parsedParticleSystem, scene, rootUrl) {
  17290. var emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  17291. var particleSystem = new BABYLON.ParticleSystem("particles#" + emitter.name, parsedParticleSystem.capacity, scene);
  17292. if (parsedParticleSystem.textureName) {
  17293. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  17294. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  17295. }
  17296. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  17297. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  17298. particleSystem.minSize = parsedParticleSystem.minSize;
  17299. particleSystem.maxSize = parsedParticleSystem.maxSize;
  17300. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  17301. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  17302. particleSystem.emitter = emitter;
  17303. particleSystem.emitRate = parsedParticleSystem.emitRate;
  17304. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  17305. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  17306. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  17307. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  17308. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  17309. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  17310. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  17311. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  17312. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  17313. particleSystem.targetStopDuration = parsedParticleSystem.targetStopFrame;
  17314. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  17315. particleSystem.blendMode = parsedParticleSystem.blendMode;
  17316. particleSystem.start();
  17317. return particleSystem;
  17318. };
  17319. var parseShadowGenerator = function (parsedShadowGenerator, scene) {
  17320. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  17321. var shadowGenerator = new BABYLON.ShadowGenerator(parsedShadowGenerator.mapSize, light);
  17322. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  17323. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  17324. shadowGenerator.getShadowMap().renderList.push(mesh);
  17325. }
  17326. if (parsedShadowGenerator.usePoissonSampling) {
  17327. shadowGenerator.usePoissonSampling = true;
  17328. } else {
  17329. shadowGenerator.useVarianceShadowMap = parsedShadowGenerator.useVarianceShadowMap;
  17330. }
  17331. return shadowGenerator;
  17332. };
  17333. var parseAnimation = function (parsedAnimation) {
  17334. var animation = new BABYLON.Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  17335. var dataType = parsedAnimation.dataType;
  17336. var keys = [];
  17337. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  17338. var key = parsedAnimation.keys[index];
  17339. var data;
  17340. switch (dataType) {
  17341. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  17342. data = key.values[0];
  17343. break;
  17344. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  17345. data = BABYLON.Quaternion.FromArray(key.values);
  17346. break;
  17347. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  17348. data = BABYLON.Matrix.FromArray(key.values);
  17349. break;
  17350. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  17351. default:
  17352. data = BABYLON.Vector3.FromArray(key.values);
  17353. break;
  17354. }
  17355. keys.push({
  17356. frame: key.frame,
  17357. value: data
  17358. });
  17359. }
  17360. animation.setKeys(keys);
  17361. return animation;
  17362. };
  17363. var parseLight = function (parsedLight, scene) {
  17364. var light;
  17365. switch (parsedLight.type) {
  17366. case 0:
  17367. light = new BABYLON.PointLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), scene);
  17368. break;
  17369. case 1:
  17370. light = new BABYLON.DirectionalLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  17371. light.position = BABYLON.Vector3.FromArray(parsedLight.position);
  17372. break;
  17373. case 2:
  17374. light = new BABYLON.SpotLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), BABYLON.Vector3.FromArray(parsedLight.direction), parsedLight.angle, parsedLight.exponent, scene);
  17375. break;
  17376. case 3:
  17377. light = new BABYLON.HemisphericLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  17378. light.groundColor = BABYLON.Color3.FromArray(parsedLight.groundColor);
  17379. break;
  17380. }
  17381. light.id = parsedLight.id;
  17382. BABYLON.Tags.AddTagsTo(light, parsedLight.tags);
  17383. if (parsedLight.intensity !== undefined) {
  17384. light.intensity = parsedLight.intensity;
  17385. }
  17386. if (parsedLight.range) {
  17387. light.range = parsedLight.range;
  17388. }
  17389. light.diffuse = BABYLON.Color3.FromArray(parsedLight.diffuse);
  17390. light.specular = BABYLON.Color3.FromArray(parsedLight.specular);
  17391. if (parsedLight.excludedMeshesIds) {
  17392. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  17393. }
  17394. // Parent
  17395. if (parsedLight.parentId) {
  17396. light._waitingParentId = parsedLight.parentId;
  17397. }
  17398. if (parsedLight.includedOnlyMeshesIds) {
  17399. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  17400. }
  17401. // Animations
  17402. if (parsedLight.animations) {
  17403. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  17404. var parsedAnimation = parsedLight.animations[animationIndex];
  17405. light.animations.push(parseAnimation(parsedAnimation));
  17406. }
  17407. }
  17408. if (parsedLight.autoAnimate) {
  17409. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, 1.0);
  17410. }
  17411. };
  17412. var parseCamera = function (parsedCamera, scene) {
  17413. var camera;
  17414. var position = BABYLON.Vector3.FromArray(parsedCamera.position);
  17415. var lockedTargetMesh = (parsedCamera.lockedTargetId) ? scene.getLastMeshByID(parsedCamera.lockedTargetId) : null;
  17416. if (parsedCamera.type === "AnaglyphArcRotateCamera" || parsedCamera.type === "ArcRotateCamera") {
  17417. var alpha = parsedCamera.alpha;
  17418. var beta = parsedCamera.beta;
  17419. var radius = parsedCamera.radius;
  17420. if (parsedCamera.type === "AnaglyphArcRotateCamera") {
  17421. var eye_space = parsedCamera.eye_space;
  17422. camera = new BABYLON.AnaglyphArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, eye_space, scene);
  17423. } else {
  17424. camera = new BABYLON.ArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, scene);
  17425. }
  17426. } else if (parsedCamera.type === "AnaglyphFreeCamera") {
  17427. var eye_space = parsedCamera.eye_space;
  17428. camera = new BABYLON.AnaglyphFreeCamera(parsedCamera.name, position, eye_space, scene);
  17429. } else if (parsedCamera.type === "DeviceOrientationCamera") {
  17430. camera = new BABYLON.DeviceOrientationCamera(parsedCamera.name, position, scene);
  17431. } else if (parsedCamera.type === "FollowCamera") {
  17432. camera = new BABYLON.FollowCamera(parsedCamera.name, position, scene);
  17433. camera.heightOffset = parsedCamera.heightOffset;
  17434. camera.radius = parsedCamera.radius;
  17435. camera.rotationOffset = parsedCamera.rotationOffset;
  17436. if (lockedTargetMesh)
  17437. camera.target = lockedTargetMesh;
  17438. } else if (parsedCamera.type === "GamepadCamera") {
  17439. camera = new BABYLON.GamepadCamera(parsedCamera.name, position, scene);
  17440. } else if (parsedCamera.type === "OculusCamera") {
  17441. camera = new BABYLON.OculusCamera(parsedCamera.name, position, scene);
  17442. } else if (parsedCamera.type === "OculusGamepadCamera") {
  17443. camera = new BABYLON.OculusGamepadCamera(parsedCamera.name, position, scene);
  17444. } else if (parsedCamera.type === "TouchCamera") {
  17445. camera = new BABYLON.TouchCamera(parsedCamera.name, position, scene);
  17446. } else if (parsedCamera.type === "VirtualJoysticksCamera") {
  17447. camera = new BABYLON.VirtualJoysticksCamera(parsedCamera.name, position, scene);
  17448. } else if (parsedCamera.type === "WebVRCamera") {
  17449. camera = new BABYLON.WebVRCamera(parsedCamera.name, position, scene);
  17450. } else if (parsedCamera.type === "VRDeviceOrientationCamera") {
  17451. camera = new BABYLON.VRDeviceOrientationCamera(parsedCamera.name, position, scene);
  17452. } else {
  17453. // Free Camera is the default value
  17454. camera = new BABYLON.FreeCamera(parsedCamera.name, position, scene);
  17455. }
  17456. // Test for lockedTargetMesh & FreeCamera outside of if-else-if nest, since things like GamepadCamera extend FreeCamera
  17457. if (lockedTargetMesh && camera instanceof BABYLON.FreeCamera) {
  17458. camera.lockedTarget = lockedTargetMesh;
  17459. }
  17460. camera.id = parsedCamera.id;
  17461. BABYLON.Tags.AddTagsTo(camera, parsedCamera.tags);
  17462. // Parent
  17463. if (parsedCamera.parentId) {
  17464. camera._waitingParentId = parsedCamera.parentId;
  17465. }
  17466. // Target
  17467. if (parsedCamera.target) {
  17468. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  17469. } else {
  17470. camera.rotation = BABYLON.Vector3.FromArray(parsedCamera.rotation);
  17471. }
  17472. camera.fov = parsedCamera.fov;
  17473. camera.minZ = parsedCamera.minZ;
  17474. camera.maxZ = parsedCamera.maxZ;
  17475. camera.speed = parsedCamera.speed;
  17476. camera.inertia = parsedCamera.inertia;
  17477. camera.checkCollisions = parsedCamera.checkCollisions;
  17478. camera.applyGravity = parsedCamera.applyGravity;
  17479. if (parsedCamera.ellipsoid) {
  17480. camera.ellipsoid = BABYLON.Vector3.FromArray(parsedCamera.ellipsoid);
  17481. }
  17482. // Animations
  17483. if (parsedCamera.animations) {
  17484. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  17485. var parsedAnimation = parsedCamera.animations[animationIndex];
  17486. camera.animations.push(parseAnimation(parsedAnimation));
  17487. }
  17488. }
  17489. if (parsedCamera.autoAnimate) {
  17490. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, 1.0);
  17491. }
  17492. // Layer Mask
  17493. if (parsedCamera.layerMask && (!isNaN(parsedCamera.layerMask))) {
  17494. camera.layerMask = Math.abs(parseInt(parsedCamera.layerMask));
  17495. } else {
  17496. camera.layerMask = 0xFFFFFFFF;
  17497. }
  17498. return camera;
  17499. };
  17500. var parseGeometry = function (parsedGeometry, scene) {
  17501. var id = parsedGeometry.id;
  17502. return scene.getGeometryByID(id);
  17503. };
  17504. var parseBox = function (parsedBox, scene) {
  17505. if (parseGeometry(parsedBox, scene)) {
  17506. return null;
  17507. }
  17508. var box = new BABYLON.Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  17509. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  17510. scene.pushGeometry(box, true);
  17511. return box;
  17512. };
  17513. var parseSphere = function (parsedSphere, scene) {
  17514. if (parseGeometry(parsedSphere, scene)) {
  17515. return null;
  17516. }
  17517. var sphere = new BABYLON.Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  17518. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  17519. scene.pushGeometry(sphere, true);
  17520. return sphere;
  17521. };
  17522. var parseCylinder = function (parsedCylinder, scene) {
  17523. if (parseGeometry(parsedCylinder, scene)) {
  17524. return null;
  17525. }
  17526. var cylinder = new BABYLON.Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  17527. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  17528. scene.pushGeometry(cylinder, true);
  17529. return cylinder;
  17530. };
  17531. var parseTorus = function (parsedTorus, scene) {
  17532. if (parseGeometry(parsedTorus, scene)) {
  17533. return null;
  17534. }
  17535. var torus = new BABYLON.Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  17536. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  17537. scene.pushGeometry(torus, true);
  17538. return torus;
  17539. };
  17540. var parseGround = function (parsedGround, scene) {
  17541. if (parseGeometry(parsedGround, scene)) {
  17542. return null;
  17543. }
  17544. var ground = new BABYLON.Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  17545. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  17546. scene.pushGeometry(ground, true);
  17547. return ground;
  17548. };
  17549. var parsePlane = function (parsedPlane, scene) {
  17550. if (parseGeometry(parsedPlane, scene)) {
  17551. return null;
  17552. }
  17553. var plane = new BABYLON.Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  17554. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  17555. scene.pushGeometry(plane, true);
  17556. return plane;
  17557. };
  17558. var parseTorusKnot = function (parsedTorusKnot, scene) {
  17559. if (parseGeometry(parsedTorusKnot, scene)) {
  17560. return null;
  17561. }
  17562. 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);
  17563. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  17564. scene.pushGeometry(torusKnot, true);
  17565. return torusKnot;
  17566. };
  17567. var parseVertexData = function (parsedVertexData, scene, rootUrl) {
  17568. if (parseGeometry(parsedVertexData, scene)) {
  17569. return null;
  17570. }
  17571. var geometry = new BABYLON.Geometry(parsedVertexData.id, scene);
  17572. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  17573. if (parsedVertexData.delayLoadingFile) {
  17574. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  17575. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  17576. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  17577. geometry._delayInfo = [];
  17578. if (parsedVertexData.hasUVs) {
  17579. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  17580. }
  17581. if (parsedVertexData.hasUVs2) {
  17582. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  17583. }
  17584. if (parsedVertexData.hasColors) {
  17585. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  17586. }
  17587. if (parsedVertexData.hasMatricesIndices) {
  17588. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  17589. }
  17590. if (parsedVertexData.hasMatricesWeights) {
  17591. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  17592. }
  17593. geometry._delayLoadingFunction = importVertexData;
  17594. } else {
  17595. importVertexData(parsedVertexData, geometry);
  17596. }
  17597. scene.pushGeometry(geometry, true);
  17598. return geometry;
  17599. };
  17600. var parseMesh = function (parsedMesh, scene, rootUrl) {
  17601. var mesh = new BABYLON.Mesh(parsedMesh.name, scene);
  17602. mesh.id = parsedMesh.id;
  17603. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  17604. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  17605. if (parsedMesh.rotationQuaternion) {
  17606. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  17607. } else if (parsedMesh.rotation) {
  17608. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  17609. }
  17610. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  17611. if (parsedMesh.localMatrix) {
  17612. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  17613. } else if (parsedMesh.pivotMatrix) {
  17614. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  17615. }
  17616. mesh.setEnabled(parsedMesh.isEnabled);
  17617. mesh.isVisible = parsedMesh.isVisible;
  17618. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  17619. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  17620. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  17621. if (parsedMesh.applyFog !== undefined) {
  17622. mesh.applyFog = parsedMesh.applyFog;
  17623. }
  17624. if (parsedMesh.pickable !== undefined) {
  17625. mesh.isPickable = parsedMesh.pickable;
  17626. }
  17627. if (parsedMesh.alphaIndex !== undefined) {
  17628. mesh.alphaIndex = parsedMesh.alphaIndex;
  17629. }
  17630. mesh.receiveShadows = parsedMesh.receiveShadows;
  17631. mesh.billboardMode = parsedMesh.billboardMode;
  17632. if (parsedMesh.visibility !== undefined) {
  17633. mesh.visibility = parsedMesh.visibility;
  17634. }
  17635. mesh.checkCollisions = parsedMesh.checkCollisions;
  17636. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  17637. // Parent
  17638. if (parsedMesh.parentId) {
  17639. mesh._waitingParentId = parsedMesh.parentId;
  17640. }
  17641. // Geometry
  17642. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  17643. if (parsedMesh.delayLoadingFile) {
  17644. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  17645. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  17646. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  17647. if (parsedMesh._binaryInfo) {
  17648. mesh._binaryInfo = parsedMesh._binaryInfo;
  17649. }
  17650. mesh._delayInfo = [];
  17651. if (parsedMesh.hasUVs) {
  17652. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  17653. }
  17654. if (parsedMesh.hasUVs2) {
  17655. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  17656. }
  17657. if (parsedMesh.hasColors) {
  17658. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  17659. }
  17660. if (parsedMesh.hasMatricesIndices) {
  17661. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  17662. }
  17663. if (parsedMesh.hasMatricesWeights) {
  17664. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  17665. }
  17666. mesh._delayLoadingFunction = importGeometry;
  17667. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  17668. mesh._checkDelayState();
  17669. }
  17670. } else {
  17671. importGeometry(parsedMesh, mesh);
  17672. }
  17673. // Material
  17674. if (parsedMesh.materialId) {
  17675. mesh.setMaterialByID(parsedMesh.materialId);
  17676. } else {
  17677. mesh.material = null;
  17678. }
  17679. // Skeleton
  17680. if (parsedMesh.skeletonId > -1) {
  17681. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  17682. }
  17683. // Physics
  17684. if (parsedMesh.physicsImpostor) {
  17685. if (!scene.isPhysicsEnabled()) {
  17686. scene.enablePhysics();
  17687. }
  17688. mesh.setPhysicsState({ impostor: parsedMesh.physicsImpostor, mass: parsedMesh.physicsMass, friction: parsedMesh.physicsFriction, restitution: parsedMesh.physicsRestitution });
  17689. }
  17690. // Animations
  17691. if (parsedMesh.animations) {
  17692. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  17693. var parsedAnimation = parsedMesh.animations[animationIndex];
  17694. mesh.animations.push(parseAnimation(parsedAnimation));
  17695. }
  17696. }
  17697. if (parsedMesh.autoAnimate) {
  17698. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, 1.0);
  17699. }
  17700. // Layer Mask
  17701. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  17702. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  17703. } else {
  17704. mesh.layerMask = 0xFFFFFFFF;
  17705. }
  17706. // Instances
  17707. if (parsedMesh.instances) {
  17708. for (var index = 0; index < parsedMesh.instances.length; index++) {
  17709. var parsedInstance = parsedMesh.instances[index];
  17710. var instance = mesh.createInstance(parsedInstance.name);
  17711. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  17712. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  17713. if (parsedInstance.rotationQuaternion) {
  17714. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  17715. } else if (parsedInstance.rotation) {
  17716. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  17717. }
  17718. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  17719. instance.checkCollisions = mesh.checkCollisions;
  17720. if (parsedMesh.animations) {
  17721. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  17722. parsedAnimation = parsedMesh.animations[animationIndex];
  17723. instance.animations.push(parseAnimation(parsedAnimation));
  17724. }
  17725. }
  17726. }
  17727. }
  17728. return mesh;
  17729. };
  17730. var isDescendantOf = function (mesh, names, hierarchyIds) {
  17731. names = (names instanceof Array) ? names : [names];
  17732. for (var i in names) {
  17733. if (mesh.name === names[i]) {
  17734. hierarchyIds.push(mesh.id);
  17735. return true;
  17736. }
  17737. }
  17738. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  17739. hierarchyIds.push(mesh.id);
  17740. return true;
  17741. }
  17742. return false;
  17743. };
  17744. var importVertexData = function (parsedVertexData, geometry) {
  17745. var vertexData = new BABYLON.VertexData();
  17746. // positions
  17747. var positions = parsedVertexData.positions;
  17748. if (positions) {
  17749. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  17750. }
  17751. // normals
  17752. var normals = parsedVertexData.normals;
  17753. if (normals) {
  17754. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  17755. }
  17756. // uvs
  17757. var uvs = parsedVertexData.uvs;
  17758. if (uvs) {
  17759. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  17760. }
  17761. // uv2s
  17762. var uv2s = parsedVertexData.uv2s;
  17763. if (uv2s) {
  17764. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  17765. }
  17766. // colors
  17767. var colors = parsedVertexData.colors;
  17768. if (colors) {
  17769. vertexData.set(checkColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  17770. }
  17771. // matricesIndices
  17772. var matricesIndices = parsedVertexData.matricesIndices;
  17773. if (matricesIndices) {
  17774. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  17775. }
  17776. // matricesWeights
  17777. var matricesWeights = parsedVertexData.matricesWeights;
  17778. if (matricesWeights) {
  17779. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  17780. }
  17781. // indices
  17782. var indices = parsedVertexData.indices;
  17783. if (indices) {
  17784. vertexData.indices = indices;
  17785. }
  17786. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  17787. };
  17788. var importGeometry = function (parsedGeometry, mesh) {
  17789. var scene = mesh.getScene();
  17790. // Geometry
  17791. var geometryId = parsedGeometry.geometryId;
  17792. if (geometryId) {
  17793. var geometry = scene.getGeometryByID(geometryId);
  17794. if (geometry) {
  17795. geometry.applyToMesh(mesh);
  17796. }
  17797. } else if (parsedGeometry instanceof ArrayBuffer) {
  17798. var binaryInfo = mesh._binaryInfo;
  17799. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  17800. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  17801. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  17802. }
  17803. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  17804. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  17805. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  17806. }
  17807. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  17808. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  17809. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  17810. }
  17811. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  17812. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  17813. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  17814. }
  17815. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  17816. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  17817. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false);
  17818. }
  17819. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  17820. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  17821. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  17822. }
  17823. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  17824. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  17825. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  17826. }
  17827. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  17828. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  17829. mesh.setIndices(indicesData);
  17830. }
  17831. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  17832. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  17833. mesh.subMeshes = [];
  17834. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  17835. var materialIndex = subMeshesData[(i * 5) + 0];
  17836. var verticesStart = subMeshesData[(i * 5) + 1];
  17837. var verticesCount = subMeshesData[(i * 5) + 2];
  17838. var indexStart = subMeshesData[(i * 5) + 3];
  17839. var indexCount = subMeshesData[(i * 5) + 4];
  17840. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  17841. }
  17842. }
  17843. } else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  17844. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  17845. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  17846. if (parsedGeometry.uvs) {
  17847. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  17848. }
  17849. if (parsedGeometry.uvs2) {
  17850. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  17851. }
  17852. if (parsedGeometry.colors) {
  17853. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, checkColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  17854. }
  17855. if (parsedGeometry.matricesIndices) {
  17856. if (!parsedGeometry.matricesIndices._isExpanded) {
  17857. var floatIndices = [];
  17858. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  17859. var matricesIndex = parsedGeometry.matricesIndices[i];
  17860. floatIndices.push(matricesIndex & 0x000000FF);
  17861. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  17862. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  17863. floatIndices.push(matricesIndex >> 24);
  17864. }
  17865. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  17866. } else {
  17867. delete parsedGeometry.matricesIndices._isExpanded;
  17868. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  17869. }
  17870. }
  17871. if (parsedGeometry.matricesWeights) {
  17872. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  17873. }
  17874. mesh.setIndices(parsedGeometry.indices);
  17875. // SubMeshes
  17876. if (parsedGeometry.subMeshes) {
  17877. mesh.subMeshes = [];
  17878. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  17879. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  17880. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  17881. }
  17882. }
  17883. }
  17884. // Flat shading
  17885. if (mesh._shouldGenerateFlatShading) {
  17886. mesh.convertToFlatShadedMesh();
  17887. delete mesh._shouldGenerateFlatShading;
  17888. }
  17889. // Update
  17890. mesh.computeWorldMatrix(true);
  17891. // Octree
  17892. if (scene._selectionOctree) {
  17893. scene._selectionOctree.addMesh(mesh);
  17894. }
  17895. };
  17896. BABYLON.SceneLoader.RegisterPlugin({
  17897. extensions: ".babylon",
  17898. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  17899. var parsedData = JSON.parse(data);
  17900. var loadedSkeletonsIds = [];
  17901. var loadedMaterialsIds = [];
  17902. var hierarchyIds = [];
  17903. for (var index = 0; index < parsedData.meshes.length; index++) {
  17904. var parsedMesh = parsedData.meshes[index];
  17905. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  17906. if (meshesNames instanceof Array) {
  17907. // Remove found mesh name from list.
  17908. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  17909. }
  17910. // Material ?
  17911. if (parsedMesh.materialId) {
  17912. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  17913. if (!materialFound) {
  17914. for (var multimatIndex = 0; multimatIndex < parsedData.multiMaterials.length; multimatIndex++) {
  17915. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  17916. if (parsedMultiMaterial.id == parsedMesh.materialId) {
  17917. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  17918. var subMatId = parsedMultiMaterial.materials[matIndex];
  17919. loadedMaterialsIds.push(subMatId);
  17920. parseMaterialById(subMatId, parsedData, scene, rootUrl);
  17921. }
  17922. loadedMaterialsIds.push(parsedMultiMaterial.id);
  17923. parseMultiMaterial(parsedMultiMaterial, scene);
  17924. materialFound = true;
  17925. break;
  17926. }
  17927. }
  17928. }
  17929. if (!materialFound) {
  17930. loadedMaterialsIds.push(parsedMesh.materialId);
  17931. parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  17932. }
  17933. }
  17934. // Skeleton ?
  17935. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  17936. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  17937. if (!skeletonAlreadyLoaded) {
  17938. for (var skeletonIndex = 0; skeletonIndex < parsedData.skeletons.length; skeletonIndex++) {
  17939. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  17940. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  17941. skeletons.push(parseSkeleton(parsedSkeleton, scene));
  17942. loadedSkeletonsIds.push(parsedSkeleton.id);
  17943. }
  17944. }
  17945. }
  17946. }
  17947. var mesh = parseMesh(parsedMesh, scene, rootUrl);
  17948. meshes.push(mesh);
  17949. }
  17950. }
  17951. for (index = 0; index < scene.meshes.length; index++) {
  17952. var currentMesh = scene.meshes[index];
  17953. if (currentMesh._waitingParentId) {
  17954. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  17955. currentMesh._waitingParentId = undefined;
  17956. }
  17957. }
  17958. // Particles
  17959. if (parsedData.particleSystems) {
  17960. for (index = 0; index < parsedData.particleSystems.length; index++) {
  17961. var parsedParticleSystem = parsedData.particleSystems[index];
  17962. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  17963. particleSystems.push(parseParticleSystem(parsedParticleSystem, scene, rootUrl));
  17964. }
  17965. }
  17966. }
  17967. return true;
  17968. },
  17969. load: function (scene, data, rootUrl) {
  17970. var parsedData = JSON.parse(data);
  17971. // Scene
  17972. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  17973. scene.autoClear = parsedData.autoClear;
  17974. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  17975. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  17976. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  17977. // Fog
  17978. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  17979. scene.fogMode = parsedData.fogMode;
  17980. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  17981. scene.fogStart = parsedData.fogStart;
  17982. scene.fogEnd = parsedData.fogEnd;
  17983. scene.fogDensity = parsedData.fogDensity;
  17984. }
  17985. for (var index = 0; index < parsedData.lights.length; index++) {
  17986. var parsedLight = parsedData.lights[index];
  17987. parseLight(parsedLight, scene);
  17988. }
  17989. // Materials
  17990. if (parsedData.materials) {
  17991. for (index = 0; index < parsedData.materials.length; index++) {
  17992. var parsedMaterial = parsedData.materials[index];
  17993. parseMaterial(parsedMaterial, scene, rootUrl);
  17994. }
  17995. }
  17996. if (parsedData.multiMaterials) {
  17997. for (index = 0; index < parsedData.multiMaterials.length; index++) {
  17998. var parsedMultiMaterial = parsedData.multiMaterials[index];
  17999. parseMultiMaterial(parsedMultiMaterial, scene);
  18000. }
  18001. }
  18002. // Skeletons
  18003. if (parsedData.skeletons) {
  18004. for (index = 0; index < parsedData.skeletons.length; index++) {
  18005. var parsedSkeleton = parsedData.skeletons[index];
  18006. parseSkeleton(parsedSkeleton, scene);
  18007. }
  18008. }
  18009. // Geometries
  18010. var geometries = parsedData.geometries;
  18011. if (geometries) {
  18012. // Boxes
  18013. var boxes = geometries.boxes;
  18014. if (boxes) {
  18015. for (index = 0; index < boxes.length; index++) {
  18016. var parsedBox = boxes[index];
  18017. parseBox(parsedBox, scene);
  18018. }
  18019. }
  18020. // Spheres
  18021. var spheres = geometries.spheres;
  18022. if (spheres) {
  18023. for (index = 0; index < spheres.length; index++) {
  18024. var parsedSphere = spheres[index];
  18025. parseSphere(parsedSphere, scene);
  18026. }
  18027. }
  18028. // Cylinders
  18029. var cylinders = geometries.cylinders;
  18030. if (cylinders) {
  18031. for (index = 0; index < cylinders.length; index++) {
  18032. var parsedCylinder = cylinders[index];
  18033. parseCylinder(parsedCylinder, scene);
  18034. }
  18035. }
  18036. // Toruses
  18037. var toruses = geometries.toruses;
  18038. if (toruses) {
  18039. for (index = 0; index < toruses.length; index++) {
  18040. var parsedTorus = toruses[index];
  18041. parseTorus(parsedTorus, scene);
  18042. }
  18043. }
  18044. // Grounds
  18045. var grounds = geometries.grounds;
  18046. if (grounds) {
  18047. for (index = 0; index < grounds.length; index++) {
  18048. var parsedGround = grounds[index];
  18049. parseGround(parsedGround, scene);
  18050. }
  18051. }
  18052. // Planes
  18053. var planes = geometries.planes;
  18054. if (planes) {
  18055. for (index = 0; index < planes.length; index++) {
  18056. var parsedPlane = planes[index];
  18057. parsePlane(parsedPlane, scene);
  18058. }
  18059. }
  18060. // TorusKnots
  18061. var torusKnots = geometries.torusKnots;
  18062. if (torusKnots) {
  18063. for (index = 0; index < torusKnots.length; index++) {
  18064. var parsedTorusKnot = torusKnots[index];
  18065. parseTorusKnot(parsedTorusKnot, scene);
  18066. }
  18067. }
  18068. // VertexData
  18069. var vertexData = geometries.vertexData;
  18070. if (vertexData) {
  18071. for (index = 0; index < vertexData.length; index++) {
  18072. var parsedVertexData = vertexData[index];
  18073. parseVertexData(parsedVertexData, scene, rootUrl);
  18074. }
  18075. }
  18076. }
  18077. for (index = 0; index < parsedData.meshes.length; index++) {
  18078. var parsedMesh = parsedData.meshes[index];
  18079. parseMesh(parsedMesh, scene, rootUrl);
  18080. }
  18081. for (index = 0; index < parsedData.cameras.length; index++) {
  18082. var parsedCamera = parsedData.cameras[index];
  18083. parseCamera(parsedCamera, scene);
  18084. }
  18085. if (parsedData.activeCameraID) {
  18086. scene.setActiveCameraByID(parsedData.activeCameraID);
  18087. }
  18088. for (index = 0; index < scene.cameras.length; index++) {
  18089. var camera = scene.cameras[index];
  18090. if (camera._waitingParentId) {
  18091. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  18092. camera._waitingParentId = undefined;
  18093. }
  18094. }
  18095. for (index = 0; index < scene.lights.length; index++) {
  18096. var light = scene.lights[index];
  18097. if (light._waitingParentId) {
  18098. light.parent = scene.getLastEntryByID(light._waitingParentId);
  18099. light._waitingParentId = undefined;
  18100. }
  18101. }
  18102. for (index = 0; index < scene.meshes.length; index++) {
  18103. var mesh = scene.meshes[index];
  18104. if (mesh._waitingParentId) {
  18105. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  18106. mesh._waitingParentId = undefined;
  18107. }
  18108. }
  18109. // Particles Systems
  18110. if (parsedData.particleSystems) {
  18111. for (index = 0; index < parsedData.particleSystems.length; index++) {
  18112. var parsedParticleSystem = parsedData.particleSystems[index];
  18113. parseParticleSystem(parsedParticleSystem, scene, rootUrl);
  18114. }
  18115. }
  18116. // Lens flares
  18117. if (parsedData.lensFlareSystems) {
  18118. for (index = 0; index < parsedData.lensFlareSystems.length; index++) {
  18119. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  18120. parseLensFlareSystem(parsedLensFlareSystem, scene, rootUrl);
  18121. }
  18122. }
  18123. // Shadows
  18124. if (parsedData.shadowGenerators) {
  18125. for (index = 0; index < parsedData.shadowGenerators.length; index++) {
  18126. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  18127. parseShadowGenerator(parsedShadowGenerator, scene);
  18128. }
  18129. }
  18130. // Finish
  18131. return true;
  18132. }
  18133. });
  18134. })(BABYLON.Internals || (BABYLON.Internals = {}));
  18135. var Internals = BABYLON.Internals;
  18136. })(BABYLON || (BABYLON = {}));
  18137. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  18138. var BABYLON;
  18139. (function (BABYLON) {
  18140. // Unique ID when we import meshes from Babylon to CSG
  18141. var currentCSGMeshId = 0;
  18142. // # class Vertex
  18143. // Represents a vertex of a polygon. Use your own vertex class instead of this
  18144. // one to provide additional features like texture coordinates and vertex
  18145. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  18146. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  18147. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  18148. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  18149. // is not used anywhere else.
  18150. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  18151. var Vertex = (function () {
  18152. function Vertex(pos, normal, uv) {
  18153. this.pos = pos;
  18154. this.normal = normal;
  18155. this.uv = uv;
  18156. }
  18157. Vertex.prototype.clone = function () {
  18158. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  18159. };
  18160. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  18161. // orientation of a polygon is flipped.
  18162. Vertex.prototype.flip = function () {
  18163. this.normal = this.normal.scale(-1);
  18164. };
  18165. // Create a new vertex between this vertex and `other` by linearly
  18166. // interpolating all properties using a parameter of `t`. Subclasses should
  18167. // override this to interpolate additional properties.
  18168. Vertex.prototype.interpolate = function (other, t) {
  18169. 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));
  18170. };
  18171. return Vertex;
  18172. })();
  18173. // # class Plane
  18174. // Represents a plane in 3D space.
  18175. var Plane = (function () {
  18176. function Plane(normal, w) {
  18177. this.normal = normal;
  18178. this.w = w;
  18179. }
  18180. Plane.FromPoints = function (a, b, c) {
  18181. var v0 = c.subtract(a);
  18182. var v1 = b.subtract(a);
  18183. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  18184. return null;
  18185. }
  18186. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  18187. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  18188. };
  18189. Plane.prototype.clone = function () {
  18190. return new Plane(this.normal.clone(), this.w);
  18191. };
  18192. Plane.prototype.flip = function () {
  18193. this.normal.scaleInPlace(-1);
  18194. this.w = -this.w;
  18195. };
  18196. // Split `polygon` by this plane if needed, then put the polygon or polygon
  18197. // fragments in the appropriate lists. Coplanar polygons go into either
  18198. // `coplanarFront` or `coplanarBack` depending on their orientation with
  18199. // respect to this plane. Polygons in front or in back of this plane go into
  18200. // either `front` or `back`.
  18201. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  18202. var COPLANAR = 0;
  18203. var FRONT = 1;
  18204. var BACK = 2;
  18205. var SPANNING = 3;
  18206. // Classify each point as well as the entire polygon into one of the above
  18207. // four classes.
  18208. var polygonType = 0;
  18209. var types = [];
  18210. for (var i = 0; i < polygon.vertices.length; i++) {
  18211. var t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  18212. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  18213. polygonType |= type;
  18214. types.push(type);
  18215. }
  18216. switch (polygonType) {
  18217. case COPLANAR:
  18218. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  18219. break;
  18220. case FRONT:
  18221. front.push(polygon);
  18222. break;
  18223. case BACK:
  18224. back.push(polygon);
  18225. break;
  18226. case SPANNING:
  18227. var f = [], b = [];
  18228. for (i = 0; i < polygon.vertices.length; i++) {
  18229. var j = (i + 1) % polygon.vertices.length;
  18230. var ti = types[i], tj = types[j];
  18231. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  18232. if (ti != BACK)
  18233. f.push(vi);
  18234. if (ti != FRONT)
  18235. b.push(ti != BACK ? vi.clone() : vi);
  18236. if ((ti | tj) == SPANNING) {
  18237. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  18238. var v = vi.interpolate(vj, t);
  18239. f.push(v);
  18240. b.push(v.clone());
  18241. }
  18242. }
  18243. if (f.length >= 3) {
  18244. var poly = new Polygon(f, polygon.shared);
  18245. if (poly.plane)
  18246. front.push(poly);
  18247. }
  18248. if (b.length >= 3) {
  18249. poly = new Polygon(b, polygon.shared);
  18250. if (poly.plane)
  18251. back.push(poly);
  18252. }
  18253. break;
  18254. }
  18255. };
  18256. Plane.EPSILON = 1e-5;
  18257. return Plane;
  18258. })();
  18259. // # class Polygon
  18260. // Represents a convex polygon. The vertices used to initialize a polygon must
  18261. // be coplanar and form a convex loop.
  18262. //
  18263. // Each convex polygon has a `shared` property, which is shared between all
  18264. // polygons that are clones of each other or were split from the same polygon.
  18265. // This can be used to define per-polygon properties (such as surface color).
  18266. var Polygon = (function () {
  18267. function Polygon(vertices, shared) {
  18268. this.vertices = vertices;
  18269. this.shared = shared;
  18270. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  18271. }
  18272. Polygon.prototype.clone = function () {
  18273. var vertices = this.vertices.map(function (v) {
  18274. return v.clone();
  18275. });
  18276. return new Polygon(vertices, this.shared);
  18277. };
  18278. Polygon.prototype.flip = function () {
  18279. this.vertices.reverse().map(function (v) {
  18280. v.flip();
  18281. });
  18282. this.plane.flip();
  18283. };
  18284. return Polygon;
  18285. })();
  18286. // # class Node
  18287. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  18288. // by picking a polygon to split along. That polygon (and all other coplanar
  18289. // polygons) are added directly to that node and the other polygons are added to
  18290. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  18291. // no distinction between internal and leaf nodes.
  18292. var Node = (function () {
  18293. function Node(polygons) {
  18294. this.plane = null;
  18295. this.front = null;
  18296. this.back = null;
  18297. this.polygons = [];
  18298. if (polygons) {
  18299. this.build(polygons);
  18300. }
  18301. }
  18302. Node.prototype.clone = function () {
  18303. var node = new Node();
  18304. node.plane = this.plane && this.plane.clone();
  18305. node.front = this.front && this.front.clone();
  18306. node.back = this.back && this.back.clone();
  18307. node.polygons = this.polygons.map(function (p) {
  18308. return p.clone();
  18309. });
  18310. return node;
  18311. };
  18312. // Convert solid space to empty space and empty space to solid space.
  18313. Node.prototype.invert = function () {
  18314. for (var i = 0; i < this.polygons.length; i++) {
  18315. this.polygons[i].flip();
  18316. }
  18317. if (this.plane) {
  18318. this.plane.flip();
  18319. }
  18320. if (this.front) {
  18321. this.front.invert();
  18322. }
  18323. if (this.back) {
  18324. this.back.invert();
  18325. }
  18326. var temp = this.front;
  18327. this.front = this.back;
  18328. this.back = temp;
  18329. };
  18330. // Recursively remove all polygons in `polygons` that are inside this BSP
  18331. // tree.
  18332. Node.prototype.clipPolygons = function (polygons) {
  18333. if (!this.plane)
  18334. return polygons.slice();
  18335. var front = [], back = [];
  18336. for (var i = 0; i < polygons.length; i++) {
  18337. this.plane.splitPolygon(polygons[i], front, back, front, back);
  18338. }
  18339. if (this.front) {
  18340. front = this.front.clipPolygons(front);
  18341. }
  18342. if (this.back) {
  18343. back = this.back.clipPolygons(back);
  18344. } else {
  18345. back = [];
  18346. }
  18347. return front.concat(back);
  18348. };
  18349. // Remove all polygons in this BSP tree that are inside the other BSP tree
  18350. // `bsp`.
  18351. Node.prototype.clipTo = function (bsp) {
  18352. this.polygons = bsp.clipPolygons(this.polygons);
  18353. if (this.front)
  18354. this.front.clipTo(bsp);
  18355. if (this.back)
  18356. this.back.clipTo(bsp);
  18357. };
  18358. // Return a list of all polygons in this BSP tree.
  18359. Node.prototype.allPolygons = function () {
  18360. var polygons = this.polygons.slice();
  18361. if (this.front)
  18362. polygons = polygons.concat(this.front.allPolygons());
  18363. if (this.back)
  18364. polygons = polygons.concat(this.back.allPolygons());
  18365. return polygons;
  18366. };
  18367. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  18368. // new polygons are filtered down to the bottom of the tree and become new
  18369. // nodes there. Each set of polygons is partitioned using the first polygon
  18370. // (no heuristic is used to pick a good split).
  18371. Node.prototype.build = function (polygons) {
  18372. if (!polygons.length)
  18373. return;
  18374. if (!this.plane)
  18375. this.plane = polygons[0].plane.clone();
  18376. var front = [], back = [];
  18377. for (var i = 0; i < polygons.length; i++) {
  18378. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  18379. }
  18380. if (front.length) {
  18381. if (!this.front)
  18382. this.front = new Node();
  18383. this.front.build(front);
  18384. }
  18385. if (back.length) {
  18386. if (!this.back)
  18387. this.back = new Node();
  18388. this.back.build(back);
  18389. }
  18390. };
  18391. return Node;
  18392. })();
  18393. var CSG = (function () {
  18394. function CSG() {
  18395. this.polygons = new Array();
  18396. }
  18397. // Convert BABYLON.Mesh to BABYLON.CSG
  18398. CSG.FromMesh = function (mesh) {
  18399. var vertex, normal, uv, position, polygon, polygons = [], vertices;
  18400. if (mesh instanceof BABYLON.Mesh) {
  18401. mesh.computeWorldMatrix(true);
  18402. var matrix = mesh.getWorldMatrix();
  18403. var meshPosition = mesh.position.clone();
  18404. var meshRotation = mesh.rotation.clone();
  18405. var meshScaling = mesh.scaling.clone();
  18406. } else {
  18407. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  18408. }
  18409. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  18410. var subMeshes = mesh.subMeshes;
  18411. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  18412. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  18413. vertices = [];
  18414. for (var j = 0; j < 3; j++) {
  18415. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  18416. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  18417. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  18418. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  18419. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  18420. vertex = new Vertex(position, normal, uv);
  18421. vertices.push(vertex);
  18422. }
  18423. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  18424. // To handle the case of degenerated triangle
  18425. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  18426. if (polygon.plane)
  18427. polygons.push(polygon);
  18428. }
  18429. }
  18430. var csg = CSG.FromPolygons(polygons);
  18431. csg.matrix = matrix;
  18432. csg.position = meshPosition;
  18433. csg.rotation = meshRotation;
  18434. csg.scaling = meshScaling;
  18435. currentCSGMeshId++;
  18436. return csg;
  18437. };
  18438. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  18439. CSG.FromPolygons = function (polygons) {
  18440. var csg = new BABYLON.CSG();
  18441. csg.polygons = polygons;
  18442. return csg;
  18443. };
  18444. CSG.prototype.clone = function () {
  18445. var csg = new BABYLON.CSG();
  18446. csg.polygons = this.polygons.map(function (p) {
  18447. return p.clone();
  18448. });
  18449. csg.copyTransformAttributes(this);
  18450. return csg;
  18451. };
  18452. CSG.prototype.toPolygons = function () {
  18453. return this.polygons;
  18454. };
  18455. CSG.prototype.union = function (csg) {
  18456. var a = new Node(this.clone().polygons);
  18457. var b = new Node(csg.clone().polygons);
  18458. a.clipTo(b);
  18459. b.clipTo(a);
  18460. b.invert();
  18461. b.clipTo(a);
  18462. b.invert();
  18463. a.build(b.allPolygons());
  18464. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  18465. };
  18466. CSG.prototype.unionInPlace = function (csg) {
  18467. var a = new Node(this.polygons);
  18468. var b = new Node(csg.polygons);
  18469. a.clipTo(b);
  18470. b.clipTo(a);
  18471. b.invert();
  18472. b.clipTo(a);
  18473. b.invert();
  18474. a.build(b.allPolygons());
  18475. this.polygons = a.allPolygons();
  18476. };
  18477. CSG.prototype.subtract = function (csg) {
  18478. var a = new Node(this.clone().polygons);
  18479. var b = new Node(csg.clone().polygons);
  18480. a.invert();
  18481. a.clipTo(b);
  18482. b.clipTo(a);
  18483. b.invert();
  18484. b.clipTo(a);
  18485. b.invert();
  18486. a.build(b.allPolygons());
  18487. a.invert();
  18488. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  18489. };
  18490. CSG.prototype.subtractInPlace = function (csg) {
  18491. var a = new Node(this.polygons);
  18492. var b = new Node(csg.polygons);
  18493. a.invert();
  18494. a.clipTo(b);
  18495. b.clipTo(a);
  18496. b.invert();
  18497. b.clipTo(a);
  18498. b.invert();
  18499. a.build(b.allPolygons());
  18500. a.invert();
  18501. this.polygons = a.allPolygons();
  18502. };
  18503. CSG.prototype.intersect = function (csg) {
  18504. var a = new Node(this.clone().polygons);
  18505. var b = new Node(csg.clone().polygons);
  18506. a.invert();
  18507. b.clipTo(a);
  18508. b.invert();
  18509. a.clipTo(b);
  18510. b.clipTo(a);
  18511. a.build(b.allPolygons());
  18512. a.invert();
  18513. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  18514. };
  18515. CSG.prototype.intersectInPlace = function (csg) {
  18516. var a = new Node(this.polygons);
  18517. var b = new Node(csg.polygons);
  18518. a.invert();
  18519. b.clipTo(a);
  18520. b.invert();
  18521. a.clipTo(b);
  18522. b.clipTo(a);
  18523. a.build(b.allPolygons());
  18524. a.invert();
  18525. this.polygons = a.allPolygons();
  18526. };
  18527. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  18528. // not modified.
  18529. CSG.prototype.inverse = function () {
  18530. var csg = this.clone();
  18531. csg.inverseInPlace();
  18532. return csg;
  18533. };
  18534. CSG.prototype.inverseInPlace = function () {
  18535. this.polygons.map(function (p) {
  18536. p.flip();
  18537. });
  18538. };
  18539. // This is used to keep meshes transformations so they can be restored
  18540. // when we build back a Babylon Mesh
  18541. // NB : All CSG operations are performed in world coordinates
  18542. CSG.prototype.copyTransformAttributes = function (csg) {
  18543. this.matrix = csg.matrix;
  18544. this.position = csg.position;
  18545. this.rotation = csg.rotation;
  18546. this.scaling = csg.scaling;
  18547. return this;
  18548. };
  18549. // Build Raw mesh from CSG
  18550. // Coordinates here are in world space
  18551. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  18552. var matrix = this.matrix.clone();
  18553. matrix.invert();
  18554. 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;
  18555. if (keepSubMeshes) {
  18556. // Sort Polygons, since subMeshes are indices range
  18557. polygons.sort(function (a, b) {
  18558. if (a.shared.meshId === b.shared.meshId) {
  18559. return a.shared.subMeshId - b.shared.subMeshId;
  18560. } else {
  18561. return a.shared.meshId - b.shared.meshId;
  18562. }
  18563. });
  18564. }
  18565. for (var i = 0, il = polygons.length; i < il; i++) {
  18566. polygon = polygons[i];
  18567. // Building SubMeshes
  18568. if (!subMesh_dict[polygon.shared.meshId]) {
  18569. subMesh_dict[polygon.shared.meshId] = {};
  18570. }
  18571. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  18572. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  18573. indexStart: +Infinity,
  18574. indexEnd: -Infinity,
  18575. materialIndex: polygon.shared.materialIndex
  18576. };
  18577. }
  18578. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  18579. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  18580. polygonIndices[0] = 0;
  18581. polygonIndices[1] = j - 1;
  18582. polygonIndices[2] = j;
  18583. for (var k = 0; k < 3; k++) {
  18584. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  18585. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  18586. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  18587. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  18588. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  18589. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  18590. // Check if 2 points can be merged
  18591. 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)) {
  18592. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  18593. uvs.push(uv.x, uv.y);
  18594. normals.push(normal.x, normal.y, normal.z);
  18595. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  18596. }
  18597. indices.push(vertex_idx);
  18598. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  18599. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  18600. currentIndex++;
  18601. }
  18602. }
  18603. }
  18604. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  18605. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  18606. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  18607. mesh.setIndices(indices);
  18608. if (keepSubMeshes) {
  18609. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  18610. var materialIndexOffset = 0, materialMaxIndex;
  18611. mesh.subMeshes.length = 0;
  18612. for (var m in subMesh_dict) {
  18613. materialMaxIndex = -1;
  18614. for (var sm in subMesh_dict[m]) {
  18615. subMesh_obj = subMesh_dict[m][sm];
  18616. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  18617. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  18618. }
  18619. materialIndexOffset += ++materialMaxIndex;
  18620. }
  18621. }
  18622. return mesh;
  18623. };
  18624. // Build Mesh from CSG taking material and transforms into account
  18625. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  18626. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  18627. mesh.material = material;
  18628. mesh.position.copyFrom(this.position);
  18629. mesh.rotation.copyFrom(this.rotation);
  18630. mesh.scaling.copyFrom(this.scaling);
  18631. mesh.computeWorldMatrix(true);
  18632. return mesh;
  18633. };
  18634. return CSG;
  18635. })();
  18636. BABYLON.CSG = CSG;
  18637. })(BABYLON || (BABYLON = {}));
  18638. //# sourceMappingURL=babylon.csg.js.map
  18639. var BABYLON;
  18640. (function (BABYLON) {
  18641. var OculusDistortionCorrectionPostProcess = (function (_super) {
  18642. __extends(OculusDistortionCorrectionPostProcess, _super);
  18643. //ANY
  18644. function OculusDistortionCorrectionPostProcess(name, camera, isRightEye, cameraSettings) {
  18645. var _this = this;
  18646. _super.call(this, name, "oculusDistortionCorrection", [
  18647. 'LensCenter',
  18648. 'Scale',
  18649. 'ScaleIn',
  18650. 'HmdWarpParam'
  18651. ], null, cameraSettings.PostProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  18652. this._isRightEye = isRightEye;
  18653. this._distortionFactors = cameraSettings.DistortionK;
  18654. this._postProcessScaleFactor = cameraSettings.PostProcessScaleFactor;
  18655. this._lensCenterOffset = cameraSettings.LensCenterOffset;
  18656. this.onSizeChanged = function () {
  18657. _this.aspectRatio = _this.width * .5 / _this.height;
  18658. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  18659. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  18660. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  18661. };
  18662. this.onApply = function (effect) {
  18663. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  18664. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  18665. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  18666. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  18667. };
  18668. }
  18669. return OculusDistortionCorrectionPostProcess;
  18670. })(BABYLON.PostProcess);
  18671. BABYLON.OculusDistortionCorrectionPostProcess = OculusDistortionCorrectionPostProcess;
  18672. })(BABYLON || (BABYLON = {}));
  18673. //# sourceMappingURL=babylon.oculusDistortionCorrectionPostProcess.js.map
  18674. // Mainly based on these 2 articles :
  18675. // 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
  18676. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  18677. var BABYLON;
  18678. (function (BABYLON) {
  18679. (function (JoystickAxis) {
  18680. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  18681. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  18682. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  18683. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  18684. var JoystickAxis = BABYLON.JoystickAxis;
  18685. var VirtualJoystick = (function () {
  18686. function VirtualJoystick(leftJoystick) {
  18687. var _this = this;
  18688. if (leftJoystick) {
  18689. this._leftJoystick = true;
  18690. } else {
  18691. this._leftJoystick = false;
  18692. }
  18693. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  18694. VirtualJoystick._globalJoystickIndex++;
  18695. // By default left & right arrow keys are moving the X
  18696. // and up & down keys are moving the Y
  18697. this._axisTargetedByLeftAndRight = 0 /* X */;
  18698. this._axisTargetedByUpAndDown = 1 /* Y */;
  18699. this.reverseLeftRight = false;
  18700. this.reverseUpDown = false;
  18701. // collections of pointers
  18702. this._touches = new BABYLON.VirtualJoystick.Collection();
  18703. this.deltaPosition = BABYLON.Vector3.Zero();
  18704. this._joystickSensibility = 25;
  18705. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  18706. this._rotationSpeed = 25;
  18707. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  18708. this._rotateOnAxisRelativeToMesh = false;
  18709. // injecting a canvas element on top of the canvas 3D game
  18710. if (!VirtualJoystick.vjCanvas) {
  18711. window.addEventListener("resize", function () {
  18712. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  18713. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  18714. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  18715. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  18716. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  18717. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  18718. }, false);
  18719. VirtualJoystick.vjCanvas = document.createElement("canvas");
  18720. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  18721. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  18722. VirtualJoystick.vjCanvas.width = window.innerWidth;
  18723. VirtualJoystick.vjCanvas.height = window.innerHeight;
  18724. VirtualJoystick.vjCanvas.style.width = "100%";
  18725. VirtualJoystick.vjCanvas.style.height = "100%";
  18726. VirtualJoystick.vjCanvas.style.position = "absolute";
  18727. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  18728. VirtualJoystick.vjCanvas.style.top = "0px";
  18729. VirtualJoystick.vjCanvas.style.left = "0px";
  18730. VirtualJoystick.vjCanvas.style.zIndex = "5";
  18731. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  18732. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  18733. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  18734. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  18735. document.body.appendChild(VirtualJoystick.vjCanvas);
  18736. }
  18737. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  18738. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  18739. this.pressed = false;
  18740. // default joystick color
  18741. this._joystickColor = "cyan";
  18742. this._joystickPointerID = -1;
  18743. // current joystick position
  18744. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  18745. // origin joystick position
  18746. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  18747. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  18748. VirtualJoystick.vjCanvas.addEventListener('pointerdown', function (evt) {
  18749. _this._onPointerDown(evt);
  18750. }, false);
  18751. VirtualJoystick.vjCanvas.addEventListener('pointermove', function (evt) {
  18752. _this._onPointerMove(evt);
  18753. }, false);
  18754. VirtualJoystick.vjCanvas.addEventListener('pointerup', function (evt) {
  18755. _this._onPointerUp(evt);
  18756. }, false);
  18757. VirtualJoystick.vjCanvas.addEventListener('pointerout', function (evt) {
  18758. _this._onPointerUp(evt);
  18759. }, false);
  18760. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  18761. evt.preventDefault(); // Disables system menu
  18762. }, false);
  18763. requestAnimationFrame(function () {
  18764. _this._drawVirtualJoystick();
  18765. });
  18766. }
  18767. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  18768. this._joystickSensibility = newJoystickSensibility;
  18769. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  18770. };
  18771. VirtualJoystick.prototype._onPointerDown = function (e) {
  18772. var positionOnScreenCondition;
  18773. e.preventDefault();
  18774. if (this._leftJoystick === true) {
  18775. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  18776. } else {
  18777. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  18778. }
  18779. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  18780. // First contact will be dedicated to the virtual joystick
  18781. this._joystickPointerID = e.pointerId;
  18782. this._joystickPointerStartPos.x = e.clientX;
  18783. this._joystickPointerStartPos.y = e.clientY;
  18784. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  18785. this._deltaJoystickVector.x = 0;
  18786. this._deltaJoystickVector.y = 0;
  18787. this.pressed = true;
  18788. this._touches.add(e.pointerId.toString(), e);
  18789. } else {
  18790. // You can only trigger the action buttons with a joystick declared
  18791. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  18792. this._action();
  18793. this._touches.add(e.pointerId.toString(), e);
  18794. }
  18795. }
  18796. };
  18797. VirtualJoystick.prototype._onPointerMove = function (e) {
  18798. // If the current pointer is the one associated to the joystick (first touch contact)
  18799. if (this._joystickPointerID == e.pointerId) {
  18800. this._joystickPointerPos.x = e.clientX;
  18801. this._joystickPointerPos.y = e.clientY;
  18802. this._deltaJoystickVector = this._joystickPointerPos.clone();
  18803. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  18804. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  18805. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  18806. switch (this._axisTargetedByLeftAndRight) {
  18807. case 0 /* X */:
  18808. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  18809. break;
  18810. case 1 /* Y */:
  18811. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  18812. break;
  18813. case 2 /* Z */:
  18814. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  18815. break;
  18816. }
  18817. var directionUpDown = this.reverseUpDown ? 1 : -1;
  18818. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  18819. switch (this._axisTargetedByUpAndDown) {
  18820. case 0 /* X */:
  18821. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  18822. break;
  18823. case 1 /* Y */:
  18824. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  18825. break;
  18826. case 2 /* Z */:
  18827. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  18828. break;
  18829. }
  18830. } else {
  18831. if (this._touches.item(e.pointerId.toString())) {
  18832. this._touches.item(e.pointerId.toString()).x = e.clientX;
  18833. this._touches.item(e.pointerId.toString()).y = e.clientY;
  18834. }
  18835. }
  18836. };
  18837. VirtualJoystick.prototype._onPointerUp = function (e) {
  18838. this._clearCanvas();
  18839. if (this._joystickPointerID == e.pointerId) {
  18840. this._joystickPointerID = -1;
  18841. this.pressed = false;
  18842. }
  18843. this._deltaJoystickVector.x = 0;
  18844. this._deltaJoystickVector.y = 0;
  18845. this._touches.remove(e.pointerId.toString());
  18846. };
  18847. /**
  18848. * Change the color of the virtual joystick
  18849. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  18850. */
  18851. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  18852. this._joystickColor = newColor;
  18853. };
  18854. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  18855. this._action = action;
  18856. };
  18857. // Define which axis you'd like to control for left & right
  18858. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  18859. switch (axis) {
  18860. case 0 /* X */:
  18861. case 1 /* Y */:
  18862. case 2 /* Z */:
  18863. this._axisTargetedByLeftAndRight = axis;
  18864. break;
  18865. default:
  18866. this._axisTargetedByLeftAndRight = 0 /* X */;
  18867. break;
  18868. }
  18869. };
  18870. // Define which axis you'd like to control for up & down
  18871. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  18872. switch (axis) {
  18873. case 0 /* X */:
  18874. case 1 /* Y */:
  18875. case 2 /* Z */:
  18876. this._axisTargetedByUpAndDown = axis;
  18877. break;
  18878. default:
  18879. this._axisTargetedByUpAndDown = 1 /* Y */;
  18880. break;
  18881. }
  18882. };
  18883. VirtualJoystick.prototype._clearCanvas = function () {
  18884. if (this._leftJoystick) {
  18885. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  18886. } else {
  18887. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  18888. }
  18889. };
  18890. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  18891. var _this = this;
  18892. if (this.pressed) {
  18893. this._clearCanvas();
  18894. this._touches.forEach(function (touch) {
  18895. if (touch.pointerId === _this._joystickPointerID) {
  18896. VirtualJoystick.vjCanvasContext.beginPath();
  18897. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  18898. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  18899. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  18900. VirtualJoystick.vjCanvasContext.stroke();
  18901. VirtualJoystick.vjCanvasContext.beginPath();
  18902. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  18903. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  18904. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  18905. VirtualJoystick.vjCanvasContext.stroke();
  18906. VirtualJoystick.vjCanvasContext.beginPath();
  18907. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  18908. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  18909. VirtualJoystick.vjCanvasContext.stroke();
  18910. } else {
  18911. VirtualJoystick.vjCanvasContext.beginPath();
  18912. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  18913. VirtualJoystick.vjCanvasContext.beginPath();
  18914. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  18915. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  18916. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  18917. VirtualJoystick.vjCanvasContext.stroke();
  18918. }
  18919. ;
  18920. });
  18921. }
  18922. requestAnimationFrame(function () {
  18923. _this._drawVirtualJoystick();
  18924. });
  18925. };
  18926. VirtualJoystick.prototype.releaseCanvas = function () {
  18927. if (VirtualJoystick.vjCanvas) {
  18928. document.body.removeChild(VirtualJoystick.vjCanvas);
  18929. VirtualJoystick.vjCanvas = null;
  18930. }
  18931. };
  18932. VirtualJoystick._globalJoystickIndex = 0;
  18933. return VirtualJoystick;
  18934. })();
  18935. BABYLON.VirtualJoystick = VirtualJoystick;
  18936. })(BABYLON || (BABYLON = {}));
  18937. var BABYLON;
  18938. (function (BABYLON) {
  18939. (function (VirtualJoystick) {
  18940. var Collection = (function () {
  18941. function Collection() {
  18942. this._count = 0;
  18943. this._collection = new Array();
  18944. }
  18945. Collection.prototype.Count = function () {
  18946. return this._count;
  18947. };
  18948. Collection.prototype.add = function (key, item) {
  18949. if (this._collection[key] != undefined) {
  18950. return undefined;
  18951. }
  18952. this._collection[key] = item;
  18953. return ++this._count;
  18954. };
  18955. Collection.prototype.remove = function (key) {
  18956. if (this._collection[key] == undefined) {
  18957. return undefined;
  18958. }
  18959. delete this._collection[key];
  18960. return --this._count;
  18961. };
  18962. Collection.prototype.item = function (key) {
  18963. return this._collection[key];
  18964. };
  18965. Collection.prototype.forEach = function (block) {
  18966. var key;
  18967. for (key in this._collection) {
  18968. if (this._collection.hasOwnProperty(key)) {
  18969. block(this._collection[key]);
  18970. }
  18971. }
  18972. };
  18973. return Collection;
  18974. })();
  18975. VirtualJoystick.Collection = Collection;
  18976. })(BABYLON.VirtualJoystick || (BABYLON.VirtualJoystick = {}));
  18977. var VirtualJoystick = BABYLON.VirtualJoystick;
  18978. })(BABYLON || (BABYLON = {}));
  18979. //# sourceMappingURL=babylon.virtualJoystick.js.map
  18980. var BABYLON;
  18981. (function (BABYLON) {
  18982. var OculusRiftDevKit2013_Metric = {
  18983. HResolution: 1280,
  18984. VResolution: 800,
  18985. HScreenSize: 0.149759993,
  18986. VScreenSize: 0.0935999975,
  18987. VScreenCenter: 0.0467999987,
  18988. EyeToScreenDistance: 0.0410000011,
  18989. LensSeparationDistance: 0.0635000020,
  18990. InterpupillaryDistance: 0.0640000030,
  18991. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  18992. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  18993. PostProcessScaleFactor: 1.714605507808412,
  18994. LensCenterOffset: 0.151976421
  18995. };
  18996. var _OculusInnerCamera = (function (_super) {
  18997. __extends(_OculusInnerCamera, _super);
  18998. function _OculusInnerCamera(name, position, scene, isLeftEye) {
  18999. _super.call(this, name, position, scene);
  19000. this._workMatrix = new BABYLON.Matrix();
  19001. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  19002. // Constants
  19003. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  19004. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  19005. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  19006. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  19007. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  19008. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  19009. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  19010. // Postprocess
  19011. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  19012. }
  19013. _OculusInnerCamera.prototype.getProjectionMatrix = function () {
  19014. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  19015. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  19016. return this._projectionMatrix;
  19017. };
  19018. _OculusInnerCamera.prototype._getViewMatrix = function () {
  19019. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  19020. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  19021. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  19022. // Computing target and final matrix
  19023. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  19024. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  19025. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  19026. return this._viewMatrix;
  19027. };
  19028. return _OculusInnerCamera;
  19029. })(BABYLON.FreeCamera);
  19030. var OculusCamera = (function (_super) {
  19031. __extends(OculusCamera, _super);
  19032. function OculusCamera(name, position, scene) {
  19033. _super.call(this, name, position, scene);
  19034. this._leftCamera = new _OculusInnerCamera(name + "_left", position.clone(), scene, true);
  19035. this._rightCamera = new _OculusInnerCamera(name + "_right", position.clone(), scene, false);
  19036. this.subCameras.push(this._leftCamera);
  19037. this.subCameras.push(this._rightCamera);
  19038. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  19039. }
  19040. OculusCamera.prototype._update = function () {
  19041. this._leftCamera.position.copyFrom(this.position);
  19042. this._rightCamera.position.copyFrom(this.position);
  19043. this._updateCamera(this._leftCamera);
  19044. this._updateCamera(this._rightCamera);
  19045. _super.prototype._update.call(this);
  19046. };
  19047. OculusCamera.prototype._updateCamera = function (camera) {
  19048. camera.minZ = this.minZ;
  19049. camera.maxZ = this.maxZ;
  19050. camera.rotation.x = this.rotation.x;
  19051. camera.rotation.y = this.rotation.y;
  19052. camera.rotation.z = this.rotation.z;
  19053. };
  19054. // Oculus events
  19055. OculusCamera.prototype._onOrientationEvent = function (evt) {
  19056. var yaw = evt.alpha / 180 * Math.PI;
  19057. var pitch = evt.beta / 180 * Math.PI;
  19058. var roll = evt.gamma / 180 * Math.PI;
  19059. if (!this._offsetOrientation) {
  19060. this._offsetOrientation = {
  19061. yaw: yaw,
  19062. pitch: pitch,
  19063. roll: roll
  19064. };
  19065. return;
  19066. } else {
  19067. this.rotation.y += yaw - this._offsetOrientation.yaw;
  19068. this.rotation.x += pitch - this._offsetOrientation.pitch;
  19069. this.rotation.z += this._offsetOrientation.roll - roll;
  19070. this._offsetOrientation.yaw = yaw;
  19071. this._offsetOrientation.pitch = pitch;
  19072. this._offsetOrientation.roll = roll;
  19073. }
  19074. };
  19075. OculusCamera.prototype.attachControl = function (element, noPreventDefault) {
  19076. _super.prototype.attachControl.call(this, element, noPreventDefault);
  19077. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  19078. };
  19079. OculusCamera.prototype.detachControl = function (element) {
  19080. _super.prototype.detachControl.call(this, element);
  19081. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  19082. };
  19083. return OculusCamera;
  19084. })(BABYLON.FreeCamera);
  19085. BABYLON.OculusCamera = OculusCamera;
  19086. })(BABYLON || (BABYLON = {}));
  19087. //# sourceMappingURL=babylon.oculusCamera.js.map
  19088. var BABYLON;
  19089. (function (BABYLON) {
  19090. var OculusRiftDevKit2013_Metric = {
  19091. HResolution: 1280,
  19092. VResolution: 800,
  19093. HScreenSize: 0.149759993,
  19094. VScreenSize: 0.0935999975,
  19095. VScreenCenter: 0.0467999987,
  19096. EyeToScreenDistance: 0.0410000011,
  19097. LensSeparationDistance: 0.0635000020,
  19098. InterpupillaryDistance: 0.0640000030,
  19099. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  19100. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  19101. PostProcessScaleFactor: 1.714605507808412,
  19102. LensCenterOffset: 0.151976421
  19103. };
  19104. var _OculusInnerGamepadCamera = (function (_super) {
  19105. __extends(_OculusInnerGamepadCamera, _super);
  19106. function _OculusInnerGamepadCamera(name, position, scene, isLeftEye) {
  19107. _super.call(this, name, position, scene);
  19108. this._workMatrix = new BABYLON.Matrix();
  19109. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  19110. // Constants
  19111. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  19112. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  19113. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  19114. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  19115. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  19116. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  19117. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  19118. // Postprocess
  19119. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  19120. }
  19121. _OculusInnerGamepadCamera.prototype.getProjectionMatrix = function () {
  19122. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  19123. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  19124. return this._projectionMatrix;
  19125. };
  19126. _OculusInnerGamepadCamera.prototype._getViewMatrix = function () {
  19127. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  19128. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  19129. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  19130. // Computing target and final matrix
  19131. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  19132. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  19133. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  19134. return this._viewMatrix;
  19135. };
  19136. return _OculusInnerGamepadCamera;
  19137. })(BABYLON.FreeCamera);
  19138. var OculusGamepadCamera = (function (_super) {
  19139. __extends(OculusGamepadCamera, _super);
  19140. function OculusGamepadCamera(name, position, scene) {
  19141. var _this = this;
  19142. _super.call(this, name, position, scene);
  19143. this.angularSensibility = 200;
  19144. this.moveSensibility = 75;
  19145. this._leftCamera = new _OculusInnerGamepadCamera(name + "_left", position.clone(), scene, true);
  19146. this._rightCamera = new _OculusInnerGamepadCamera(name + "_right", position.clone(), scene, false);
  19147. this.subCameras.push(this._leftCamera);
  19148. this.subCameras.push(this._rightCamera);
  19149. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  19150. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  19151. _this._onNewGameConnected(gamepad);
  19152. });
  19153. }
  19154. OculusGamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  19155. // Only the first gamepad can control the camera
  19156. if (gamepad.index === 0) {
  19157. this._gamepad = gamepad;
  19158. }
  19159. };
  19160. OculusGamepadCamera.prototype._update = function () {
  19161. this._leftCamera.position.copyFrom(this.position);
  19162. this._rightCamera.position.copyFrom(this.position);
  19163. this._updateCamera(this._leftCamera);
  19164. this._updateCamera(this._rightCamera);
  19165. _super.prototype._update.call(this);
  19166. };
  19167. OculusGamepadCamera.prototype._checkInputs = function () {
  19168. if (!this._gamepad) {
  19169. return;
  19170. }
  19171. var LSValues = this._gamepad.leftStick;
  19172. var normalizedLX = LSValues.x / this.moveSensibility;
  19173. var normalizedLY = LSValues.y / this.moveSensibility;
  19174. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  19175. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  19176. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  19177. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x, 0, -LSValues.y), cameraTransform);
  19178. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  19179. };
  19180. OculusGamepadCamera.prototype._updateCamera = function (camera) {
  19181. camera.minZ = this.minZ;
  19182. camera.maxZ = this.maxZ;
  19183. camera.rotation.x = this.rotation.x;
  19184. camera.rotation.y = this.rotation.y;
  19185. camera.rotation.z = this.rotation.z;
  19186. };
  19187. // Oculus events
  19188. OculusGamepadCamera.prototype._onOrientationEvent = function (evt) {
  19189. var yaw = evt.alpha / 180 * Math.PI;
  19190. var pitch = evt.beta / 180 * Math.PI;
  19191. var roll = evt.gamma / 180 * Math.PI;
  19192. if (!this._offsetOrientation) {
  19193. this._offsetOrientation = {
  19194. yaw: yaw,
  19195. pitch: pitch,
  19196. roll: roll
  19197. };
  19198. return;
  19199. } else {
  19200. this.rotation.y += yaw - this._offsetOrientation.yaw;
  19201. this.rotation.x += pitch - this._offsetOrientation.pitch;
  19202. this.rotation.z += this._offsetOrientation.roll - roll;
  19203. this._offsetOrientation.yaw = yaw;
  19204. this._offsetOrientation.pitch = pitch;
  19205. this._offsetOrientation.roll = roll;
  19206. }
  19207. };
  19208. OculusGamepadCamera.prototype.attachControl = function (element, noPreventDefault) {
  19209. _super.prototype.attachControl.call(this, element, noPreventDefault);
  19210. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  19211. };
  19212. OculusGamepadCamera.prototype.detachControl = function (element) {
  19213. _super.prototype.detachControl.call(this, element);
  19214. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  19215. };
  19216. OculusGamepadCamera.prototype.dispose = function () {
  19217. this._gamepads.dispose();
  19218. _super.prototype.dispose.call(this);
  19219. };
  19220. return OculusGamepadCamera;
  19221. })(BABYLON.FreeCamera);
  19222. BABYLON.OculusGamepadCamera = OculusGamepadCamera;
  19223. })(BABYLON || (BABYLON = {}));
  19224. //# sourceMappingURL=babylon.oculusGamepadCamera.js.map
  19225. var BABYLON;
  19226. (function (BABYLON) {
  19227. // We're mainly based on the logic defined into the FreeCamera code
  19228. var VirtualJoysticksCamera = (function (_super) {
  19229. __extends(VirtualJoysticksCamera, _super);
  19230. function VirtualJoysticksCamera(name, position, scene) {
  19231. _super.call(this, name, position, scene);
  19232. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  19233. this._leftjoystick.setAxisForUpDown(2 /* Z */);
  19234. this._leftjoystick.setAxisForLeftRight(0 /* X */);
  19235. this._leftjoystick.setJoystickSensibility(0.15);
  19236. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  19237. this._rightjoystick.setAxisForUpDown(0 /* X */);
  19238. this._rightjoystick.setAxisForLeftRight(1 /* Y */);
  19239. this._rightjoystick.reverseUpDown = true;
  19240. this._rightjoystick.setJoystickSensibility(0.05);
  19241. this._rightjoystick.setJoystickColor("yellow");
  19242. }
  19243. VirtualJoysticksCamera.prototype._checkInputs = function () {
  19244. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  19245. var deltaTransform = BABYLON.Vector3.TransformCoordinates(this._leftjoystick.deltaPosition, cameraTransform);
  19246. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  19247. this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  19248. if (!this._leftjoystick.pressed) {
  19249. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  19250. }
  19251. if (!this._rightjoystick.pressed) {
  19252. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  19253. }
  19254. };
  19255. VirtualJoysticksCamera.prototype.dispose = function () {
  19256. this._leftjoystick.releaseCanvas();
  19257. _super.prototype.dispose.call(this);
  19258. };
  19259. return VirtualJoysticksCamera;
  19260. })(BABYLON.FreeCamera);
  19261. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  19262. })(BABYLON || (BABYLON = {}));
  19263. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  19264. var BABYLON;
  19265. (function (BABYLON) {
  19266. var ShaderMaterial = (function (_super) {
  19267. __extends(ShaderMaterial, _super);
  19268. function ShaderMaterial(name, scene, shaderPath, options) {
  19269. _super.call(this, name, scene);
  19270. this._textures = new Array();
  19271. this._floats = new Array();
  19272. this._floatsArrays = {};
  19273. this._colors3 = new Array();
  19274. this._colors4 = new Array();
  19275. this._vectors2 = new Array();
  19276. this._vectors3 = new Array();
  19277. this._matrices = new Array();
  19278. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  19279. this._shaderPath = shaderPath;
  19280. options.needAlphaBlending = options.needAlphaBlending || false;
  19281. options.needAlphaTesting = options.needAlphaTesting || false;
  19282. options.attributes = options.attributes || ["position", "normal", "uv"];
  19283. options.uniforms = options.uniforms || ["worldViewProjection"];
  19284. options.samplers = options.samplers || [];
  19285. this._options = options;
  19286. }
  19287. ShaderMaterial.prototype.needAlphaBlending = function () {
  19288. return this._options.needAlphaBlending;
  19289. };
  19290. ShaderMaterial.prototype.needAlphaTesting = function () {
  19291. return this._options.needAlphaTesting;
  19292. };
  19293. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  19294. if (this._options.uniforms.indexOf(uniformName) === -1) {
  19295. this._options.uniforms.push(uniformName);
  19296. }
  19297. };
  19298. ShaderMaterial.prototype.setTexture = function (name, texture) {
  19299. if (this._options.samplers.indexOf(name) === -1) {
  19300. this._options.samplers.push(name);
  19301. }
  19302. this._textures[name] = texture;
  19303. return this;
  19304. };
  19305. ShaderMaterial.prototype.setFloat = function (name, value) {
  19306. this._checkUniform(name);
  19307. this._floats[name] = value;
  19308. return this;
  19309. };
  19310. ShaderMaterial.prototype.setFloats = function (name, value) {
  19311. this._checkUniform(name);
  19312. this._floatsArrays[name] = value;
  19313. return this;
  19314. };
  19315. ShaderMaterial.prototype.setColor3 = function (name, value) {
  19316. this._checkUniform(name);
  19317. this._colors3[name] = value;
  19318. return this;
  19319. };
  19320. ShaderMaterial.prototype.setColor4 = function (name, value) {
  19321. this._checkUniform(name);
  19322. this._colors4[name] = value;
  19323. return this;
  19324. };
  19325. ShaderMaterial.prototype.setVector2 = function (name, value) {
  19326. this._checkUniform(name);
  19327. this._vectors2[name] = value;
  19328. return this;
  19329. };
  19330. ShaderMaterial.prototype.setVector3 = function (name, value) {
  19331. this._checkUniform(name);
  19332. this._vectors3[name] = value;
  19333. return this;
  19334. };
  19335. ShaderMaterial.prototype.setMatrix = function (name, value) {
  19336. this._checkUniform(name);
  19337. this._matrices[name] = value;
  19338. return this;
  19339. };
  19340. ShaderMaterial.prototype.isReady = function () {
  19341. var scene = this.getScene();
  19342. var engine = scene.getEngine();
  19343. if (!this.checkReadyOnEveryCall) {
  19344. if (this._renderId === scene.getRenderId()) {
  19345. return true;
  19346. }
  19347. }
  19348. var previousEffect = this._effect;
  19349. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, "", null, this.onCompiled, this.onError);
  19350. if (!this._effect.isReady()) {
  19351. return false;
  19352. }
  19353. if (previousEffect !== this._effect) {
  19354. scene.resetCachedMaterial();
  19355. }
  19356. this._renderId = scene.getRenderId();
  19357. return true;
  19358. };
  19359. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  19360. var scene = this.getScene();
  19361. if (this._options.uniforms.indexOf("world") !== -1) {
  19362. this._effect.setMatrix("world", world);
  19363. }
  19364. if (this._options.uniforms.indexOf("worldView") !== -1) {
  19365. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  19366. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  19367. }
  19368. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  19369. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  19370. }
  19371. };
  19372. ShaderMaterial.prototype.bind = function (world) {
  19373. // Std values
  19374. this.bindOnlyWorldMatrix(world);
  19375. if (this.getScene().getCachedMaterial() !== this) {
  19376. if (this._options.uniforms.indexOf("view") !== -1) {
  19377. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  19378. }
  19379. if (this._options.uniforms.indexOf("projection") !== -1) {
  19380. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  19381. }
  19382. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  19383. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  19384. }
  19385. for (var name in this._textures) {
  19386. this._effect.setTexture(name, this._textures[name]);
  19387. }
  19388. for (name in this._floats) {
  19389. this._effect.setFloat(name, this._floats[name]);
  19390. }
  19391. for (name in this._floatsArrays) {
  19392. this._effect.setArray(name, this._floatsArrays[name]);
  19393. }
  19394. for (name in this._colors3) {
  19395. this._effect.setColor3(name, this._colors3[name]);
  19396. }
  19397. for (name in this._colors4) {
  19398. var color = this._colors4[name];
  19399. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  19400. }
  19401. for (name in this._vectors2) {
  19402. this._effect.setVector2(name, this._vectors2[name]);
  19403. }
  19404. for (name in this._vectors3) {
  19405. this._effect.setVector3(name, this._vectors3[name]);
  19406. }
  19407. for (name in this._matrices) {
  19408. this._effect.setMatrix(name, this._matrices[name]);
  19409. }
  19410. }
  19411. _super.prototype.bind.call(this, world, null);
  19412. };
  19413. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  19414. for (var name in this._textures) {
  19415. this._textures[name].dispose();
  19416. }
  19417. this._textures = [];
  19418. _super.prototype.dispose.call(this, forceDisposeEffect);
  19419. };
  19420. return ShaderMaterial;
  19421. })(BABYLON.Material);
  19422. BABYLON.ShaderMaterial = ShaderMaterial;
  19423. })(BABYLON || (BABYLON = {}));
  19424. //# sourceMappingURL=babylon.shaderMaterial.js.map
  19425. var BABYLON;
  19426. (function (BABYLON) {
  19427. var VertexData = (function () {
  19428. function VertexData() {
  19429. }
  19430. VertexData.prototype.set = function (data, kind) {
  19431. switch (kind) {
  19432. case BABYLON.VertexBuffer.PositionKind:
  19433. this.positions = data;
  19434. break;
  19435. case BABYLON.VertexBuffer.NormalKind:
  19436. this.normals = data;
  19437. break;
  19438. case BABYLON.VertexBuffer.UVKind:
  19439. this.uvs = data;
  19440. break;
  19441. case BABYLON.VertexBuffer.UV2Kind:
  19442. this.uv2s = data;
  19443. break;
  19444. case BABYLON.VertexBuffer.ColorKind:
  19445. this.colors = data;
  19446. break;
  19447. case BABYLON.VertexBuffer.MatricesIndicesKind:
  19448. this.matricesIndices = data;
  19449. break;
  19450. case BABYLON.VertexBuffer.MatricesWeightsKind:
  19451. this.matricesWeights = data;
  19452. break;
  19453. }
  19454. };
  19455. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  19456. this._applyTo(mesh, updatable);
  19457. };
  19458. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  19459. this._applyTo(geometry, updatable);
  19460. };
  19461. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  19462. this._update(mesh);
  19463. };
  19464. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  19465. this._update(geometry);
  19466. };
  19467. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  19468. if (this.positions) {
  19469. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  19470. }
  19471. if (this.normals) {
  19472. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  19473. }
  19474. if (this.uvs) {
  19475. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  19476. }
  19477. if (this.uv2s) {
  19478. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updatable);
  19479. }
  19480. if (this.colors) {
  19481. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  19482. }
  19483. if (this.matricesIndices) {
  19484. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  19485. }
  19486. if (this.matricesWeights) {
  19487. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  19488. }
  19489. if (this.indices) {
  19490. meshOrGeometry.setIndices(this.indices);
  19491. }
  19492. };
  19493. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  19494. if (this.positions) {
  19495. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  19496. }
  19497. if (this.normals) {
  19498. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  19499. }
  19500. if (this.uvs) {
  19501. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  19502. }
  19503. if (this.uv2s) {
  19504. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updateExtends, makeItUnique);
  19505. }
  19506. if (this.colors) {
  19507. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  19508. }
  19509. if (this.matricesIndices) {
  19510. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  19511. }
  19512. if (this.matricesWeights) {
  19513. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  19514. }
  19515. if (this.indices) {
  19516. meshOrGeometry.setIndices(this.indices);
  19517. }
  19518. };
  19519. VertexData.prototype.transform = function (matrix) {
  19520. var transformed = BABYLON.Vector3.Zero();
  19521. if (this.positions) {
  19522. var position = BABYLON.Vector3.Zero();
  19523. for (var index = 0; index < this.positions.length; index += 3) {
  19524. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  19525. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  19526. this.positions[index] = transformed.x;
  19527. this.positions[index + 1] = transformed.y;
  19528. this.positions[index + 2] = transformed.z;
  19529. }
  19530. }
  19531. if (this.normals) {
  19532. var normal = BABYLON.Vector3.Zero();
  19533. for (index = 0; index < this.normals.length; index += 3) {
  19534. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  19535. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  19536. this.normals[index] = transformed.x;
  19537. this.normals[index + 1] = transformed.y;
  19538. this.normals[index + 2] = transformed.z;
  19539. }
  19540. }
  19541. };
  19542. VertexData.prototype.merge = function (other) {
  19543. if (other.indices) {
  19544. if (!this.indices) {
  19545. this.indices = [];
  19546. }
  19547. var offset = this.positions ? this.positions.length / 3 : 0;
  19548. for (var index = 0; index < other.indices.length; index++) {
  19549. this.indices.push(other.indices[index] + offset);
  19550. }
  19551. }
  19552. if (other.positions) {
  19553. if (!this.positions) {
  19554. this.positions = [];
  19555. }
  19556. for (index = 0; index < other.positions.length; index++) {
  19557. this.positions.push(other.positions[index]);
  19558. }
  19559. }
  19560. if (other.normals) {
  19561. if (!this.normals) {
  19562. this.normals = [];
  19563. }
  19564. for (index = 0; index < other.normals.length; index++) {
  19565. this.normals.push(other.normals[index]);
  19566. }
  19567. }
  19568. if (other.uvs) {
  19569. if (!this.uvs) {
  19570. this.uvs = [];
  19571. }
  19572. for (index = 0; index < other.uvs.length; index++) {
  19573. this.uvs.push(other.uvs[index]);
  19574. }
  19575. }
  19576. if (other.uv2s) {
  19577. if (!this.uv2s) {
  19578. this.uv2s = [];
  19579. }
  19580. for (index = 0; index < other.uv2s.length; index++) {
  19581. this.uv2s.push(other.uv2s[index]);
  19582. }
  19583. }
  19584. if (other.matricesIndices) {
  19585. if (!this.matricesIndices) {
  19586. this.matricesIndices = [];
  19587. }
  19588. for (index = 0; index < other.matricesIndices.length; index++) {
  19589. this.matricesIndices.push(other.matricesIndices[index]);
  19590. }
  19591. }
  19592. if (other.matricesWeights) {
  19593. if (!this.matricesWeights) {
  19594. this.matricesWeights = [];
  19595. }
  19596. for (index = 0; index < other.matricesWeights.length; index++) {
  19597. this.matricesWeights.push(other.matricesWeights[index]);
  19598. }
  19599. }
  19600. if (other.colors) {
  19601. if (!this.colors) {
  19602. this.colors = [];
  19603. }
  19604. for (index = 0; index < other.colors.length; index++) {
  19605. this.colors.push(other.colors[index]);
  19606. }
  19607. }
  19608. };
  19609. // Statics
  19610. VertexData.ExtractFromMesh = function (mesh) {
  19611. return VertexData._ExtractFrom(mesh);
  19612. };
  19613. VertexData.ExtractFromGeometry = function (geometry) {
  19614. return VertexData._ExtractFrom(geometry);
  19615. };
  19616. VertexData._ExtractFrom = function (meshOrGeometry) {
  19617. var result = new BABYLON.VertexData();
  19618. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  19619. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19620. }
  19621. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  19622. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  19623. }
  19624. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  19625. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind);
  19626. }
  19627. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  19628. result.uv2s = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  19629. }
  19630. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  19631. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  19632. }
  19633. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  19634. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  19635. }
  19636. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  19637. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  19638. }
  19639. result.indices = meshOrGeometry.getIndices();
  19640. return result;
  19641. };
  19642. VertexData.CreateBox = function (size) {
  19643. var normalsSource = [
  19644. new BABYLON.Vector3(0, 0, 1),
  19645. new BABYLON.Vector3(0, 0, -1),
  19646. new BABYLON.Vector3(1, 0, 0),
  19647. new BABYLON.Vector3(-1, 0, 0),
  19648. new BABYLON.Vector3(0, 1, 0),
  19649. new BABYLON.Vector3(0, -1, 0)
  19650. ];
  19651. var indices = [];
  19652. var positions = [];
  19653. var normals = [];
  19654. var uvs = [];
  19655. size = size || 1;
  19656. for (var index = 0; index < normalsSource.length; index++) {
  19657. var normal = normalsSource[index];
  19658. // Get two vectors perpendicular to the face normal and to each other.
  19659. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  19660. var side2 = BABYLON.Vector3.Cross(normal, side1);
  19661. // Six indices (two triangles) per face.
  19662. var verticesLength = positions.length / 3;
  19663. indices.push(verticesLength);
  19664. indices.push(verticesLength + 1);
  19665. indices.push(verticesLength + 2);
  19666. indices.push(verticesLength);
  19667. indices.push(verticesLength + 2);
  19668. indices.push(verticesLength + 3);
  19669. // Four vertices per face.
  19670. var vertex = normal.subtract(side1).subtract(side2).scale(size / 2);
  19671. positions.push(vertex.x, vertex.y, vertex.z);
  19672. normals.push(normal.x, normal.y, normal.z);
  19673. uvs.push(1.0, 1.0);
  19674. vertex = normal.subtract(side1).add(side2).scale(size / 2);
  19675. positions.push(vertex.x, vertex.y, vertex.z);
  19676. normals.push(normal.x, normal.y, normal.z);
  19677. uvs.push(0.0, 1.0);
  19678. vertex = normal.add(side1).add(side2).scale(size / 2);
  19679. positions.push(vertex.x, vertex.y, vertex.z);
  19680. normals.push(normal.x, normal.y, normal.z);
  19681. uvs.push(0.0, 0.0);
  19682. vertex = normal.add(side1).subtract(side2).scale(size / 2);
  19683. positions.push(vertex.x, vertex.y, vertex.z);
  19684. normals.push(normal.x, normal.y, normal.z);
  19685. uvs.push(1.0, 0.0);
  19686. }
  19687. // Result
  19688. var vertexData = new BABYLON.VertexData();
  19689. vertexData.indices = indices;
  19690. vertexData.positions = positions;
  19691. vertexData.normals = normals;
  19692. vertexData.uvs = uvs;
  19693. return vertexData;
  19694. };
  19695. VertexData.CreateSphere = function (segments, diameter) {
  19696. segments = segments || 32;
  19697. diameter = diameter || 1;
  19698. var radius = diameter / 2;
  19699. var totalZRotationSteps = 2 + segments;
  19700. var totalYRotationSteps = 2 * totalZRotationSteps;
  19701. var indices = [];
  19702. var positions = [];
  19703. var normals = [];
  19704. var uvs = [];
  19705. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  19706. var normalizedZ = zRotationStep / totalZRotationSteps;
  19707. var angleZ = (normalizedZ * Math.PI);
  19708. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  19709. var normalizedY = yRotationStep / totalYRotationSteps;
  19710. var angleY = normalizedY * Math.PI * 2;
  19711. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  19712. var rotationY = BABYLON.Matrix.RotationY(angleY);
  19713. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  19714. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  19715. var vertex = complete.scale(radius);
  19716. var normal = BABYLON.Vector3.Normalize(vertex);
  19717. positions.push(vertex.x, vertex.y, vertex.z);
  19718. normals.push(normal.x, normal.y, normal.z);
  19719. uvs.push(normalizedZ, normalizedY);
  19720. }
  19721. if (zRotationStep > 0) {
  19722. var verticesCount = positions.length / 3;
  19723. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  19724. indices.push((firstIndex));
  19725. indices.push((firstIndex + 1));
  19726. indices.push(firstIndex + totalYRotationSteps + 1);
  19727. indices.push((firstIndex + totalYRotationSteps + 1));
  19728. indices.push((firstIndex + 1));
  19729. indices.push((firstIndex + totalYRotationSteps + 2));
  19730. }
  19731. }
  19732. }
  19733. // Result
  19734. var vertexData = new BABYLON.VertexData();
  19735. vertexData.indices = indices;
  19736. vertexData.positions = positions;
  19737. vertexData.normals = normals;
  19738. vertexData.uvs = uvs;
  19739. return vertexData;
  19740. };
  19741. VertexData.CreateCylinder = function (height, diameterTop, diameterBottom, tessellation, subdivisions) {
  19742. if (typeof subdivisions === "undefined") { subdivisions = 1; }
  19743. var radiusTop = diameterTop / 2;
  19744. var radiusBottom = diameterBottom / 2;
  19745. var indices = [];
  19746. var positions = [];
  19747. var normals = [];
  19748. var uvs = [];
  19749. height = height || 1;
  19750. diameterTop = diameterTop || 0.5;
  19751. diameterBottom = diameterBottom || 1;
  19752. tessellation = tessellation || 16;
  19753. subdivisions = subdivisions || 1;
  19754. subdivisions = (subdivisions < 1) ? 1 : subdivisions;
  19755. var getCircleVector = function (i) {
  19756. var angle = (i * 2.0 * Math.PI / tessellation);
  19757. var dx = Math.cos(angle);
  19758. var dz = Math.sin(angle);
  19759. return new BABYLON.Vector3(dx, 0, dz);
  19760. };
  19761. var createCylinderCap = function (isTop) {
  19762. var radius = isTop ? radiusTop : radiusBottom;
  19763. if (radius == 0) {
  19764. return;
  19765. }
  19766. var vbase = positions.length / 3;
  19767. var offset = new BABYLON.Vector3(0, height / 2, 0);
  19768. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  19769. if (!isTop) {
  19770. offset.scaleInPlace(-1);
  19771. textureScale.x = -textureScale.x;
  19772. }
  19773. for (i = 0; i < tessellation; i++) {
  19774. var circleVector = getCircleVector(i);
  19775. var position = circleVector.scale(radius).add(offset);
  19776. var textureCoordinate = new BABYLON.Vector2(circleVector.x * textureScale.x + 0.5, circleVector.z * textureScale.y + 0.5);
  19777. positions.push(position.x, position.y, position.z);
  19778. uvs.push(textureCoordinate.x, textureCoordinate.y);
  19779. }
  19780. for (var i = 0; i < tessellation - 2; i++) {
  19781. if (!isTop) {
  19782. indices.push(vbase);
  19783. indices.push(vbase + (i + 2) % tessellation);
  19784. indices.push(vbase + (i + 1) % tessellation);
  19785. } else {
  19786. indices.push(vbase);
  19787. indices.push(vbase + (i + 1) % tessellation);
  19788. indices.push(vbase + (i + 2) % tessellation);
  19789. }
  19790. }
  19791. };
  19792. var base = new BABYLON.Vector3(0, -1, 0).scale(height / 2);
  19793. var offset = new BABYLON.Vector3(0, 1, 0).scale(height / subdivisions);
  19794. var stride = tessellation + 1;
  19795. for (var i = 0; i <= tessellation; i++) {
  19796. var circleVector = getCircleVector(i);
  19797. var textureCoordinate = new BABYLON.Vector2(i / tessellation, 0);
  19798. var position, radius = radiusBottom;
  19799. for (var s = 0; s <= subdivisions; s++) {
  19800. // Update variables
  19801. position = circleVector.scale(radius);
  19802. position.addInPlace(base.add(offset.scale(s)));
  19803. textureCoordinate.y += 1 / subdivisions;
  19804. radius += (radiusTop - radiusBottom) / subdivisions;
  19805. // Push in arrays
  19806. positions.push(position.x, position.y, position.z);
  19807. uvs.push(textureCoordinate.x, textureCoordinate.y);
  19808. }
  19809. }
  19810. subdivisions += 1;
  19811. for (var s = 0; s < subdivisions - 1; s++) {
  19812. for (var i = 0; i <= tessellation; i++) {
  19813. indices.push(i * subdivisions + s);
  19814. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  19815. indices.push(i * subdivisions + (s + 1));
  19816. indices.push(i * subdivisions + (s + 1));
  19817. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  19818. indices.push((i * subdivisions + (s + subdivisions + 1)) % (stride * subdivisions));
  19819. }
  19820. }
  19821. // Create flat triangle fan caps to seal the top and bottom.
  19822. createCylinderCap(true);
  19823. createCylinderCap(false);
  19824. // Normals
  19825. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  19826. // Result
  19827. var vertexData = new BABYLON.VertexData();
  19828. vertexData.indices = indices;
  19829. vertexData.positions = positions;
  19830. vertexData.normals = normals;
  19831. vertexData.uvs = uvs;
  19832. return vertexData;
  19833. };
  19834. VertexData.CreateTorus = function (diameter, thickness, tessellation) {
  19835. var indices = [];
  19836. var positions = [];
  19837. var normals = [];
  19838. var uvs = [];
  19839. diameter = diameter || 1;
  19840. thickness = thickness || 0.5;
  19841. tessellation = tessellation || 16;
  19842. var stride = tessellation + 1;
  19843. for (var i = 0; i <= tessellation; i++) {
  19844. var u = i / tessellation;
  19845. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  19846. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  19847. for (var j = 0; j <= tessellation; j++) {
  19848. var v = 1 - j / tessellation;
  19849. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  19850. var dx = Math.cos(innerAngle);
  19851. var dy = Math.sin(innerAngle);
  19852. // Create a vertex.
  19853. var normal = new BABYLON.Vector3(dx, dy, 0);
  19854. var position = normal.scale(thickness / 2);
  19855. var textureCoordinate = new BABYLON.Vector2(u, v);
  19856. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  19857. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  19858. positions.push(position.x, position.y, position.z);
  19859. normals.push(normal.x, normal.y, normal.z);
  19860. uvs.push(textureCoordinate.x, textureCoordinate.y);
  19861. // And create indices for two triangles.
  19862. var nextI = (i + 1) % stride;
  19863. var nextJ = (j + 1) % stride;
  19864. indices.push(i * stride + j);
  19865. indices.push(i * stride + nextJ);
  19866. indices.push(nextI * stride + j);
  19867. indices.push(i * stride + nextJ);
  19868. indices.push(nextI * stride + nextJ);
  19869. indices.push(nextI * stride + j);
  19870. }
  19871. }
  19872. // Result
  19873. var vertexData = new BABYLON.VertexData();
  19874. vertexData.indices = indices;
  19875. vertexData.positions = positions;
  19876. vertexData.normals = normals;
  19877. vertexData.uvs = uvs;
  19878. return vertexData;
  19879. };
  19880. VertexData.CreateLines = function (points) {
  19881. var indices = [];
  19882. var positions = [];
  19883. for (var index = 0; index < points.length; index++) {
  19884. positions.push(points[index].x, points[index].y, points[index].z);
  19885. if (index > 0) {
  19886. indices.push(index - 1);
  19887. indices.push(index);
  19888. }
  19889. }
  19890. // Result
  19891. var vertexData = new BABYLON.VertexData();
  19892. vertexData.indices = indices;
  19893. vertexData.positions = positions;
  19894. return vertexData;
  19895. };
  19896. VertexData.CreateGround = function (width, height, subdivisions) {
  19897. var indices = [];
  19898. var positions = [];
  19899. var normals = [];
  19900. var uvs = [];
  19901. var row, col;
  19902. width = width || 1;
  19903. height = height || 1;
  19904. subdivisions = subdivisions || 1;
  19905. for (row = 0; row <= subdivisions; row++) {
  19906. for (col = 0; col <= subdivisions; col++) {
  19907. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  19908. var normal = new BABYLON.Vector3(0, 1.0, 0);
  19909. positions.push(position.x, position.y, position.z);
  19910. normals.push(normal.x, normal.y, normal.z);
  19911. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  19912. }
  19913. }
  19914. for (row = 0; row < subdivisions; row++) {
  19915. for (col = 0; col < subdivisions; col++) {
  19916. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  19917. indices.push(col + 1 + row * (subdivisions + 1));
  19918. indices.push(col + row * (subdivisions + 1));
  19919. indices.push(col + (row + 1) * (subdivisions + 1));
  19920. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  19921. indices.push(col + row * (subdivisions + 1));
  19922. }
  19923. }
  19924. // Result
  19925. var vertexData = new BABYLON.VertexData();
  19926. vertexData.indices = indices;
  19927. vertexData.positions = positions;
  19928. vertexData.normals = normals;
  19929. vertexData.uvs = uvs;
  19930. return vertexData;
  19931. };
  19932. VertexData.CreateTiledGround = function (xmin, zmin, xmax, zmax, subdivisions, precision) {
  19933. if (typeof subdivisions === "undefined") { subdivisions = { w: 1, h: 1 }; }
  19934. if (typeof precision === "undefined") { precision = { w: 1, h: 1 }; }
  19935. var indices = [];
  19936. var positions = [];
  19937. var normals = [];
  19938. var uvs = [];
  19939. var row, col, tileRow, tileCol;
  19940. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  19941. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  19942. precision.w = (precision.w < 1) ? 1 : precision.w;
  19943. precision.h = (precision.h < 1) ? 1 : precision.h;
  19944. var tileSize = {
  19945. 'w': (xmax - xmin) / subdivisions.w,
  19946. 'h': (zmax - zmin) / subdivisions.h
  19947. };
  19948. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  19949. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  19950. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  19951. }
  19952. }
  19953. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  19954. // Indices
  19955. var base = positions.length / 3;
  19956. var rowLength = precision.w + 1;
  19957. for (row = 0; row < precision.h; row++) {
  19958. for (col = 0; col < precision.w; col++) {
  19959. var square = [
  19960. base + col + row * rowLength,
  19961. base + (col + 1) + row * rowLength,
  19962. base + (col + 1) + (row + 1) * rowLength,
  19963. base + col + (row + 1) * rowLength
  19964. ];
  19965. indices.push(square[1]);
  19966. indices.push(square[2]);
  19967. indices.push(square[3]);
  19968. indices.push(square[0]);
  19969. indices.push(square[1]);
  19970. indices.push(square[3]);
  19971. }
  19972. }
  19973. // Position, normals and uvs
  19974. var position = BABYLON.Vector3.Zero();
  19975. var normal = new BABYLON.Vector3(0, 1.0, 0);
  19976. for (row = 0; row <= precision.h; row++) {
  19977. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  19978. for (col = 0; col <= precision.w; col++) {
  19979. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  19980. position.y = 0;
  19981. positions.push(position.x, position.y, position.z);
  19982. normals.push(normal.x, normal.y, normal.z);
  19983. uvs.push(col / precision.w, row / precision.h);
  19984. }
  19985. }
  19986. }
  19987. // Result
  19988. var vertexData = new BABYLON.VertexData();
  19989. vertexData.indices = indices;
  19990. vertexData.positions = positions;
  19991. vertexData.normals = normals;
  19992. vertexData.uvs = uvs;
  19993. return vertexData;
  19994. };
  19995. VertexData.CreateGroundFromHeightMap = function (width, height, subdivisions, minHeight, maxHeight, buffer, bufferWidth, bufferHeight) {
  19996. var indices = [];
  19997. var positions = [];
  19998. var normals = [];
  19999. var uvs = [];
  20000. var row, col;
  20001. for (row = 0; row <= subdivisions; row++) {
  20002. for (col = 0; col <= subdivisions; col++) {
  20003. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  20004. // Compute height
  20005. var heightMapX = (((position.x + width / 2) / width) * (bufferWidth - 1)) | 0;
  20006. var heightMapY = ((1.0 - (position.z + height / 2) / height) * (bufferHeight - 1)) | 0;
  20007. var pos = (heightMapX + heightMapY * bufferWidth) * 4;
  20008. var r = buffer[pos] / 255.0;
  20009. var g = buffer[pos + 1] / 255.0;
  20010. var b = buffer[pos + 2] / 255.0;
  20011. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  20012. position.y = minHeight + (maxHeight - minHeight) * gradient;
  20013. // Add vertex
  20014. positions.push(position.x, position.y, position.z);
  20015. normals.push(0, 0, 0);
  20016. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  20017. }
  20018. }
  20019. for (row = 0; row < subdivisions; row++) {
  20020. for (col = 0; col < subdivisions; col++) {
  20021. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  20022. indices.push(col + 1 + row * (subdivisions + 1));
  20023. indices.push(col + row * (subdivisions + 1));
  20024. indices.push(col + (row + 1) * (subdivisions + 1));
  20025. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  20026. indices.push(col + row * (subdivisions + 1));
  20027. }
  20028. }
  20029. // Normals
  20030. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  20031. // Result
  20032. var vertexData = new BABYLON.VertexData();
  20033. vertexData.indices = indices;
  20034. vertexData.positions = positions;
  20035. vertexData.normals = normals;
  20036. vertexData.uvs = uvs;
  20037. return vertexData;
  20038. };
  20039. VertexData.CreatePlane = function (size) {
  20040. var indices = [];
  20041. var positions = [];
  20042. var normals = [];
  20043. var uvs = [];
  20044. size = size || 1;
  20045. // Vertices
  20046. var halfSize = size / 2.0;
  20047. positions.push(-halfSize, -halfSize, 0);
  20048. normals.push(0, 0, -1.0);
  20049. uvs.push(0.0, 0.0);
  20050. positions.push(halfSize, -halfSize, 0);
  20051. normals.push(0, 0, -1.0);
  20052. uvs.push(1.0, 0.0);
  20053. positions.push(halfSize, halfSize, 0);
  20054. normals.push(0, 0, -1.0);
  20055. uvs.push(1.0, 1.0);
  20056. positions.push(-halfSize, halfSize, 0);
  20057. normals.push(0, 0, -1.0);
  20058. uvs.push(0.0, 1.0);
  20059. // Indices
  20060. indices.push(0);
  20061. indices.push(1);
  20062. indices.push(2);
  20063. indices.push(0);
  20064. indices.push(2);
  20065. indices.push(3);
  20066. // Result
  20067. var vertexData = new BABYLON.VertexData();
  20068. vertexData.indices = indices;
  20069. vertexData.positions = positions;
  20070. vertexData.normals = normals;
  20071. vertexData.uvs = uvs;
  20072. return vertexData;
  20073. };
  20074. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  20075. VertexData.CreateTorusKnot = function (radius, tube, radialSegments, tubularSegments, p, q) {
  20076. var indices = [];
  20077. var positions = [];
  20078. var normals = [];
  20079. var uvs = [];
  20080. radius = radius || 2;
  20081. tube = tube || 0.5;
  20082. radialSegments = radialSegments || 32;
  20083. tubularSegments = tubularSegments || 32;
  20084. p = p || 2;
  20085. q = q || 3;
  20086. // Helper
  20087. var getPos = function (angle) {
  20088. var cu = Math.cos(angle);
  20089. var su = Math.sin(angle);
  20090. var quOverP = q / p * angle;
  20091. var cs = Math.cos(quOverP);
  20092. var tx = radius * (2 + cs) * 0.5 * cu;
  20093. var ty = radius * (2 + cs) * su * 0.5;
  20094. var tz = radius * Math.sin(quOverP) * 0.5;
  20095. return new BABYLON.Vector3(tx, ty, tz);
  20096. };
  20097. for (var i = 0; i <= radialSegments; i++) {
  20098. var modI = i % radialSegments;
  20099. var u = modI / radialSegments * 2 * p * Math.PI;
  20100. var p1 = getPos(u);
  20101. var p2 = getPos(u + 0.01);
  20102. var tang = p2.subtract(p1);
  20103. var n = p2.add(p1);
  20104. var bitan = BABYLON.Vector3.Cross(tang, n);
  20105. n = BABYLON.Vector3.Cross(bitan, tang);
  20106. bitan.normalize();
  20107. n.normalize();
  20108. for (var j = 0; j < tubularSegments; j++) {
  20109. var modJ = j % tubularSegments;
  20110. var v = modJ / tubularSegments * 2 * Math.PI;
  20111. var cx = -tube * Math.cos(v);
  20112. var cy = tube * Math.sin(v);
  20113. positions.push(p1.x + cx * n.x + cy * bitan.x);
  20114. positions.push(p1.y + cx * n.y + cy * bitan.y);
  20115. positions.push(p1.z + cx * n.z + cy * bitan.z);
  20116. uvs.push(i / radialSegments);
  20117. uvs.push(j / tubularSegments);
  20118. }
  20119. }
  20120. for (i = 0; i < radialSegments; i++) {
  20121. for (j = 0; j < tubularSegments; j++) {
  20122. var jNext = (j + 1) % tubularSegments;
  20123. var a = i * tubularSegments + j;
  20124. var b = (i + 1) * tubularSegments + j;
  20125. var c = (i + 1) * tubularSegments + jNext;
  20126. var d = i * tubularSegments + jNext;
  20127. indices.push(d);
  20128. indices.push(b);
  20129. indices.push(a);
  20130. indices.push(d);
  20131. indices.push(c);
  20132. indices.push(b);
  20133. }
  20134. }
  20135. // Normals
  20136. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  20137. // Result
  20138. var vertexData = new BABYLON.VertexData();
  20139. vertexData.indices = indices;
  20140. vertexData.positions = positions;
  20141. vertexData.normals = normals;
  20142. vertexData.uvs = uvs;
  20143. return vertexData;
  20144. };
  20145. // Tools
  20146. VertexData.ComputeNormals = function (positions, indices, normals) {
  20147. var positionVectors = [];
  20148. var facesOfVertices = [];
  20149. var index;
  20150. for (index = 0; index < positions.length; index += 3) {
  20151. var vector3 = new BABYLON.Vector3(positions[index], positions[index + 1], positions[index + 2]);
  20152. positionVectors.push(vector3);
  20153. facesOfVertices.push([]);
  20154. }
  20155. // Compute normals
  20156. var facesNormals = [];
  20157. for (index = 0; index < indices.length / 3; index++) {
  20158. var i1 = indices[index * 3];
  20159. var i2 = indices[index * 3 + 1];
  20160. var i3 = indices[index * 3 + 2];
  20161. var p1 = positionVectors[i1];
  20162. var p2 = positionVectors[i2];
  20163. var p3 = positionVectors[i3];
  20164. var p1p2 = p1.subtract(p2);
  20165. var p3p2 = p3.subtract(p2);
  20166. facesNormals[index] = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  20167. facesOfVertices[i1].push(index);
  20168. facesOfVertices[i2].push(index);
  20169. facesOfVertices[i3].push(index);
  20170. }
  20171. for (index = 0; index < positionVectors.length; index++) {
  20172. var faces = facesOfVertices[index];
  20173. var normal = BABYLON.Vector3.Zero();
  20174. for (var faceIndex = 0; faceIndex < faces.length; faceIndex++) {
  20175. normal.addInPlace(facesNormals[faces[faceIndex]]);
  20176. }
  20177. normal = BABYLON.Vector3.Normalize(normal.scale(1.0 / faces.length));
  20178. normals[index * 3] = normal.x;
  20179. normals[index * 3 + 1] = normal.y;
  20180. normals[index * 3 + 2] = normal.z;
  20181. }
  20182. };
  20183. return VertexData;
  20184. })();
  20185. BABYLON.VertexData = VertexData;
  20186. })(BABYLON || (BABYLON = {}));
  20187. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  20188. var BABYLON;
  20189. (function (BABYLON) {
  20190. var buildCamera = function (that, name) {
  20191. that._leftCamera.isIntermediate = true;
  20192. that.subCameras.push(that._leftCamera);
  20193. that.subCameras.push(that._rightCamera);
  20194. that._leftTexture = new BABYLON.PassPostProcess(name + "_leftTexture", 1.0, that._leftCamera);
  20195. that._anaglyphPostProcess = new BABYLON.AnaglyphPostProcess(name + "_anaglyph", 1.0, that._rightCamera);
  20196. that._anaglyphPostProcess.onApply = function (effect) {
  20197. effect.setTextureFromPostProcess("leftSampler", that._leftTexture);
  20198. };
  20199. that._update();
  20200. };
  20201. var AnaglyphArcRotateCamera = (function (_super) {
  20202. __extends(AnaglyphArcRotateCamera, _super);
  20203. // ANY
  20204. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, eyeSpace, scene) {
  20205. _super.call(this, name, alpha, beta, radius, target, scene);
  20206. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  20207. this._leftCamera = new BABYLON.ArcRotateCamera(name + "_left", alpha - this._eyeSpace, beta, radius, target, scene);
  20208. this._rightCamera = new BABYLON.ArcRotateCamera(name + "_right", alpha + this._eyeSpace, beta, radius, target, scene);
  20209. buildCamera(this, name);
  20210. }
  20211. AnaglyphArcRotateCamera.prototype._update = function () {
  20212. this._updateCamera(this._leftCamera);
  20213. this._updateCamera(this._rightCamera);
  20214. this._leftCamera.alpha = this.alpha - this._eyeSpace;
  20215. this._rightCamera.alpha = this.alpha + this._eyeSpace;
  20216. _super.prototype._update.call(this);
  20217. };
  20218. AnaglyphArcRotateCamera.prototype._updateCamera = function (camera) {
  20219. camera.beta = this.beta;
  20220. camera.radius = this.radius;
  20221. camera.minZ = this.minZ;
  20222. camera.maxZ = this.maxZ;
  20223. camera.fov = this.fov;
  20224. camera.target = this.target;
  20225. };
  20226. return AnaglyphArcRotateCamera;
  20227. })(BABYLON.ArcRotateCamera);
  20228. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  20229. var AnaglyphFreeCamera = (function (_super) {
  20230. __extends(AnaglyphFreeCamera, _super);
  20231. function AnaglyphFreeCamera(name, position, eyeSpace, scene) {
  20232. _super.call(this, name, position, scene);
  20233. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  20234. this._transformMatrix = new BABYLON.Matrix();
  20235. this._leftCamera = new BABYLON.FreeCamera(name + "_left", position.clone(), scene);
  20236. this._rightCamera = new BABYLON.FreeCamera(name + "_right", position.clone(), scene);
  20237. buildCamera(this, name);
  20238. }
  20239. AnaglyphFreeCamera.prototype._getSubCameraPosition = function (eyeSpace, result) {
  20240. var target = this.getTarget();
  20241. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(eyeSpace), this._transformMatrix);
  20242. this._transformMatrix = this._transformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  20243. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._transformMatrix, result);
  20244. };
  20245. AnaglyphFreeCamera.prototype._update = function () {
  20246. this._getSubCameraPosition(-this._eyeSpace, this._leftCamera.position);
  20247. this._getSubCameraPosition(this._eyeSpace, this._rightCamera.position);
  20248. this._updateCamera(this._leftCamera);
  20249. this._updateCamera(this._rightCamera);
  20250. _super.prototype._update.call(this);
  20251. };
  20252. AnaglyphFreeCamera.prototype._updateCamera = function (camera) {
  20253. camera.minZ = this.minZ;
  20254. camera.maxZ = this.maxZ;
  20255. camera.fov = this.fov;
  20256. camera.viewport = this.viewport;
  20257. camera.setTarget(this.getTarget());
  20258. };
  20259. return AnaglyphFreeCamera;
  20260. })(BABYLON.FreeCamera);
  20261. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  20262. })(BABYLON || (BABYLON = {}));
  20263. //# sourceMappingURL=babylon.anaglyphCamera.js.map
  20264. var BABYLON;
  20265. (function (BABYLON) {
  20266. var AnaglyphPostProcess = (function (_super) {
  20267. __extends(AnaglyphPostProcess, _super);
  20268. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  20269. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  20270. }
  20271. return AnaglyphPostProcess;
  20272. })(BABYLON.PostProcess);
  20273. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  20274. })(BABYLON || (BABYLON = {}));
  20275. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  20276. var BABYLON;
  20277. (function (BABYLON) {
  20278. var Tags = (function () {
  20279. function Tags() {
  20280. }
  20281. Tags.EnableFor = function (obj) {
  20282. obj._tags = obj._tags || {};
  20283. obj.hasTags = function () {
  20284. return Tags.HasTags(obj);
  20285. };
  20286. obj.addTags = function (tagsString) {
  20287. return Tags.AddTagsTo(obj, tagsString);
  20288. };
  20289. obj.removeTags = function (tagsString) {
  20290. return Tags.RemoveTagsFrom(obj, tagsString);
  20291. };
  20292. obj.matchesTagsQuery = function (tagsQuery) {
  20293. return Tags.MatchesQuery(obj, tagsQuery);
  20294. };
  20295. };
  20296. Tags.DisableFor = function (obj) {
  20297. delete obj._tags;
  20298. delete obj.hasTags;
  20299. delete obj.addTags;
  20300. delete obj.removeTags;
  20301. delete obj.matchesTagsQuery;
  20302. };
  20303. Tags.HasTags = function (obj) {
  20304. if (!obj._tags) {
  20305. return false;
  20306. }
  20307. return !BABYLON.Tools.IsEmpty(obj._tags);
  20308. };
  20309. Tags.GetTags = function (obj) {
  20310. if (!obj._tags) {
  20311. return null;
  20312. }
  20313. return obj._tags;
  20314. };
  20315. // the tags 'true' and 'false' are reserved and cannot be used as tags
  20316. // a tag cannot start with '||', '&&', and '!'
  20317. // it cannot contain whitespaces
  20318. Tags.AddTagsTo = function (obj, tagsString) {
  20319. if (!tagsString) {
  20320. return;
  20321. }
  20322. var tags = tagsString.split(" ");
  20323. for (var t in tags) {
  20324. Tags._AddTagTo(obj, tags[t]);
  20325. }
  20326. };
  20327. Tags._AddTagTo = function (obj, tag) {
  20328. tag = tag.trim();
  20329. if (tag === "" || tag === "true" || tag === "false") {
  20330. return;
  20331. }
  20332. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  20333. return;
  20334. }
  20335. Tags.EnableFor(obj);
  20336. obj._tags[tag] = true;
  20337. };
  20338. Tags.RemoveTagsFrom = function (obj, tagsString) {
  20339. if (!Tags.HasTags(obj)) {
  20340. return;
  20341. }
  20342. var tags = tagsString.split(" ");
  20343. for (var t in tags) {
  20344. Tags._RemoveTagFrom(obj, tags[t]);
  20345. }
  20346. };
  20347. Tags._RemoveTagFrom = function (obj, tag) {
  20348. delete obj._tags[tag];
  20349. };
  20350. Tags.MatchesQuery = function (obj, tagsQuery) {
  20351. if (tagsQuery === undefined) {
  20352. return true;
  20353. }
  20354. if (tagsQuery === "") {
  20355. return Tags.HasTags(obj);
  20356. }
  20357. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) {
  20358. return Tags.HasTags(obj) && obj._tags[r];
  20359. });
  20360. };
  20361. return Tags;
  20362. })();
  20363. BABYLON.Tags = Tags;
  20364. })(BABYLON || (BABYLON = {}));
  20365. //# sourceMappingURL=babylon.tags.js.map
  20366. var BABYLON;
  20367. (function (BABYLON) {
  20368. (function (Internals) {
  20369. var AndOrNotEvaluator = (function () {
  20370. function AndOrNotEvaluator() {
  20371. }
  20372. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  20373. if (!query.match(/\([^\(\)]*\)/g)) {
  20374. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  20375. } else {
  20376. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  20377. // remove parenthesis
  20378. r = r.slice(1, r.length - 1);
  20379. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  20380. });
  20381. }
  20382. if (query === "true") {
  20383. return true;
  20384. }
  20385. if (query === "false") {
  20386. return false;
  20387. }
  20388. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  20389. };
  20390. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  20391. evaluateCallback = evaluateCallback || (function (r) {
  20392. return r === "true" ? true : false;
  20393. });
  20394. var result;
  20395. var or = parenthesisContent.split("||");
  20396. for (var i in or) {
  20397. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  20398. var and = ori.split("&&");
  20399. if (and.length > 1) {
  20400. for (var j = 0; j < and.length; ++j) {
  20401. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  20402. if (andj !== "true" && andj !== "false") {
  20403. if (andj[0] === "!") {
  20404. result = !evaluateCallback(andj.substring(1));
  20405. } else {
  20406. result = evaluateCallback(andj);
  20407. }
  20408. } else {
  20409. result = andj === "true" ? true : false;
  20410. }
  20411. if (!result) {
  20412. ori = "false";
  20413. break;
  20414. }
  20415. }
  20416. }
  20417. if (result || ori === "true") {
  20418. result = true;
  20419. break;
  20420. }
  20421. // result equals false (or undefined)
  20422. if (ori !== "true" && ori !== "false") {
  20423. if (ori[0] === "!") {
  20424. result = !evaluateCallback(ori.substring(1));
  20425. } else {
  20426. result = evaluateCallback(ori);
  20427. }
  20428. } else {
  20429. result = ori === "true" ? true : false;
  20430. }
  20431. }
  20432. // the whole parenthesis scope is replaced by 'true' or 'false'
  20433. return result ? "true" : "false";
  20434. };
  20435. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  20436. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  20437. // remove whitespaces
  20438. r = r.replace(/[\s]/g, function () {
  20439. return "";
  20440. });
  20441. return r.length % 2 ? "!" : "";
  20442. });
  20443. booleanString = booleanString.trim();
  20444. if (booleanString === "!true") {
  20445. booleanString = "false";
  20446. } else if (booleanString === "!false") {
  20447. booleanString = "true";
  20448. }
  20449. return booleanString;
  20450. };
  20451. return AndOrNotEvaluator;
  20452. })();
  20453. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  20454. })(BABYLON.Internals || (BABYLON.Internals = {}));
  20455. var Internals = BABYLON.Internals;
  20456. })(BABYLON || (BABYLON = {}));
  20457. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  20458. var BABYLON;
  20459. (function (BABYLON) {
  20460. var PostProcessRenderPass = (function () {
  20461. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  20462. this._enabled = true;
  20463. this._refCount = 0;
  20464. this._name = name;
  20465. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  20466. this.setRenderList(renderList);
  20467. this._renderTexture.onBeforeRender = beforeRender;
  20468. this._renderTexture.onAfterRender = afterRender;
  20469. this._scene = scene;
  20470. this._renderList = renderList;
  20471. }
  20472. // private
  20473. PostProcessRenderPass.prototype._incRefCount = function () {
  20474. if (this._refCount === 0) {
  20475. this._scene.customRenderTargets.push(this._renderTexture);
  20476. }
  20477. return ++this._refCount;
  20478. };
  20479. PostProcessRenderPass.prototype._decRefCount = function () {
  20480. this._refCount--;
  20481. if (this._refCount <= 0) {
  20482. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  20483. }
  20484. return this._refCount;
  20485. };
  20486. PostProcessRenderPass.prototype._update = function () {
  20487. this.setRenderList(this._renderList);
  20488. };
  20489. // public
  20490. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  20491. this._renderTexture.renderList = renderList;
  20492. };
  20493. PostProcessRenderPass.prototype.getRenderTexture = function () {
  20494. return this._renderTexture;
  20495. };
  20496. return PostProcessRenderPass;
  20497. })();
  20498. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  20499. })(BABYLON || (BABYLON = {}));
  20500. //# sourceMappingURL=babylon.postProcessRenderPass.js.map
  20501. var BABYLON;
  20502. (function (BABYLON) {
  20503. var PostProcessRenderEffect = (function () {
  20504. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  20505. this._engine = engine;
  20506. this._name = name;
  20507. this._singleInstance = singleInstance || true;
  20508. this._getPostProcess = getPostProcess;
  20509. this._cameras = [];
  20510. this._indicesForCamera = [];
  20511. this._postProcesses = {};
  20512. this._renderPasses = {};
  20513. this._renderEffectAsPasses = {};
  20514. }
  20515. PostProcessRenderEffect.prototype._update = function () {
  20516. for (var renderPassName in this._renderPasses) {
  20517. this._renderPasses[renderPassName]._update();
  20518. }
  20519. };
  20520. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  20521. this._renderPasses[renderPass._name] = renderPass;
  20522. this._linkParameters();
  20523. };
  20524. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  20525. delete this._renderPasses[renderPass._name];
  20526. this._linkParameters();
  20527. };
  20528. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  20529. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  20530. this._linkParameters();
  20531. };
  20532. PostProcessRenderEffect.prototype.getPass = function (passName) {
  20533. for (var renderPassName in this._renderPasses) {
  20534. if (renderPassName === passName) {
  20535. return this._renderPasses[passName];
  20536. }
  20537. }
  20538. };
  20539. PostProcessRenderEffect.prototype.emptyPasses = function () {
  20540. this._renderPasses = {};
  20541. this._linkParameters();
  20542. };
  20543. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  20544. var cameraKey;
  20545. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  20546. for (var i = 0; i < _cam.length; i++) {
  20547. var camera = _cam[i];
  20548. var cameraName = camera.name;
  20549. if (this._singleInstance) {
  20550. cameraKey = 0;
  20551. } else {
  20552. cameraKey = cameraName;
  20553. }
  20554. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  20555. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  20556. if (!this._indicesForCamera[cameraName]) {
  20557. this._indicesForCamera[cameraName] = [];
  20558. }
  20559. this._indicesForCamera[cameraName].push(index);
  20560. if (this._cameras.indexOf(camera) === -1) {
  20561. this._cameras[cameraName] = camera;
  20562. }
  20563. for (var passName in this._renderPasses) {
  20564. this._renderPasses[passName]._incRefCount();
  20565. }
  20566. }
  20567. this._linkParameters();
  20568. };
  20569. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  20570. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  20571. for (var i = 0; i < _cam.length; i++) {
  20572. var camera = _cam[i];
  20573. var cameraName = camera.name;
  20574. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  20575. var index = this._cameras.indexOf(cameraName);
  20576. this._indicesForCamera.splice(index, 1);
  20577. this._cameras.splice(index, 1);
  20578. for (var passName in this._renderPasses) {
  20579. this._renderPasses[passName]._decRefCount();
  20580. }
  20581. }
  20582. };
  20583. PostProcessRenderEffect.prototype._enable = function (cameras) {
  20584. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  20585. for (var i = 0; i < _cam.length; i++) {
  20586. var camera = _cam[i];
  20587. var cameraName = camera.name;
  20588. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  20589. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  20590. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  20591. }
  20592. }
  20593. for (var passName in this._renderPasses) {
  20594. this._renderPasses[passName]._incRefCount();
  20595. }
  20596. }
  20597. };
  20598. PostProcessRenderEffect.prototype._disable = function (cameras) {
  20599. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  20600. for (var i = 0; i < _cam.length; i++) {
  20601. var camera = _cam[i];
  20602. var cameraName = camera.Name;
  20603. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  20604. for (var passName in this._renderPasses) {
  20605. this._renderPasses[passName]._decRefCount();
  20606. }
  20607. }
  20608. };
  20609. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  20610. if (this._singleInstance) {
  20611. return this._postProcesses[0];
  20612. } else {
  20613. return this._postProcesses[camera.name];
  20614. }
  20615. };
  20616. PostProcessRenderEffect.prototype._linkParameters = function () {
  20617. var _this = this;
  20618. for (var index in this._postProcesses) {
  20619. if (this.applyParameters) {
  20620. this.applyParameters(this._postProcesses[index]);
  20621. }
  20622. this._postProcesses[index].onBeforeRender = function (effect) {
  20623. _this._linkTextures(effect);
  20624. };
  20625. }
  20626. };
  20627. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  20628. for (var renderPassName in this._renderPasses) {
  20629. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  20630. }
  20631. for (var renderEffectName in this._renderEffectAsPasses) {
  20632. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  20633. }
  20634. };
  20635. return PostProcessRenderEffect;
  20636. })();
  20637. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  20638. })(BABYLON || (BABYLON = {}));
  20639. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  20640. var BABYLON;
  20641. (function (BABYLON) {
  20642. var PostProcessRenderPipeline = (function () {
  20643. function PostProcessRenderPipeline(engine, name) {
  20644. this._engine = engine;
  20645. this._name = name;
  20646. this._renderEffects = {};
  20647. this._renderEffectsForIsolatedPass = {};
  20648. this._cameras = [];
  20649. }
  20650. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  20651. this._renderEffects[renderEffect._name] = renderEffect;
  20652. };
  20653. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  20654. var renderEffects = this._renderEffects[renderEffectName];
  20655. if (!renderEffects) {
  20656. return;
  20657. }
  20658. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  20659. };
  20660. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  20661. var renderEffects = this._renderEffects[renderEffectName];
  20662. if (!renderEffects) {
  20663. return;
  20664. }
  20665. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  20666. };
  20667. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  20668. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  20669. var indicesToDelete = [];
  20670. for (var i = 0; i < _cam.length; i++) {
  20671. var camera = _cam[i];
  20672. var cameraName = camera.name;
  20673. if (this._cameras.indexOf(camera) === -1) {
  20674. this._cameras[cameraName] = camera;
  20675. } else if (unique) {
  20676. indicesToDelete.push(i);
  20677. }
  20678. }
  20679. for (var i = 0; i < indicesToDelete.length; i++) {
  20680. cameras.splice(indicesToDelete[i], 1);
  20681. }
  20682. for (var renderEffectName in this._renderEffects) {
  20683. this._renderEffects[renderEffectName]._attachCameras(_cam);
  20684. }
  20685. };
  20686. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  20687. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  20688. for (var renderEffectName in this._renderEffects) {
  20689. this._renderEffects[renderEffectName]._detachCameras(_cam);
  20690. }
  20691. for (var i = 0; i < _cam.length; i++) {
  20692. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  20693. }
  20694. };
  20695. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  20696. var _this = this;
  20697. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  20698. var pass = null;
  20699. for (var renderEffectName in this._renderEffects) {
  20700. pass = this._renderEffects[renderEffectName].getPass(passName);
  20701. if (pass != null) {
  20702. break;
  20703. }
  20704. }
  20705. if (pass === null) {
  20706. return;
  20707. }
  20708. for (var renderEffectName in this._renderEffects) {
  20709. this._renderEffects[renderEffectName]._disable(_cam);
  20710. }
  20711. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  20712. for (var i = 0; i < _cam.length; i++) {
  20713. var camera = _cam[i];
  20714. var cameraName = camera.name;
  20715. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () {
  20716. return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true);
  20717. });
  20718. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  20719. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  20720. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  20721. }
  20722. };
  20723. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  20724. var _this = this;
  20725. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  20726. for (var i = 0; i < _cam.length; i++) {
  20727. var camera = _cam[i];
  20728. var cameraName = camera.name;
  20729. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () {
  20730. return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true);
  20731. });
  20732. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  20733. }
  20734. for (var renderEffectName in this._renderEffects) {
  20735. this._renderEffects[renderEffectName]._enable(_cam);
  20736. }
  20737. };
  20738. PostProcessRenderPipeline.prototype._update = function () {
  20739. for (var renderEffectName in this._renderEffects) {
  20740. this._renderEffects[renderEffectName]._update();
  20741. }
  20742. for (var i = 0; i < this._cameras.length; i++) {
  20743. var cameraName = this._cameras[i].name;
  20744. if (this._renderEffectsForIsolatedPass[cameraName]) {
  20745. this._renderEffectsForIsolatedPass[cameraName]._update();
  20746. }
  20747. }
  20748. };
  20749. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  20750. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  20751. return PostProcessRenderPipeline;
  20752. })();
  20753. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  20754. })(BABYLON || (BABYLON = {}));
  20755. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  20756. var BABYLON;
  20757. (function (BABYLON) {
  20758. var PostProcessRenderPipelineManager = (function () {
  20759. function PostProcessRenderPipelineManager() {
  20760. this._renderPipelines = {};
  20761. }
  20762. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  20763. this._renderPipelines[renderPipeline._name] = renderPipeline;
  20764. };
  20765. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  20766. var renderPipeline = this._renderPipelines[renderPipelineName];
  20767. if (!renderPipeline) {
  20768. return;
  20769. }
  20770. renderPipeline._attachCameras(cameras, unique);
  20771. };
  20772. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  20773. var renderPipeline = this._renderPipelines[renderPipelineName];
  20774. if (!renderPipeline) {
  20775. return;
  20776. }
  20777. renderPipeline._detachCameras(cameras);
  20778. };
  20779. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  20780. var renderPipeline = this._renderPipelines[renderPipelineName];
  20781. if (!renderPipeline) {
  20782. return;
  20783. }
  20784. renderPipeline._enableEffect(renderEffectName, cameras);
  20785. };
  20786. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  20787. var renderPipeline = this._renderPipelines[renderPipelineName];
  20788. if (!renderPipeline) {
  20789. return;
  20790. }
  20791. renderPipeline._disableEffect(renderEffectName, cameras);
  20792. };
  20793. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  20794. var renderPipeline = this._renderPipelines[renderPipelineName];
  20795. if (!renderPipeline) {
  20796. return;
  20797. }
  20798. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  20799. };
  20800. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  20801. var renderPipeline = this._renderPipelines[renderPipelineName];
  20802. if (!renderPipeline) {
  20803. return;
  20804. }
  20805. renderPipeline._disableDisplayOnlyPass(cameras);
  20806. };
  20807. PostProcessRenderPipelineManager.prototype.update = function () {
  20808. for (var renderPipelineName in this._renderPipelines) {
  20809. this._renderPipelines[renderPipelineName]._update();
  20810. }
  20811. };
  20812. return PostProcessRenderPipelineManager;
  20813. })();
  20814. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  20815. })(BABYLON || (BABYLON = {}));
  20816. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  20817. var BABYLON;
  20818. (function (BABYLON) {
  20819. var DisplayPassPostProcess = (function (_super) {
  20820. __extends(DisplayPassPostProcess, _super);
  20821. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  20822. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  20823. }
  20824. return DisplayPassPostProcess;
  20825. })(BABYLON.PostProcess);
  20826. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  20827. })(BABYLON || (BABYLON = {}));
  20828. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  20829. var BABYLON;
  20830. (function (BABYLON) {
  20831. var BoundingBoxRenderer = (function () {
  20832. function BoundingBoxRenderer(scene) {
  20833. this.frontColor = new BABYLON.Color3(1, 1, 1);
  20834. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  20835. this.showBackLines = true;
  20836. this.renderList = new BABYLON.SmartArray(32);
  20837. this._scene = scene;
  20838. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  20839. attributes: ["position"],
  20840. uniforms: ["worldViewProjection", "color"]
  20841. });
  20842. var engine = this._scene.getEngine();
  20843. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  20844. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  20845. 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]);
  20846. }
  20847. BoundingBoxRenderer.prototype.reset = function () {
  20848. this.renderList.reset();
  20849. };
  20850. BoundingBoxRenderer.prototype.render = function () {
  20851. if (this.renderList.length === 0 || !this._colorShader.isReady()) {
  20852. return;
  20853. }
  20854. var engine = this._scene.getEngine();
  20855. engine.setDepthWrite(false);
  20856. this._colorShader._preBind();
  20857. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  20858. var boundingBox = this.renderList.data[boundingBoxIndex];
  20859. var min = boundingBox.minimum;
  20860. var max = boundingBox.maximum;
  20861. var diff = max.subtract(min);
  20862. var median = min.add(diff.scale(0.5));
  20863. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z).multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z)).multiply(boundingBox.getWorldMatrix());
  20864. // VBOs
  20865. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  20866. if (this.showBackLines) {
  20867. // Back
  20868. engine.setDepthFunctionToGreaterOrEqual();
  20869. this._scene.resetCachedMaterial();
  20870. this._colorShader.setColor4("color", this.backColor.toColor4());
  20871. this._colorShader.bind(worldMatrix);
  20872. // Draw order
  20873. engine.draw(false, 0, 24);
  20874. }
  20875. // Front
  20876. engine.setDepthFunctionToLess();
  20877. this._scene.resetCachedMaterial();
  20878. this._colorShader.setColor4("color", this.frontColor.toColor4());
  20879. this._colorShader.bind(worldMatrix);
  20880. // Draw order
  20881. engine.draw(false, 0, 24);
  20882. }
  20883. this._colorShader.unbind();
  20884. engine.setDepthFunctionToLessOrEqual();
  20885. engine.setDepthWrite(true);
  20886. };
  20887. BoundingBoxRenderer.prototype.dispose = function () {
  20888. this._colorShader.dispose();
  20889. this._vb.dispose();
  20890. this._scene.getEngine()._releaseBuffer(this._ib);
  20891. };
  20892. return BoundingBoxRenderer;
  20893. })();
  20894. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  20895. })(BABYLON || (BABYLON = {}));
  20896. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  20897. /**
  20898. * Based on jsTGALoader - Javascript loader for TGA file
  20899. * By Vincent Thibault
  20900. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  20901. */
  20902. var BABYLON;
  20903. (function (BABYLON) {
  20904. (function (Internals) {
  20905. var TGATools = (function () {
  20906. function TGATools() {
  20907. }
  20908. TGATools.GetTGAHeader = function (data) {
  20909. var offset = 0;
  20910. var header = {
  20911. id_length: data[offset++],
  20912. colormap_type: data[offset++],
  20913. image_type: data[offset++],
  20914. colormap_index: data[offset++] | data[offset++] << 8,
  20915. colormap_length: data[offset++] | data[offset++] << 8,
  20916. colormap_size: data[offset++],
  20917. origin: [
  20918. data[offset++] | data[offset++] << 8,
  20919. data[offset++] | data[offset++] << 8
  20920. ],
  20921. width: data[offset++] | data[offset++] << 8,
  20922. height: data[offset++] | data[offset++] << 8,
  20923. pixel_size: data[offset++],
  20924. flags: data[offset++]
  20925. };
  20926. return header;
  20927. };
  20928. TGATools.UploadContent = function (gl, data) {
  20929. // Not enough data to contain header ?
  20930. if (data.length < 19) {
  20931. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  20932. return;
  20933. }
  20934. // Read Header
  20935. var offset = 18;
  20936. var header = TGATools.GetTGAHeader(data);
  20937. // Assume it's a valid Targa file.
  20938. if (header.id_length + offset > data.length) {
  20939. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  20940. return;
  20941. }
  20942. // Skip not needed data
  20943. offset += header.id_length;
  20944. var use_rle = false;
  20945. var use_pal = false;
  20946. var use_rgb = false;
  20947. var use_grey = false;
  20948. switch (header.image_type) {
  20949. case TGATools._TYPE_RLE_INDEXED:
  20950. use_rle = true;
  20951. case TGATools._TYPE_INDEXED:
  20952. use_pal = true;
  20953. break;
  20954. case TGATools._TYPE_RLE_RGB:
  20955. use_rle = true;
  20956. case TGATools._TYPE_RGB:
  20957. use_rgb = true;
  20958. break;
  20959. case TGATools._TYPE_RLE_GREY:
  20960. use_rle = true;
  20961. case TGATools._TYPE_GREY:
  20962. use_grey = true;
  20963. break;
  20964. }
  20965. var pixel_data;
  20966. var numAlphaBits = header.flags & 0xf;
  20967. var pixel_size = header.pixel_size >> 3;
  20968. var pixel_total = header.width * header.height * pixel_size;
  20969. // Read palettes
  20970. var palettes;
  20971. if (use_pal) {
  20972. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  20973. }
  20974. // Read LRE
  20975. if (use_rle) {
  20976. pixel_data = new Uint8Array(pixel_total);
  20977. var c, count, i;
  20978. var localOffset = 0;
  20979. var pixels = new Uint8Array(pixel_size);
  20980. while (offset < pixel_total && localOffset < pixel_total) {
  20981. c = data[offset++];
  20982. count = (c & 0x7f) + 1;
  20983. // RLE pixels
  20984. if (c & 0x80) {
  20985. for (i = 0; i < pixel_size; ++i) {
  20986. pixels[i] = data[offset++];
  20987. }
  20988. for (i = 0; i < count; ++i) {
  20989. pixel_data.set(pixels, localOffset + i * pixel_size);
  20990. }
  20991. localOffset += pixel_size * count;
  20992. } else {
  20993. count *= pixel_size;
  20994. for (i = 0; i < count; ++i) {
  20995. pixel_data[localOffset + i] = data[offset++];
  20996. }
  20997. localOffset += count;
  20998. }
  20999. }
  21000. } else {
  21001. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  21002. }
  21003. // Load to texture
  21004. var x_start, y_start, x_step, y_step, y_end, x_end;
  21005. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  21006. default:
  21007. case TGATools._ORIGIN_UL:
  21008. x_start = 0;
  21009. x_step = 1;
  21010. x_end = header.width;
  21011. y_start = 0;
  21012. y_step = 1;
  21013. y_end = header.height;
  21014. break;
  21015. case TGATools._ORIGIN_BL:
  21016. x_start = 0;
  21017. x_step = 1;
  21018. x_end = header.width;
  21019. y_start = header.height - 1;
  21020. y_step = -1;
  21021. y_end = -1;
  21022. break;
  21023. case TGATools._ORIGIN_UR:
  21024. x_start = header.width - 1;
  21025. x_step = -1;
  21026. x_end = -1;
  21027. y_start = 0;
  21028. y_step = 1;
  21029. y_end = header.height;
  21030. break;
  21031. case TGATools._ORIGIN_BR:
  21032. x_start = header.width - 1;
  21033. x_step = -1;
  21034. x_end = -1;
  21035. y_start = header.height - 1;
  21036. y_step = -1;
  21037. y_end = -1;
  21038. break;
  21039. }
  21040. // Load the specify method
  21041. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  21042. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  21043. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  21044. };
  21045. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  21046. var image = pixel_data, colormap = palettes;
  21047. var width = header.width, height = header.height;
  21048. var color, i = 0, x, y;
  21049. var imageData = new Uint8Array(width * height * 4);
  21050. for (y = y_start; y !== y_end; y += y_step) {
  21051. for (x = x_start; x !== x_end; x += x_step, i++) {
  21052. color = image[i];
  21053. imageData[(x + width * y) * 4 + 3] = 255;
  21054. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  21055. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  21056. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  21057. }
  21058. }
  21059. return imageData;
  21060. };
  21061. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  21062. var image = pixel_data;
  21063. var width = header.width, height = header.height;
  21064. var color, i = 0, x, y;
  21065. var imageData = new Uint8Array(width * height * 4);
  21066. for (y = y_start; y !== y_end; y += y_step) {
  21067. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  21068. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  21069. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  21070. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  21071. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  21072. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  21073. }
  21074. }
  21075. return imageData;
  21076. };
  21077. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  21078. var image = pixel_data;
  21079. var width = header.width, height = header.height;
  21080. var i = 0, x, y;
  21081. var imageData = new Uint8Array(width * height * 4);
  21082. for (y = y_start; y !== y_end; y += y_step) {
  21083. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  21084. imageData[(x + width * y) * 4 + 3] = 255;
  21085. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  21086. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  21087. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  21088. }
  21089. }
  21090. return imageData;
  21091. };
  21092. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  21093. var image = pixel_data;
  21094. var width = header.width, height = header.height;
  21095. var i = 0, x, y;
  21096. var imageData = new Uint8Array(width * height * 4);
  21097. for (y = y_start; y !== y_end; y += y_step) {
  21098. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  21099. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  21100. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  21101. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  21102. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  21103. }
  21104. }
  21105. return imageData;
  21106. };
  21107. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  21108. var image = pixel_data;
  21109. var width = header.width, height = header.height;
  21110. var color, i = 0, x, y;
  21111. var imageData = new Uint8Array(width * height * 4);
  21112. for (y = y_start; y !== y_end; y += y_step) {
  21113. for (x = x_start; x !== x_end; x += x_step, i++) {
  21114. color = image[i];
  21115. imageData[(x + width * y) * 4 + 0] = color;
  21116. imageData[(x + width * y) * 4 + 1] = color;
  21117. imageData[(x + width * y) * 4 + 2] = color;
  21118. imageData[(x + width * y) * 4 + 3] = 255;
  21119. }
  21120. }
  21121. return imageData;
  21122. };
  21123. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  21124. var image = pixel_data;
  21125. var width = header.width, height = header.height;
  21126. var i = 0, x, y;
  21127. var imageData = new Uint8Array(width * height * 4);
  21128. for (y = y_start; y !== y_end; y += y_step) {
  21129. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  21130. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  21131. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  21132. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  21133. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  21134. }
  21135. }
  21136. return imageData;
  21137. };
  21138. TGATools._TYPE_NO_DATA = 0;
  21139. TGATools._TYPE_INDEXED = 1;
  21140. TGATools._TYPE_RGB = 2;
  21141. TGATools._TYPE_GREY = 3;
  21142. TGATools._TYPE_RLE_INDEXED = 9;
  21143. TGATools._TYPE_RLE_RGB = 10;
  21144. TGATools._TYPE_RLE_GREY = 11;
  21145. TGATools._ORIGIN_MASK = 0x30;
  21146. TGATools._ORIGIN_SHIFT = 0x04;
  21147. TGATools._ORIGIN_BL = 0x00;
  21148. TGATools._ORIGIN_BR = 0x01;
  21149. TGATools._ORIGIN_UL = 0x02;
  21150. TGATools._ORIGIN_UR = 0x03;
  21151. return TGATools;
  21152. })();
  21153. Internals.TGATools = TGATools;
  21154. })(BABYLON.Internals || (BABYLON.Internals = {}));
  21155. var Internals = BABYLON.Internals;
  21156. })(BABYLON || (BABYLON = {}));
  21157. //# sourceMappingURL=babylon.tools.tga.js.map
  21158. var BABYLON;
  21159. (function (BABYLON) {
  21160. (function (Internals) {
  21161. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  21162. // All values and structures referenced from:
  21163. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  21164. var DDS_MAGIC = 0x20534444;
  21165. 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;
  21166. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  21167. 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;
  21168. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  21169. function FourCCToInt32(value) {
  21170. return value.charCodeAt(0) + (value.charCodeAt(1) << 8) + (value.charCodeAt(2) << 16) + (value.charCodeAt(3) << 24);
  21171. }
  21172. function Int32ToFourCC(value) {
  21173. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  21174. }
  21175. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  21176. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  21177. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  21178. var headerLengthInt = 31;
  21179. // Offsets into the header array
  21180. var off_magic = 0;
  21181. var off_size = 1;
  21182. var off_flags = 2;
  21183. var off_height = 3;
  21184. var off_width = 4;
  21185. var off_mipmapCount = 7;
  21186. var off_pfFlags = 20;
  21187. var off_pfFourCC = 21;
  21188. var off_RGBbpp = 22;
  21189. var off_RMask = 23;
  21190. var off_GMask = 24;
  21191. var off_BMask = 25;
  21192. var off_AMask = 26;
  21193. var off_caps1 = 27;
  21194. var off_caps2 = 28;
  21195. ;
  21196. var DDSTools = (function () {
  21197. function DDSTools() {
  21198. }
  21199. DDSTools.GetDDSInfo = function (arrayBuffer) {
  21200. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  21201. var mipmapCount = 1;
  21202. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  21203. mipmapCount = Math.max(1, header[off_mipmapCount]);
  21204. }
  21205. return {
  21206. width: header[off_width],
  21207. height: header[off_height],
  21208. mipmapCount: mipmapCount,
  21209. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  21210. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  21211. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  21212. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  21213. };
  21214. };
  21215. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  21216. var byteArray = new Uint8Array(dataLength);
  21217. var srcData = new Uint8Array(arrayBuffer);
  21218. var index = 0;
  21219. for (var y = height - 1; y >= 0; y--) {
  21220. for (var x = 0; x < width; x++) {
  21221. var srcPos = dataOffset + (x + y * width) * 4;
  21222. byteArray[index + 2] = srcData[srcPos];
  21223. byteArray[index + 1] = srcData[srcPos + 1];
  21224. byteArray[index] = srcData[srcPos + 2];
  21225. byteArray[index + 3] = srcData[srcPos + 3];
  21226. index += 4;
  21227. }
  21228. }
  21229. return byteArray;
  21230. };
  21231. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  21232. var byteArray = new Uint8Array(dataLength);
  21233. var srcData = new Uint8Array(arrayBuffer);
  21234. var index = 0;
  21235. for (var y = height - 1; y >= 0; y--) {
  21236. for (var x = 0; x < width; x++) {
  21237. var srcPos = dataOffset + (x + y * width) * 3;
  21238. byteArray[index + 2] = srcData[srcPos];
  21239. byteArray[index + 1] = srcData[srcPos + 1];
  21240. byteArray[index] = srcData[srcPos + 2];
  21241. index += 3;
  21242. }
  21243. }
  21244. return byteArray;
  21245. };
  21246. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  21247. var byteArray = new Uint8Array(dataLength);
  21248. var srcData = new Uint8Array(arrayBuffer);
  21249. var index = 0;
  21250. for (var y = height - 1; y >= 0; y--) {
  21251. for (var x = 0; x < width; x++) {
  21252. var srcPos = dataOffset + (x + y * width);
  21253. byteArray[index] = srcData[srcPos];
  21254. index++;
  21255. }
  21256. }
  21257. return byteArray;
  21258. };
  21259. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  21260. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  21261. if (header[off_magic] != DDS_MAGIC) {
  21262. BABYLON.Tools.Error("Invalid magic number in DDS header");
  21263. return;
  21264. }
  21265. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  21266. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  21267. return;
  21268. }
  21269. if (info.isFourCC) {
  21270. fourCC = header[off_pfFourCC];
  21271. switch (fourCC) {
  21272. case FOURCC_DXT1:
  21273. blockBytes = 8;
  21274. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  21275. break;
  21276. case FOURCC_DXT3:
  21277. blockBytes = 16;
  21278. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  21279. break;
  21280. case FOURCC_DXT5:
  21281. blockBytes = 16;
  21282. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  21283. break;
  21284. default:
  21285. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  21286. return;
  21287. }
  21288. }
  21289. mipmapCount = 1;
  21290. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  21291. mipmapCount = Math.max(1, header[off_mipmapCount]);
  21292. }
  21293. var bpp = header[off_RGBbpp];
  21294. for (var face = 0; face < faces; face++) {
  21295. var sampler = faces == 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  21296. width = header[off_width];
  21297. height = header[off_height];
  21298. dataOffset = header[off_size] + 4;
  21299. for (i = 0; i < mipmapCount; ++i) {
  21300. if (info.isRGB) {
  21301. if (bpp == 24) {
  21302. dataLength = width * height * 3;
  21303. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  21304. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  21305. } else {
  21306. dataLength = width * height * 4;
  21307. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  21308. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  21309. }
  21310. } else if (info.isLuminance) {
  21311. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  21312. var unpaddedRowSize = width;
  21313. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  21314. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  21315. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  21316. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  21317. } else {
  21318. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  21319. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  21320. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  21321. }
  21322. dataOffset += dataLength;
  21323. width *= 0.5;
  21324. height *= 0.5;
  21325. width = Math.max(1.0, width);
  21326. height = Math.max(1.0, height);
  21327. }
  21328. }
  21329. };
  21330. return DDSTools;
  21331. })();
  21332. Internals.DDSTools = DDSTools;
  21333. })(BABYLON.Internals || (BABYLON.Internals = {}));
  21334. var Internals = BABYLON.Internals;
  21335. })(BABYLON || (BABYLON = {}));
  21336. //# sourceMappingURL=babylon.tools.dds.js.map
  21337. var BABYLON;
  21338. (function (BABYLON) {
  21339. var SmartArray = (function () {
  21340. function SmartArray(capacity) {
  21341. this.length = 0;
  21342. this._duplicateId = 0;
  21343. this.data = new Array(capacity);
  21344. this._id = SmartArray._GlobalId++;
  21345. }
  21346. SmartArray.prototype.push = function (value) {
  21347. this.data[this.length++] = value;
  21348. if (this.length > this.data.length) {
  21349. this.data.length *= 2;
  21350. }
  21351. if (!value.__smartArrayFlags) {
  21352. value.__smartArrayFlags = {};
  21353. }
  21354. value.__smartArrayFlags[this._id] = this._duplicateId;
  21355. };
  21356. SmartArray.prototype.pushNoDuplicate = function (value) {
  21357. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  21358. return;
  21359. }
  21360. this.push(value);
  21361. };
  21362. SmartArray.prototype.sort = function (compareFn) {
  21363. this.data.sort(compareFn);
  21364. };
  21365. SmartArray.prototype.reset = function () {
  21366. this.length = 0;
  21367. this._duplicateId++;
  21368. };
  21369. SmartArray.prototype.concat = function (array) {
  21370. if (array.length === 0) {
  21371. return;
  21372. }
  21373. if (this.length + array.length > this.data.length) {
  21374. this.data.length = (this.length + array.length) * 2;
  21375. }
  21376. for (var index = 0; index < array.length; index++) {
  21377. this.data[this.length++] = (array.data || array)[index];
  21378. }
  21379. };
  21380. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  21381. if (array.length === 0) {
  21382. return;
  21383. }
  21384. if (this.length + array.length > this.data.length) {
  21385. this.data.length = (this.length + array.length) * 2;
  21386. }
  21387. for (var index = 0; index < array.length; index++) {
  21388. var item = (array.data || array)[index];
  21389. this.pushNoDuplicate(item);
  21390. }
  21391. };
  21392. SmartArray.prototype.indexOf = function (value) {
  21393. var position = this.data.indexOf(value);
  21394. if (position >= this.length) {
  21395. return -1;
  21396. }
  21397. return position;
  21398. };
  21399. SmartArray._GlobalId = 0;
  21400. return SmartArray;
  21401. })();
  21402. BABYLON.SmartArray = SmartArray;
  21403. })(BABYLON || (BABYLON = {}));
  21404. //# sourceMappingURL=babylon.smartArray.js.map
  21405. var BABYLON;
  21406. (function (BABYLON) {
  21407. var CannonJSPlugin = (function () {
  21408. function CannonJSPlugin() {
  21409. this._registeredMeshes = [];
  21410. this._physicsMaterials = [];
  21411. this.updateBodyPosition = function (mesh) {
  21412. for (var index = 0; index < this._registeredMeshes.length; index++) {
  21413. var registeredMesh = this._registeredMeshes[index];
  21414. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  21415. var body = registeredMesh.body;
  21416. var center = mesh.getBoundingInfo().boundingBox.center;
  21417. body.position.set(center.x, center.z, center.y);
  21418. body.quaternion.x = mesh.rotationQuaternion.x;
  21419. body.quaternion.z = mesh.rotationQuaternion.y;
  21420. body.quaternion.y = mesh.rotationQuaternion.z;
  21421. body.quaternion.w = -mesh.rotationQuaternion.w;
  21422. return;
  21423. }
  21424. }
  21425. };
  21426. }
  21427. CannonJSPlugin.prototype.initialize = function (iterations) {
  21428. if (typeof iterations === "undefined") { iterations = 10; }
  21429. this._world = new CANNON.World();
  21430. this._world.broadphase = new CANNON.NaiveBroadphase();
  21431. this._world.solver.iterations = iterations;
  21432. };
  21433. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  21434. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  21435. };
  21436. CannonJSPlugin.prototype.runOneStep = function (delta) {
  21437. this._world.step(delta);
  21438. for (var index = 0; index < this._registeredMeshes.length; index++) {
  21439. var registeredMesh = this._registeredMeshes[index];
  21440. if (registeredMesh.isChild) {
  21441. continue;
  21442. }
  21443. // Body position
  21444. var bodyX = registeredMesh.body.position.x, bodyY = registeredMesh.body.position.y, bodyZ = registeredMesh.body.position.z;
  21445. var deltaPos = registeredMesh.delta;
  21446. if (deltaPos) {
  21447. registeredMesh.mesh.position.x = bodyX + deltaPos.x;
  21448. registeredMesh.mesh.position.y = bodyZ + deltaPos.y;
  21449. registeredMesh.mesh.position.z = bodyY + deltaPos.z;
  21450. } else {
  21451. registeredMesh.mesh.position.x = bodyX;
  21452. registeredMesh.mesh.position.y = bodyZ;
  21453. registeredMesh.mesh.position.z = bodyY;
  21454. }
  21455. if (!registeredMesh.mesh.rotationQuaternion) {
  21456. registeredMesh.mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  21457. }
  21458. registeredMesh.mesh.rotationQuaternion.x = registeredMesh.body.quaternion.x;
  21459. registeredMesh.mesh.rotationQuaternion.y = registeredMesh.body.quaternion.z;
  21460. registeredMesh.mesh.rotationQuaternion.z = registeredMesh.body.quaternion.y;
  21461. registeredMesh.mesh.rotationQuaternion.w = -registeredMesh.body.quaternion.w;
  21462. }
  21463. };
  21464. CannonJSPlugin.prototype.setGravity = function (gravity) {
  21465. this._world.gravity.set(gravity.x, gravity.z, gravity.y);
  21466. };
  21467. CannonJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  21468. this.unregisterMesh(mesh);
  21469. mesh.computeWorldMatrix(true);
  21470. switch (impostor) {
  21471. case BABYLON.PhysicsEngine.SphereImpostor:
  21472. var bbox = mesh.getBoundingInfo().boundingBox;
  21473. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  21474. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  21475. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  21476. return this._createSphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2, mesh, options);
  21477. case BABYLON.PhysicsEngine.BoxImpostor:
  21478. bbox = mesh.getBoundingInfo().boundingBox;
  21479. var min = bbox.minimumWorld;
  21480. var max = bbox.maximumWorld;
  21481. var box = max.subtract(min).scale(0.5);
  21482. return this._createBox(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z), mesh, options);
  21483. case BABYLON.PhysicsEngine.PlaneImpostor:
  21484. return this._createPlane(mesh, options);
  21485. case BABYLON.PhysicsEngine.MeshImpostor:
  21486. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21487. var rawFaces = mesh.getIndices();
  21488. return this._createConvexPolyhedron(rawVerts, rawFaces, mesh, options);
  21489. }
  21490. return null;
  21491. };
  21492. CannonJSPlugin.prototype._createSphere = function (radius, mesh, options) {
  21493. var shape = new CANNON.Sphere(radius);
  21494. if (!options) {
  21495. return shape;
  21496. }
  21497. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  21498. };
  21499. CannonJSPlugin.prototype._createBox = function (x, y, z, mesh, options) {
  21500. var shape = new CANNON.Box(new CANNON.Vec3(x, z, y));
  21501. if (!options) {
  21502. return shape;
  21503. }
  21504. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  21505. };
  21506. CannonJSPlugin.prototype._createPlane = function (mesh, options) {
  21507. var shape = new CANNON.Plane();
  21508. if (!options) {
  21509. return shape;
  21510. }
  21511. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  21512. };
  21513. CannonJSPlugin.prototype._createConvexPolyhedron = function (rawVerts, rawFaces, mesh, options) {
  21514. var verts = [], faces = [];
  21515. mesh.computeWorldMatrix(true);
  21516. for (var i = 0; i < rawVerts.length; i += 3) {
  21517. var transformed = BABYLON.Vector3.Zero();
  21518. BABYLON.Vector3.TransformNormalFromFloatsToRef(rawVerts[i], rawVerts[i + 1], rawVerts[i + 2], mesh.getWorldMatrix(), transformed);
  21519. verts.push(new CANNON.Vec3(transformed.x, transformed.z, transformed.y));
  21520. }
  21521. for (var j = 0; j < rawFaces.length; j += 3) {
  21522. faces.push([rawFaces[j], rawFaces[j + 2], rawFaces[j + 1]]);
  21523. }
  21524. var shape = new CANNON.ConvexPolyhedron(verts, faces);
  21525. if (!options) {
  21526. return shape;
  21527. }
  21528. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  21529. };
  21530. CannonJSPlugin.prototype._addMaterial = function (friction, restitution) {
  21531. var index;
  21532. var mat;
  21533. for (index = 0; index < this._physicsMaterials.length; index++) {
  21534. mat = this._physicsMaterials[index];
  21535. if (mat.friction === friction && mat.restitution === restitution) {
  21536. return mat;
  21537. }
  21538. }
  21539. var currentMat = new CANNON.Material();
  21540. currentMat.friction = friction;
  21541. currentMat.restitution = restitution;
  21542. this._physicsMaterials.push(currentMat);
  21543. for (index = 0; index < this._physicsMaterials.length; index++) {
  21544. mat = this._physicsMaterials[index];
  21545. var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, mat.friction * currentMat.friction, mat.restitution * currentMat.restitution);
  21546. contactMaterial.contactEquationStiffness = 1e10;
  21547. contactMaterial.contactEquationRegularizationTime = 10;
  21548. this._world.addContactMaterial(contactMaterial);
  21549. }
  21550. return currentMat;
  21551. };
  21552. CannonJSPlugin.prototype._createRigidBodyFromShape = function (shape, mesh, mass, friction, restitution) {
  21553. var initialRotation = null;
  21554. if (mesh.rotationQuaternion) {
  21555. initialRotation = mesh.rotationQuaternion.clone();
  21556. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  21557. }
  21558. // The delta between the mesh position and the mesh bounding box center
  21559. var bbox = mesh.getBoundingInfo().boundingBox;
  21560. var deltaPosition = mesh.position.subtract(bbox.center);
  21561. var material = this._addMaterial(friction, restitution);
  21562. var body = new CANNON.RigidBody(mass, shape, material);
  21563. if (initialRotation) {
  21564. body.quaternion.x = initialRotation.x;
  21565. body.quaternion.z = initialRotation.y;
  21566. body.quaternion.y = initialRotation.z;
  21567. body.quaternion.w = -initialRotation.w;
  21568. }
  21569. body.position.set(bbox.center.x, bbox.center.z, bbox.center.y);
  21570. this._world.add(body);
  21571. this._registeredMeshes.push({ mesh: mesh, body: body, material: material, delta: deltaPosition });
  21572. return body;
  21573. };
  21574. CannonJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  21575. var compoundShape = new CANNON.Compound();
  21576. for (var index = 0; index < parts.length; index++) {
  21577. var mesh = parts[index].mesh;
  21578. var shape = this.registerMesh(mesh, parts[index].impostor);
  21579. if (index == 0) {
  21580. compoundShape.addChild(shape, new CANNON.Vec3(0, 0, 0));
  21581. } else {
  21582. compoundShape.addChild(shape, new CANNON.Vec3(mesh.position.x, mesh.position.z, mesh.position.y));
  21583. }
  21584. }
  21585. var initialMesh = parts[0].mesh;
  21586. var body = this._createRigidBodyFromShape(compoundShape, initialMesh, options.mass, options.friction, options.restitution);
  21587. body.parts = parts;
  21588. return body;
  21589. };
  21590. CannonJSPlugin.prototype._unbindBody = function (body) {
  21591. for (var index = 0; index < this._registeredMeshes.length; index++) {
  21592. var registeredMesh = this._registeredMeshes[index];
  21593. if (registeredMesh.body === body) {
  21594. registeredMesh.body = null;
  21595. registeredMesh.delta = 0;
  21596. }
  21597. }
  21598. };
  21599. CannonJSPlugin.prototype.unregisterMesh = function (mesh) {
  21600. for (var index = 0; index < this._registeredMeshes.length; index++) {
  21601. var registeredMesh = this._registeredMeshes[index];
  21602. if (registeredMesh.mesh === mesh) {
  21603. // Remove body
  21604. if (registeredMesh.body) {
  21605. this._world.remove(registeredMesh.body);
  21606. this._unbindBody(registeredMesh.body);
  21607. }
  21608. this._registeredMeshes.splice(index, 1);
  21609. return;
  21610. }
  21611. }
  21612. };
  21613. CannonJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  21614. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.z, contactPoint.y);
  21615. var impulse = new CANNON.Vec3(force.x, force.z, force.y);
  21616. for (var index = 0; index < this._registeredMeshes.length; index++) {
  21617. var registeredMesh = this._registeredMeshes[index];
  21618. if (registeredMesh.mesh === mesh) {
  21619. registeredMesh.body.applyImpulse(impulse, worldPoint);
  21620. return;
  21621. }
  21622. }
  21623. };
  21624. CannonJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2) {
  21625. var body1 = null, body2 = null;
  21626. for (var index = 0; index < this._registeredMeshes.length; index++) {
  21627. var registeredMesh = this._registeredMeshes[index];
  21628. if (registeredMesh.mesh === mesh1) {
  21629. body1 = registeredMesh.body;
  21630. } else if (registeredMesh.mesh === mesh2) {
  21631. body2 = registeredMesh.body;
  21632. }
  21633. }
  21634. if (!body1 || !body2) {
  21635. return false;
  21636. }
  21637. 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));
  21638. this._world.addConstraint(constraint);
  21639. return true;
  21640. };
  21641. CannonJSPlugin.prototype.dispose = function () {
  21642. while (this._registeredMeshes.length) {
  21643. this.unregisterMesh(this._registeredMeshes[0].mesh);
  21644. }
  21645. };
  21646. CannonJSPlugin.prototype.isSupported = function () {
  21647. return window.CANNON !== undefined;
  21648. };
  21649. return CannonJSPlugin;
  21650. })();
  21651. BABYLON.CannonJSPlugin = CannonJSPlugin;
  21652. })(BABYLON || (BABYLON = {}));
  21653. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  21654. var BABYLON;
  21655. (function (BABYLON) {
  21656. var Condition = (function () {
  21657. function Condition(actionManager) {
  21658. this._actionManager = actionManager;
  21659. }
  21660. Condition.prototype.isValid = function () {
  21661. return true;
  21662. };
  21663. Condition.prototype._getProperty = function (propertyPath) {
  21664. return this._actionManager._getProperty(propertyPath);
  21665. };
  21666. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  21667. return this._actionManager._getEffectiveTarget(target, propertyPath);
  21668. };
  21669. return Condition;
  21670. })();
  21671. BABYLON.Condition = Condition;
  21672. var ValueCondition = (function (_super) {
  21673. __extends(ValueCondition, _super);
  21674. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  21675. if (typeof operator === "undefined") { operator = ValueCondition.IsEqual; }
  21676. _super.call(this, actionManager);
  21677. this.propertyPath = propertyPath;
  21678. this.value = value;
  21679. this.operator = operator;
  21680. this._target = this._getEffectiveTarget(target, this.propertyPath);
  21681. this._property = this._getProperty(this.propertyPath);
  21682. }
  21683. Object.defineProperty(ValueCondition, "IsEqual", {
  21684. get: function () {
  21685. return ValueCondition._IsEqual;
  21686. },
  21687. enumerable: true,
  21688. configurable: true
  21689. });
  21690. Object.defineProperty(ValueCondition, "IsDifferent", {
  21691. get: function () {
  21692. return ValueCondition._IsDifferent;
  21693. },
  21694. enumerable: true,
  21695. configurable: true
  21696. });
  21697. Object.defineProperty(ValueCondition, "IsGreater", {
  21698. get: function () {
  21699. return ValueCondition._IsGreater;
  21700. },
  21701. enumerable: true,
  21702. configurable: true
  21703. });
  21704. Object.defineProperty(ValueCondition, "IsLesser", {
  21705. get: function () {
  21706. return ValueCondition._IsLesser;
  21707. },
  21708. enumerable: true,
  21709. configurable: true
  21710. });
  21711. // Methods
  21712. ValueCondition.prototype.isValid = function () {
  21713. switch (this.operator) {
  21714. case ValueCondition.IsGreater:
  21715. return this._target[this._property] > this.value;
  21716. case ValueCondition.IsLesser:
  21717. return this._target[this._property] < this.value;
  21718. case ValueCondition.IsEqual:
  21719. case ValueCondition.IsDifferent:
  21720. var check;
  21721. if (this.value.equals) {
  21722. check = this.value.equals(this._target[this._property]);
  21723. } else {
  21724. check = this.value === this._target[this._property];
  21725. }
  21726. return this.operator === ValueCondition.IsEqual ? check : !check;
  21727. }
  21728. return false;
  21729. };
  21730. ValueCondition._IsEqual = 0;
  21731. ValueCondition._IsDifferent = 1;
  21732. ValueCondition._IsGreater = 2;
  21733. ValueCondition._IsLesser = 3;
  21734. return ValueCondition;
  21735. })(Condition);
  21736. BABYLON.ValueCondition = ValueCondition;
  21737. var PredicateCondition = (function (_super) {
  21738. __extends(PredicateCondition, _super);
  21739. function PredicateCondition(actionManager, predicate) {
  21740. _super.call(this, actionManager);
  21741. this.predicate = predicate;
  21742. }
  21743. PredicateCondition.prototype.isValid = function () {
  21744. return this.predicate();
  21745. };
  21746. return PredicateCondition;
  21747. })(Condition);
  21748. BABYLON.PredicateCondition = PredicateCondition;
  21749. var StateCondition = (function (_super) {
  21750. __extends(StateCondition, _super);
  21751. function StateCondition(actionManager, target, value) {
  21752. _super.call(this, actionManager);
  21753. this.value = value;
  21754. this._target = target;
  21755. }
  21756. // Methods
  21757. StateCondition.prototype.isValid = function () {
  21758. return this._target.state === this.value;
  21759. };
  21760. return StateCondition;
  21761. })(Condition);
  21762. BABYLON.StateCondition = StateCondition;
  21763. })(BABYLON || (BABYLON = {}));
  21764. //# sourceMappingURL=babylon.condition.js.map
  21765. var BABYLON;
  21766. (function (BABYLON) {
  21767. var Action = (function () {
  21768. function Action(triggerOptions, condition) {
  21769. this.triggerOptions = triggerOptions;
  21770. if (triggerOptions.parameter) {
  21771. this.trigger = triggerOptions.trigger;
  21772. this._triggerParameter = triggerOptions.parameter;
  21773. } else {
  21774. this.trigger = triggerOptions;
  21775. }
  21776. this._nextActiveAction = this;
  21777. this._condition = condition;
  21778. }
  21779. // Methods
  21780. Action.prototype._prepare = function () {
  21781. };
  21782. Action.prototype.getTriggerParameter = function () {
  21783. return this._triggerParameter;
  21784. };
  21785. Action.prototype._executeCurrent = function (evt) {
  21786. if (this._condition) {
  21787. var currentRenderId = this._actionManager.getScene().getRenderId();
  21788. // We cache the current evaluation for the current frame
  21789. if (this._condition._evaluationId === currentRenderId) {
  21790. if (!this._condition._currentResult) {
  21791. return;
  21792. }
  21793. } else {
  21794. this._condition._evaluationId = currentRenderId;
  21795. if (!this._condition.isValid()) {
  21796. this._condition._currentResult = false;
  21797. return;
  21798. }
  21799. this._condition._currentResult = true;
  21800. }
  21801. }
  21802. this._nextActiveAction.execute(evt);
  21803. if (this._nextActiveAction._child) {
  21804. if (!this._nextActiveAction._child._actionManager) {
  21805. this._nextActiveAction._child._actionManager = this._actionManager;
  21806. }
  21807. this._nextActiveAction = this._nextActiveAction._child;
  21808. } else {
  21809. this._nextActiveAction = this;
  21810. }
  21811. };
  21812. Action.prototype.execute = function (evt) {
  21813. };
  21814. Action.prototype.then = function (action) {
  21815. this._child = action;
  21816. action._actionManager = this._actionManager;
  21817. action._prepare();
  21818. return action;
  21819. };
  21820. Action.prototype._getProperty = function (propertyPath) {
  21821. return this._actionManager._getProperty(propertyPath);
  21822. };
  21823. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  21824. return this._actionManager._getEffectiveTarget(target, propertyPath);
  21825. };
  21826. return Action;
  21827. })();
  21828. BABYLON.Action = Action;
  21829. })(BABYLON || (BABYLON = {}));
  21830. //# sourceMappingURL=babylon.action.js.map
  21831. var BABYLON;
  21832. (function (BABYLON) {
  21833. var ActionEvent = (function () {
  21834. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent) {
  21835. this.source = source;
  21836. this.pointerX = pointerX;
  21837. this.pointerY = pointerY;
  21838. this.meshUnderPointer = meshUnderPointer;
  21839. this.sourceEvent = sourceEvent;
  21840. }
  21841. ActionEvent.CreateNew = function (source, evt) {
  21842. var scene = source.getScene();
  21843. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  21844. };
  21845. ActionEvent.CreateNewFromScene = function (scene, evt) {
  21846. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  21847. };
  21848. return ActionEvent;
  21849. })();
  21850. BABYLON.ActionEvent = ActionEvent;
  21851. var ActionManager = (function () {
  21852. function ActionManager(scene) {
  21853. // Members
  21854. this.actions = new Array();
  21855. this._scene = scene;
  21856. scene._actionManagers.push(this);
  21857. }
  21858. Object.defineProperty(ActionManager, "NothingTrigger", {
  21859. get: function () {
  21860. return ActionManager._NothingTrigger;
  21861. },
  21862. enumerable: true,
  21863. configurable: true
  21864. });
  21865. Object.defineProperty(ActionManager, "OnPickTrigger", {
  21866. get: function () {
  21867. return ActionManager._OnPickTrigger;
  21868. },
  21869. enumerable: true,
  21870. configurable: true
  21871. });
  21872. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  21873. get: function () {
  21874. return ActionManager._OnLeftPickTrigger;
  21875. },
  21876. enumerable: true,
  21877. configurable: true
  21878. });
  21879. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  21880. get: function () {
  21881. return ActionManager._OnRightPickTrigger;
  21882. },
  21883. enumerable: true,
  21884. configurable: true
  21885. });
  21886. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  21887. get: function () {
  21888. return ActionManager._OnCenterPickTrigger;
  21889. },
  21890. enumerable: true,
  21891. configurable: true
  21892. });
  21893. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  21894. get: function () {
  21895. return ActionManager._OnPointerOverTrigger;
  21896. },
  21897. enumerable: true,
  21898. configurable: true
  21899. });
  21900. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  21901. get: function () {
  21902. return ActionManager._OnPointerOutTrigger;
  21903. },
  21904. enumerable: true,
  21905. configurable: true
  21906. });
  21907. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  21908. get: function () {
  21909. return ActionManager._OnEveryFrameTrigger;
  21910. },
  21911. enumerable: true,
  21912. configurable: true
  21913. });
  21914. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  21915. get: function () {
  21916. return ActionManager._OnIntersectionEnterTrigger;
  21917. },
  21918. enumerable: true,
  21919. configurable: true
  21920. });
  21921. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  21922. get: function () {
  21923. return ActionManager._OnIntersectionExitTrigger;
  21924. },
  21925. enumerable: true,
  21926. configurable: true
  21927. });
  21928. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  21929. get: function () {
  21930. return ActionManager._OnKeyDownTrigger;
  21931. },
  21932. enumerable: true,
  21933. configurable: true
  21934. });
  21935. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  21936. get: function () {
  21937. return ActionManager._OnKeyUpTrigger;
  21938. },
  21939. enumerable: true,
  21940. configurable: true
  21941. });
  21942. // Methods
  21943. ActionManager.prototype.dispose = function () {
  21944. var index = this._scene._actionManagers.indexOf(this);
  21945. if (index > -1) {
  21946. this._scene._actionManagers.splice(index, 1);
  21947. }
  21948. };
  21949. ActionManager.prototype.getScene = function () {
  21950. return this._scene;
  21951. };
  21952. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  21953. for (var index = 0; index < this.actions.length; index++) {
  21954. var action = this.actions[index];
  21955. if (triggers.indexOf(action.trigger) > -1) {
  21956. return true;
  21957. }
  21958. }
  21959. return false;
  21960. };
  21961. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  21962. get: function () {
  21963. for (var index = 0; index < this.actions.length; index++) {
  21964. var action = this.actions[index];
  21965. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  21966. return true;
  21967. }
  21968. }
  21969. return false;
  21970. },
  21971. enumerable: true,
  21972. configurable: true
  21973. });
  21974. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  21975. get: function () {
  21976. for (var index = 0; index < this.actions.length; index++) {
  21977. var action = this.actions[index];
  21978. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnCenterPickTrigger) {
  21979. return true;
  21980. }
  21981. }
  21982. return false;
  21983. },
  21984. enumerable: true,
  21985. configurable: true
  21986. });
  21987. ActionManager.prototype.registerAction = function (action) {
  21988. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  21989. if (this.getScene().actionManager !== this) {
  21990. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  21991. return null;
  21992. }
  21993. }
  21994. this.actions.push(action);
  21995. action._actionManager = this;
  21996. action._prepare();
  21997. return action;
  21998. };
  21999. ActionManager.prototype.processTrigger = function (trigger, evt) {
  22000. for (var index = 0; index < this.actions.length; index++) {
  22001. var action = this.actions[index];
  22002. if (action.trigger === trigger) {
  22003. if (trigger === ActionManager.OnKeyUpTrigger || trigger === ActionManager.OnKeyDownTrigger) {
  22004. var parameter = action.getTriggerParameter();
  22005. if (parameter) {
  22006. if (evt.sourceEvent.key !== parameter) {
  22007. continue;
  22008. }
  22009. }
  22010. }
  22011. action._executeCurrent(evt);
  22012. }
  22013. }
  22014. };
  22015. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  22016. var properties = propertyPath.split(".");
  22017. for (var index = 0; index < properties.length - 1; index++) {
  22018. target = target[properties[index]];
  22019. }
  22020. return target;
  22021. };
  22022. ActionManager.prototype._getProperty = function (propertyPath) {
  22023. var properties = propertyPath.split(".");
  22024. return properties[properties.length - 1];
  22025. };
  22026. ActionManager._NothingTrigger = 0;
  22027. ActionManager._OnPickTrigger = 1;
  22028. ActionManager._OnLeftPickTrigger = 2;
  22029. ActionManager._OnRightPickTrigger = 3;
  22030. ActionManager._OnCenterPickTrigger = 4;
  22031. ActionManager._OnPointerOverTrigger = 5;
  22032. ActionManager._OnPointerOutTrigger = 6;
  22033. ActionManager._OnEveryFrameTrigger = 7;
  22034. ActionManager._OnIntersectionEnterTrigger = 8;
  22035. ActionManager._OnIntersectionExitTrigger = 9;
  22036. ActionManager._OnKeyDownTrigger = 10;
  22037. ActionManager._OnKeyUpTrigger = 11;
  22038. return ActionManager;
  22039. })();
  22040. BABYLON.ActionManager = ActionManager;
  22041. })(BABYLON || (BABYLON = {}));
  22042. //# sourceMappingURL=babylon.actionManager.js.map
  22043. var BABYLON;
  22044. (function (BABYLON) {
  22045. var InterpolateValueAction = (function (_super) {
  22046. __extends(InterpolateValueAction, _super);
  22047. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations) {
  22048. if (typeof duration === "undefined") { duration = 1000; }
  22049. _super.call(this, triggerOptions, condition);
  22050. this.propertyPath = propertyPath;
  22051. this.value = value;
  22052. this.duration = duration;
  22053. this.stopOtherAnimations = stopOtherAnimations;
  22054. this._target = target;
  22055. }
  22056. InterpolateValueAction.prototype._prepare = function () {
  22057. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  22058. this._property = this._getProperty(this.propertyPath);
  22059. };
  22060. InterpolateValueAction.prototype.execute = function () {
  22061. var scene = this._actionManager.getScene();
  22062. var keys = [
  22063. {
  22064. frame: 0,
  22065. value: this._target[this._property]
  22066. }, {
  22067. frame: 100,
  22068. value: this.value
  22069. }
  22070. ];
  22071. var dataType;
  22072. if (typeof this.value === "number") {
  22073. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  22074. } else if (this.value instanceof BABYLON.Color3) {
  22075. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  22076. } else if (this.value instanceof BABYLON.Vector3) {
  22077. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  22078. } else if (this.value instanceof BABYLON.Matrix) {
  22079. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  22080. } else if (this.value instanceof BABYLON.Quaternion) {
  22081. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  22082. } else {
  22083. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  22084. return;
  22085. }
  22086. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  22087. animation.setKeys(keys);
  22088. if (this.stopOtherAnimations) {
  22089. scene.stopAnimation(this._target);
  22090. }
  22091. scene.beginDirectAnimation(this._target, [animation], 0, 100);
  22092. };
  22093. return InterpolateValueAction;
  22094. })(BABYLON.Action);
  22095. BABYLON.InterpolateValueAction = InterpolateValueAction;
  22096. })(BABYLON || (BABYLON = {}));
  22097. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  22098. var BABYLON;
  22099. (function (BABYLON) {
  22100. var SwitchBooleanAction = (function (_super) {
  22101. __extends(SwitchBooleanAction, _super);
  22102. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  22103. _super.call(this, triggerOptions, condition);
  22104. this.propertyPath = propertyPath;
  22105. this._target = target;
  22106. }
  22107. SwitchBooleanAction.prototype._prepare = function () {
  22108. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  22109. this._property = this._getProperty(this.propertyPath);
  22110. };
  22111. SwitchBooleanAction.prototype.execute = function () {
  22112. this._target[this._property] = !this._target[this._property];
  22113. };
  22114. return SwitchBooleanAction;
  22115. })(BABYLON.Action);
  22116. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  22117. var SetStateAction = (function (_super) {
  22118. __extends(SetStateAction, _super);
  22119. function SetStateAction(triggerOptions, target, value, condition) {
  22120. _super.call(this, triggerOptions, condition);
  22121. this.value = value;
  22122. this._target = target;
  22123. }
  22124. SetStateAction.prototype.execute = function () {
  22125. this._target.state = this.value;
  22126. };
  22127. return SetStateAction;
  22128. })(BABYLON.Action);
  22129. BABYLON.SetStateAction = SetStateAction;
  22130. var SetValueAction = (function (_super) {
  22131. __extends(SetValueAction, _super);
  22132. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  22133. _super.call(this, triggerOptions, condition);
  22134. this.propertyPath = propertyPath;
  22135. this.value = value;
  22136. this._target = target;
  22137. }
  22138. SetValueAction.prototype._prepare = function () {
  22139. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  22140. this._property = this._getProperty(this.propertyPath);
  22141. };
  22142. SetValueAction.prototype.execute = function () {
  22143. this._target[this._property] = this.value;
  22144. };
  22145. return SetValueAction;
  22146. })(BABYLON.Action);
  22147. BABYLON.SetValueAction = SetValueAction;
  22148. var IncrementValueAction = (function (_super) {
  22149. __extends(IncrementValueAction, _super);
  22150. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  22151. _super.call(this, triggerOptions, condition);
  22152. this.propertyPath = propertyPath;
  22153. this.value = value;
  22154. this._target = target;
  22155. }
  22156. IncrementValueAction.prototype._prepare = function () {
  22157. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  22158. this._property = this._getProperty(this.propertyPath);
  22159. if (typeof this._target[this._property] !== "number") {
  22160. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  22161. }
  22162. };
  22163. IncrementValueAction.prototype.execute = function () {
  22164. this._target[this._property] += this.value;
  22165. };
  22166. return IncrementValueAction;
  22167. })(BABYLON.Action);
  22168. BABYLON.IncrementValueAction = IncrementValueAction;
  22169. var PlayAnimationAction = (function (_super) {
  22170. __extends(PlayAnimationAction, _super);
  22171. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  22172. _super.call(this, triggerOptions, condition);
  22173. this.from = from;
  22174. this.to = to;
  22175. this.loop = loop;
  22176. this._target = target;
  22177. }
  22178. PlayAnimationAction.prototype._prepare = function () {
  22179. };
  22180. PlayAnimationAction.prototype.execute = function () {
  22181. var scene = this._actionManager.getScene();
  22182. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  22183. };
  22184. return PlayAnimationAction;
  22185. })(BABYLON.Action);
  22186. BABYLON.PlayAnimationAction = PlayAnimationAction;
  22187. var StopAnimationAction = (function (_super) {
  22188. __extends(StopAnimationAction, _super);
  22189. function StopAnimationAction(triggerOptions, target, condition) {
  22190. _super.call(this, triggerOptions, condition);
  22191. this._target = target;
  22192. }
  22193. StopAnimationAction.prototype._prepare = function () {
  22194. };
  22195. StopAnimationAction.prototype.execute = function () {
  22196. var scene = this._actionManager.getScene();
  22197. scene.stopAnimation(this._target);
  22198. };
  22199. return StopAnimationAction;
  22200. })(BABYLON.Action);
  22201. BABYLON.StopAnimationAction = StopAnimationAction;
  22202. var DoNothingAction = (function (_super) {
  22203. __extends(DoNothingAction, _super);
  22204. function DoNothingAction(triggerOptions, condition) {
  22205. if (typeof triggerOptions === "undefined") { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  22206. _super.call(this, triggerOptions, condition);
  22207. }
  22208. DoNothingAction.prototype.execute = function () {
  22209. };
  22210. return DoNothingAction;
  22211. })(BABYLON.Action);
  22212. BABYLON.DoNothingAction = DoNothingAction;
  22213. var CombineAction = (function (_super) {
  22214. __extends(CombineAction, _super);
  22215. function CombineAction(triggerOptions, children, condition) {
  22216. _super.call(this, triggerOptions, condition);
  22217. this.children = children;
  22218. }
  22219. CombineAction.prototype._prepare = function () {
  22220. for (var index = 0; index < this.children.length; index++) {
  22221. this.children[index]._actionManager = this._actionManager;
  22222. this.children[index]._prepare();
  22223. }
  22224. };
  22225. CombineAction.prototype.execute = function (evt) {
  22226. for (var index = 0; index < this.children.length; index++) {
  22227. this.children[index].execute(evt);
  22228. }
  22229. };
  22230. return CombineAction;
  22231. })(BABYLON.Action);
  22232. BABYLON.CombineAction = CombineAction;
  22233. var ExecuteCodeAction = (function (_super) {
  22234. __extends(ExecuteCodeAction, _super);
  22235. function ExecuteCodeAction(triggerOptions, func, condition) {
  22236. _super.call(this, triggerOptions, condition);
  22237. this.func = func;
  22238. }
  22239. ExecuteCodeAction.prototype.execute = function (evt) {
  22240. this.func(evt);
  22241. };
  22242. return ExecuteCodeAction;
  22243. })(BABYLON.Action);
  22244. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  22245. var SetParentAction = (function (_super) {
  22246. __extends(SetParentAction, _super);
  22247. function SetParentAction(triggerOptions, target, parent, condition) {
  22248. _super.call(this, triggerOptions, condition);
  22249. this._target = target;
  22250. this._parent = parent;
  22251. }
  22252. SetParentAction.prototype._prepare = function () {
  22253. };
  22254. SetParentAction.prototype.execute = function () {
  22255. if (this._target.parent === this._parent) {
  22256. return;
  22257. }
  22258. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  22259. invertParentWorldMatrix.invert();
  22260. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  22261. this._target.parent = this._parent;
  22262. };
  22263. return SetParentAction;
  22264. })(BABYLON.Action);
  22265. BABYLON.SetParentAction = SetParentAction;
  22266. })(BABYLON || (BABYLON = {}));
  22267. //# sourceMappingURL=babylon.directActions.js.map
  22268. var BABYLON;
  22269. (function (BABYLON) {
  22270. var Geometry = (function () {
  22271. function Geometry(id, scene, vertexData, updatable, mesh) {
  22272. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  22273. this._totalVertices = 0;
  22274. this._indices = [];
  22275. this.id = id;
  22276. this._engine = scene.getEngine();
  22277. this._meshes = [];
  22278. this._scene = scene;
  22279. // vertexData
  22280. if (vertexData) {
  22281. this.setAllVerticesData(vertexData, updatable);
  22282. } else {
  22283. this._totalVertices = 0;
  22284. this._indices = [];
  22285. }
  22286. // applyToMesh
  22287. if (mesh) {
  22288. this.applyToMesh(mesh);
  22289. }
  22290. }
  22291. Geometry.prototype.getScene = function () {
  22292. return this._scene;
  22293. };
  22294. Geometry.prototype.getEngine = function () {
  22295. return this._engine;
  22296. };
  22297. Geometry.prototype.isReady = function () {
  22298. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  22299. };
  22300. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  22301. vertexData.applyToGeometry(this, updatable);
  22302. };
  22303. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  22304. this._vertexBuffers = this._vertexBuffers || {};
  22305. if (this._vertexBuffers[kind]) {
  22306. this._vertexBuffers[kind].dispose();
  22307. }
  22308. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  22309. if (kind === BABYLON.VertexBuffer.PositionKind) {
  22310. stride = this._vertexBuffers[kind].getStrideSize();
  22311. this._totalVertices = data.length / stride;
  22312. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  22313. var meshes = this._meshes;
  22314. var numOfMeshes = meshes.length;
  22315. for (var index = 0; index < numOfMeshes; index++) {
  22316. var mesh = meshes[index];
  22317. mesh._resetPointsArrayCache();
  22318. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  22319. mesh._createGlobalSubMesh();
  22320. mesh.computeWorldMatrix(true);
  22321. }
  22322. }
  22323. };
  22324. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  22325. var vertexBuffer = this.getVertexBuffer(kind);
  22326. if (!vertexBuffer) {
  22327. return;
  22328. }
  22329. vertexBuffer.updateDirectly(data, offset);
  22330. };
  22331. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  22332. var vertexBuffer = this.getVertexBuffer(kind);
  22333. if (!vertexBuffer) {
  22334. return;
  22335. }
  22336. vertexBuffer.update(data);
  22337. if (kind === BABYLON.VertexBuffer.PositionKind) {
  22338. var extend;
  22339. var stride = vertexBuffer.getStrideSize();
  22340. this._totalVertices = data.length / stride;
  22341. if (updateExtends) {
  22342. extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  22343. }
  22344. var meshes = this._meshes;
  22345. var numOfMeshes = meshes.length;
  22346. for (var index = 0; index < numOfMeshes; index++) {
  22347. var mesh = meshes[index];
  22348. mesh._resetPointsArrayCache();
  22349. if (updateExtends) {
  22350. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  22351. }
  22352. }
  22353. }
  22354. };
  22355. Geometry.prototype.getTotalVertices = function () {
  22356. if (!this.isReady()) {
  22357. return 0;
  22358. }
  22359. return this._totalVertices;
  22360. };
  22361. Geometry.prototype.getVerticesData = function (kind) {
  22362. var vertexBuffer = this.getVertexBuffer(kind);
  22363. if (!vertexBuffer) {
  22364. return null;
  22365. }
  22366. return vertexBuffer.getData();
  22367. };
  22368. Geometry.prototype.getVertexBuffer = function (kind) {
  22369. if (!this.isReady()) {
  22370. return null;
  22371. }
  22372. return this._vertexBuffers[kind];
  22373. };
  22374. Geometry.prototype.getVertexBuffers = function () {
  22375. if (!this.isReady()) {
  22376. return null;
  22377. }
  22378. return this._vertexBuffers;
  22379. };
  22380. Geometry.prototype.isVerticesDataPresent = function (kind) {
  22381. if (!this._vertexBuffers) {
  22382. if (this._delayInfo) {
  22383. return this._delayInfo.indexOf(kind) !== -1;
  22384. }
  22385. return false;
  22386. }
  22387. return this._vertexBuffers[kind] !== undefined;
  22388. };
  22389. Geometry.prototype.getVerticesDataKinds = function () {
  22390. var result = [];
  22391. if (!this._vertexBuffers && this._delayInfo) {
  22392. for (var kind in this._delayInfo) {
  22393. result.push(kind);
  22394. }
  22395. } else {
  22396. for (kind in this._vertexBuffers) {
  22397. result.push(kind);
  22398. }
  22399. }
  22400. return result;
  22401. };
  22402. Geometry.prototype.setIndices = function (indices, totalVertices) {
  22403. if (this._indexBuffer) {
  22404. this._engine._releaseBuffer(this._indexBuffer);
  22405. }
  22406. this._indices = indices;
  22407. if (this._meshes.length !== 0 && this._indices) {
  22408. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  22409. }
  22410. if (totalVertices !== undefined) {
  22411. this._totalVertices = totalVertices;
  22412. }
  22413. var meshes = this._meshes;
  22414. var numOfMeshes = meshes.length;
  22415. for (var index = 0; index < numOfMeshes; index++) {
  22416. meshes[index]._createGlobalSubMesh();
  22417. }
  22418. };
  22419. Geometry.prototype.getTotalIndices = function () {
  22420. if (!this.isReady()) {
  22421. return 0;
  22422. }
  22423. return this._indices.length;
  22424. };
  22425. Geometry.prototype.getIndices = function () {
  22426. if (!this.isReady()) {
  22427. return null;
  22428. }
  22429. return this._indices;
  22430. };
  22431. Geometry.prototype.getIndexBuffer = function () {
  22432. if (!this.isReady()) {
  22433. return null;
  22434. }
  22435. return this._indexBuffer;
  22436. };
  22437. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  22438. var meshes = this._meshes;
  22439. var index = meshes.indexOf(mesh);
  22440. if (index === -1) {
  22441. return;
  22442. }
  22443. for (var kind in this._vertexBuffers) {
  22444. this._vertexBuffers[kind].dispose();
  22445. }
  22446. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  22447. this._indexBuffer = null;
  22448. }
  22449. meshes.splice(index, 1);
  22450. mesh._geometry = null;
  22451. if (meshes.length === 0 && shouldDispose) {
  22452. this.dispose();
  22453. }
  22454. };
  22455. Geometry.prototype.applyToMesh = function (mesh) {
  22456. if (mesh._geometry === this) {
  22457. return;
  22458. }
  22459. var previousGeometry = mesh._geometry;
  22460. if (previousGeometry) {
  22461. previousGeometry.releaseForMesh(mesh);
  22462. }
  22463. var meshes = this._meshes;
  22464. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  22465. mesh._geometry = this;
  22466. this._scene.pushGeometry(this);
  22467. meshes.push(mesh);
  22468. if (this.isReady()) {
  22469. this._applyToMesh(mesh);
  22470. } else {
  22471. mesh._boundingInfo = this._boundingInfo;
  22472. }
  22473. };
  22474. Geometry.prototype._applyToMesh = function (mesh) {
  22475. var numOfMeshes = this._meshes.length;
  22476. for (var kind in this._vertexBuffers) {
  22477. if (numOfMeshes === 1) {
  22478. this._vertexBuffers[kind].create();
  22479. }
  22480. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  22481. if (kind === BABYLON.VertexBuffer.PositionKind) {
  22482. mesh._resetPointsArrayCache();
  22483. var extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  22484. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  22485. mesh._createGlobalSubMesh();
  22486. //bounding info was just created again, world matrix should be applied again.
  22487. mesh._updateBoundingInfo();
  22488. }
  22489. }
  22490. // indexBuffer
  22491. if (numOfMeshes === 1 && this._indices) {
  22492. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  22493. }
  22494. if (this._indexBuffer) {
  22495. this._indexBuffer.references = numOfMeshes;
  22496. }
  22497. };
  22498. Geometry.prototype.load = function (scene, onLoaded) {
  22499. var _this = this;
  22500. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  22501. return;
  22502. }
  22503. if (this.isReady()) {
  22504. if (onLoaded) {
  22505. onLoaded();
  22506. }
  22507. return;
  22508. }
  22509. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  22510. scene._addPendingData(this);
  22511. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  22512. _this._delayLoadingFunction(JSON.parse(data), _this);
  22513. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  22514. _this._delayInfo = [];
  22515. scene._removePendingData(_this);
  22516. var meshes = _this._meshes;
  22517. var numOfMeshes = meshes.length;
  22518. for (var index = 0; index < numOfMeshes; index++) {
  22519. _this._applyToMesh(meshes[index]);
  22520. }
  22521. if (onLoaded) {
  22522. onLoaded();
  22523. }
  22524. }, function () {
  22525. }, scene.database);
  22526. };
  22527. Geometry.prototype.dispose = function () {
  22528. var meshes = this._meshes;
  22529. var numOfMeshes = meshes.length;
  22530. var index;
  22531. for (index = 0; index < numOfMeshes; index++) {
  22532. this.releaseForMesh(meshes[index]);
  22533. }
  22534. this._meshes = [];
  22535. for (var kind in this._vertexBuffers) {
  22536. this._vertexBuffers[kind].dispose();
  22537. }
  22538. this._vertexBuffers = [];
  22539. this._totalVertices = 0;
  22540. if (this._indexBuffer) {
  22541. this._engine._releaseBuffer(this._indexBuffer);
  22542. }
  22543. this._indexBuffer = null;
  22544. this._indices = [];
  22545. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  22546. this.delayLoadingFile = null;
  22547. this._delayLoadingFunction = null;
  22548. this._delayInfo = [];
  22549. this._boundingInfo = null; // todo: .dispose()
  22550. var geometries = this._scene.getGeometries();
  22551. index = geometries.indexOf(this);
  22552. if (index > -1) {
  22553. geometries.splice(index, 1);
  22554. }
  22555. };
  22556. Geometry.prototype.copy = function (id) {
  22557. var vertexData = new BABYLON.VertexData();
  22558. vertexData.indices = [];
  22559. var indices = this.getIndices();
  22560. for (var index = 0; index < indices.length; index++) {
  22561. vertexData.indices.push(indices[index]);
  22562. }
  22563. var updatable = false;
  22564. var stopChecking = false;
  22565. for (var kind in this._vertexBuffers) {
  22566. vertexData.set(this.getVerticesData(kind), kind);
  22567. if (!stopChecking) {
  22568. updatable = this.getVertexBuffer(kind).isUpdatable();
  22569. stopChecking = !updatable;
  22570. }
  22571. }
  22572. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  22573. geometry.delayLoadState = this.delayLoadState;
  22574. geometry.delayLoadingFile = this.delayLoadingFile;
  22575. geometry._delayLoadingFunction = this._delayLoadingFunction;
  22576. for (kind in this._delayInfo) {
  22577. geometry._delayInfo = geometry._delayInfo || [];
  22578. geometry._delayInfo.push(kind);
  22579. }
  22580. // Bounding info
  22581. var extend = BABYLON.Tools.ExtractMinAndMax(this.getVerticesData(BABYLON.VertexBuffer.PositionKind), 0, this.getTotalVertices());
  22582. geometry._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  22583. return geometry;
  22584. };
  22585. // Statics
  22586. Geometry.ExtractFromMesh = function (mesh, id) {
  22587. var geometry = mesh._geometry;
  22588. if (!geometry) {
  22589. return null;
  22590. }
  22591. return geometry.copy(id);
  22592. };
  22593. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  22594. // be aware Math.random() could cause collisions
  22595. Geometry.RandomId = function () {
  22596. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  22597. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  22598. return v.toString(16);
  22599. });
  22600. };
  22601. return Geometry;
  22602. })();
  22603. BABYLON.Geometry = Geometry;
  22604. (function (Geometry) {
  22605. /////// Primitives //////////////////////////////////////////////
  22606. (function (Primitives) {
  22607. /// Abstract class
  22608. var _Primitive = (function (_super) {
  22609. __extends(_Primitive, _super);
  22610. function _Primitive(id, scene, vertexData, canBeRegenerated, mesh) {
  22611. this._beingRegenerated = true;
  22612. this._canBeRegenerated = canBeRegenerated;
  22613. _super.call(this, id, scene, vertexData, false, mesh); // updatable = false to be sure not to update vertices
  22614. this._beingRegenerated = false;
  22615. }
  22616. _Primitive.prototype.canBeRegenerated = function () {
  22617. return this._canBeRegenerated;
  22618. };
  22619. _Primitive.prototype.regenerate = function () {
  22620. if (!this._canBeRegenerated) {
  22621. return;
  22622. }
  22623. this._beingRegenerated = true;
  22624. this.setAllVerticesData(this._regenerateVertexData(), false);
  22625. this._beingRegenerated = false;
  22626. };
  22627. _Primitive.prototype.asNewGeometry = function (id) {
  22628. return _super.prototype.copy.call(this, id);
  22629. };
  22630. // overrides
  22631. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  22632. if (!this._beingRegenerated) {
  22633. return;
  22634. }
  22635. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  22636. };
  22637. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  22638. if (!this._beingRegenerated) {
  22639. return;
  22640. }
  22641. _super.prototype.setVerticesData.call(this, kind, data, false);
  22642. };
  22643. // to override
  22644. // protected
  22645. _Primitive.prototype._regenerateVertexData = function () {
  22646. throw new Error("Abstract method");
  22647. };
  22648. _Primitive.prototype.copy = function (id) {
  22649. throw new Error("Must be overriden in sub-classes.");
  22650. };
  22651. return _Primitive;
  22652. })(Geometry);
  22653. Primitives._Primitive = _Primitive;
  22654. var Box = (function (_super) {
  22655. __extends(Box, _super);
  22656. function Box(id, scene, size, canBeRegenerated, mesh) {
  22657. this.size = size;
  22658. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  22659. }
  22660. Box.prototype._regenerateVertexData = function () {
  22661. return BABYLON.VertexData.CreateBox(this.size);
  22662. };
  22663. Box.prototype.copy = function (id) {
  22664. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null);
  22665. };
  22666. return Box;
  22667. })(_Primitive);
  22668. Primitives.Box = Box;
  22669. var Sphere = (function (_super) {
  22670. __extends(Sphere, _super);
  22671. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh) {
  22672. this.segments = segments;
  22673. this.diameter = diameter;
  22674. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  22675. }
  22676. Sphere.prototype._regenerateVertexData = function () {
  22677. return BABYLON.VertexData.CreateSphere(this.segments, this.diameter);
  22678. };
  22679. Sphere.prototype.copy = function (id) {
  22680. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null);
  22681. };
  22682. return Sphere;
  22683. })(_Primitive);
  22684. Primitives.Sphere = Sphere;
  22685. var Cylinder = (function (_super) {
  22686. __extends(Cylinder, _super);
  22687. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh) {
  22688. if (typeof subdivisions === "undefined") { subdivisions = 1; }
  22689. this.height = height;
  22690. this.diameterTop = diameterTop;
  22691. this.diameterBottom = diameterBottom;
  22692. this.tessellation = tessellation;
  22693. this.subdivisions = subdivisions;
  22694. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  22695. }
  22696. Cylinder.prototype._regenerateVertexData = function () {
  22697. return BABYLON.VertexData.CreateCylinder(this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions);
  22698. };
  22699. Cylinder.prototype.copy = function (id) {
  22700. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null);
  22701. };
  22702. return Cylinder;
  22703. })(_Primitive);
  22704. Primitives.Cylinder = Cylinder;
  22705. var Torus = (function (_super) {
  22706. __extends(Torus, _super);
  22707. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh) {
  22708. this.diameter = diameter;
  22709. this.thickness = thickness;
  22710. this.tessellation = tessellation;
  22711. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  22712. }
  22713. Torus.prototype._regenerateVertexData = function () {
  22714. return BABYLON.VertexData.CreateTorus(this.diameter, this.thickness, this.tessellation);
  22715. };
  22716. Torus.prototype.copy = function (id) {
  22717. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null);
  22718. };
  22719. return Torus;
  22720. })(_Primitive);
  22721. Primitives.Torus = Torus;
  22722. var Ground = (function (_super) {
  22723. __extends(Ground, _super);
  22724. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  22725. this.width = width;
  22726. this.height = height;
  22727. this.subdivisions = subdivisions;
  22728. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  22729. }
  22730. Ground.prototype._regenerateVertexData = function () {
  22731. return BABYLON.VertexData.CreateGround(this.width, this.height, this.subdivisions);
  22732. };
  22733. Ground.prototype.copy = function (id) {
  22734. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  22735. };
  22736. return Ground;
  22737. })(_Primitive);
  22738. Primitives.Ground = Ground;
  22739. var TiledGround = (function (_super) {
  22740. __extends(TiledGround, _super);
  22741. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  22742. this.xmin = xmin;
  22743. this.zmin = zmin;
  22744. this.xmax = xmax;
  22745. this.zmax = zmax;
  22746. this.subdivisions = subdivisions;
  22747. this.precision = precision;
  22748. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  22749. }
  22750. TiledGround.prototype._regenerateVertexData = function () {
  22751. return BABYLON.VertexData.CreateTiledGround(this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision);
  22752. };
  22753. TiledGround.prototype.copy = function (id) {
  22754. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  22755. };
  22756. return TiledGround;
  22757. })(_Primitive);
  22758. Primitives.TiledGround = TiledGround;
  22759. var Plane = (function (_super) {
  22760. __extends(Plane, _super);
  22761. function Plane(id, scene, size, canBeRegenerated, mesh) {
  22762. this.size = size;
  22763. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  22764. }
  22765. Plane.prototype._regenerateVertexData = function () {
  22766. return BABYLON.VertexData.CreatePlane(this.size);
  22767. };
  22768. Plane.prototype.copy = function (id) {
  22769. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null);
  22770. };
  22771. return Plane;
  22772. })(_Primitive);
  22773. Primitives.Plane = Plane;
  22774. var TorusKnot = (function (_super) {
  22775. __extends(TorusKnot, _super);
  22776. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh) {
  22777. this.radius = radius;
  22778. this.tube = tube;
  22779. this.radialSegments = radialSegments;
  22780. this.tubularSegments = tubularSegments;
  22781. this.p = p;
  22782. this.q = q;
  22783. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  22784. }
  22785. TorusKnot.prototype._regenerateVertexData = function () {
  22786. return BABYLON.VertexData.CreateTorusKnot(this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q);
  22787. };
  22788. TorusKnot.prototype.copy = function (id) {
  22789. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null);
  22790. };
  22791. return TorusKnot;
  22792. })(_Primitive);
  22793. Primitives.TorusKnot = TorusKnot;
  22794. })(Geometry.Primitives || (Geometry.Primitives = {}));
  22795. var Primitives = Geometry.Primitives;
  22796. })(BABYLON.Geometry || (BABYLON.Geometry = {}));
  22797. var Geometry = BABYLON.Geometry;
  22798. })(BABYLON || (BABYLON = {}));
  22799. //# sourceMappingURL=babylon.geometry.js.map
  22800. var BABYLON;
  22801. (function (BABYLON) {
  22802. var Gamepads = (function () {
  22803. function Gamepads(ongamedpadconnected) {
  22804. var _this = this;
  22805. this.babylonGamepads = [];
  22806. this.oneGamepadConnected = false;
  22807. this.isMonitoring = false;
  22808. this.gamepadEventSupported = 'GamepadEvent' in window;
  22809. this.gamepadSupportAvailable = (navigator.getGamepads || !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  22810. 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=";
  22811. this._callbackGamepadConnected = ongamedpadconnected;
  22812. if (this.gamepadSupportAvailable) {
  22813. // Checking if the gamepad connected event is supported (like in Firefox)
  22814. if (this.gamepadEventSupported) {
  22815. window.addEventListener('gamepadconnected', function (evt) {
  22816. _this._onGamepadConnected(evt);
  22817. }, false);
  22818. window.addEventListener('gamepaddisconnected', function (evt) {
  22819. _this._onGamepadDisconnected(evt);
  22820. }, false);
  22821. } else {
  22822. this._startMonitoringGamepads();
  22823. }
  22824. if (!this.oneGamepadConnected) {
  22825. this._insertGamepadDOMInstructions();
  22826. }
  22827. } else {
  22828. this._insertGamepadDOMNotSupported();
  22829. }
  22830. }
  22831. Gamepads.prototype._insertGamepadDOMInstructions = function () {
  22832. Gamepads.gamepadDOMInfo = document.createElement("div");
  22833. var buttonAImage = document.createElement("img");
  22834. buttonAImage.src = this.buttonADataURL;
  22835. var spanMessage = document.createElement("span");
  22836. spanMessage.innerHTML = "<strong>to activate gamepad</strong>";
  22837. Gamepads.gamepadDOMInfo.appendChild(buttonAImage);
  22838. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  22839. Gamepads.gamepadDOMInfo.style.position = "absolute";
  22840. Gamepads.gamepadDOMInfo.style.width = "100%";
  22841. Gamepads.gamepadDOMInfo.style.height = "48px";
  22842. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  22843. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  22844. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  22845. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  22846. buttonAImage.style.position = "relative";
  22847. buttonAImage.style.bottom = "8px";
  22848. spanMessage.style.position = "relative";
  22849. spanMessage.style.fontSize = "32px";
  22850. spanMessage.style.bottom = "32px";
  22851. spanMessage.style.color = "green";
  22852. document.body.appendChild(Gamepads.gamepadDOMInfo);
  22853. };
  22854. Gamepads.prototype._insertGamepadDOMNotSupported = function () {
  22855. Gamepads.gamepadDOMInfo = document.createElement("div");
  22856. var spanMessage = document.createElement("span");
  22857. spanMessage.innerHTML = "<strong>gamepad not supported</strong>";
  22858. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  22859. Gamepads.gamepadDOMInfo.style.position = "absolute";
  22860. Gamepads.gamepadDOMInfo.style.width = "100%";
  22861. Gamepads.gamepadDOMInfo.style.height = "40px";
  22862. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  22863. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  22864. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  22865. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  22866. spanMessage.style.position = "relative";
  22867. spanMessage.style.fontSize = "32px";
  22868. spanMessage.style.color = "red";
  22869. document.body.appendChild(Gamepads.gamepadDOMInfo);
  22870. };
  22871. Gamepads.prototype.dispose = function () {
  22872. document.body.removeChild(Gamepads.gamepadDOMInfo);
  22873. };
  22874. Gamepads.prototype._onGamepadConnected = function (evt) {
  22875. var newGamepad = this._addNewGamepad(evt.gamepad);
  22876. if (this._callbackGamepadConnected)
  22877. this._callbackGamepadConnected(newGamepad);
  22878. this._startMonitoringGamepads();
  22879. };
  22880. Gamepads.prototype._addNewGamepad = function (gamepad) {
  22881. if (!this.oneGamepadConnected) {
  22882. this.oneGamepadConnected = true;
  22883. if (Gamepads.gamepadDOMInfo) {
  22884. document.body.removeChild(Gamepads.gamepadDOMInfo);
  22885. Gamepads.gamepadDOMInfo = null;
  22886. }
  22887. }
  22888. var newGamepad;
  22889. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  22890. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  22891. } else {
  22892. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  22893. }
  22894. this.babylonGamepads.push(newGamepad);
  22895. return newGamepad;
  22896. };
  22897. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  22898. for (var i in this.babylonGamepads) {
  22899. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  22900. this.babylonGamepads.splice(i, 1);
  22901. break;
  22902. }
  22903. }
  22904. // If no gamepads are left, stop the polling loop.
  22905. if (this.babylonGamepads.length == 0) {
  22906. this._stopMonitoringGamepads();
  22907. }
  22908. };
  22909. Gamepads.prototype._startMonitoringGamepads = function () {
  22910. if (!this.isMonitoring) {
  22911. this.isMonitoring = true;
  22912. this._checkGamepadsStatus();
  22913. }
  22914. };
  22915. Gamepads.prototype._stopMonitoringGamepads = function () {
  22916. this.isMonitoring = false;
  22917. };
  22918. Gamepads.prototype._checkGamepadsStatus = function () {
  22919. var _this = this;
  22920. // updating gamepad objects
  22921. this._updateGamepadObjects();
  22922. for (var i in this.babylonGamepads) {
  22923. this.babylonGamepads[i].update();
  22924. }
  22925. if (this.isMonitoring) {
  22926. if (window.requestAnimationFrame) {
  22927. window.requestAnimationFrame(function () {
  22928. _this._checkGamepadsStatus();
  22929. });
  22930. } else if (window.mozRequestAnimationFrame) {
  22931. window.mozRequestAnimationFrame(function () {
  22932. _this._checkGamepadsStatus();
  22933. });
  22934. } else if (window.webkitRequestAnimationFrame) {
  22935. window.webkitRequestAnimationFrame(function () {
  22936. _this._checkGamepadsStatus();
  22937. });
  22938. }
  22939. }
  22940. };
  22941. // This function is called only on Chrome, which does not yet support
  22942. // connection/disconnection events, but requires you to monitor
  22943. // an array for changes.
  22944. Gamepads.prototype._updateGamepadObjects = function () {
  22945. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  22946. for (var i = 0; i < gamepads.length; i++) {
  22947. if (gamepads[i]) {
  22948. if (!(gamepads[i].index in this.babylonGamepads)) {
  22949. var newGamepad = this._addNewGamepad(gamepads[i]);
  22950. if (this._callbackGamepadConnected) {
  22951. this._callbackGamepadConnected(newGamepad);
  22952. }
  22953. } else {
  22954. this.babylonGamepads[i].browserGamepad = gamepads[i];
  22955. }
  22956. }
  22957. }
  22958. };
  22959. return Gamepads;
  22960. })();
  22961. BABYLON.Gamepads = Gamepads;
  22962. var StickValues = (function () {
  22963. function StickValues(x, y) {
  22964. this.x = x;
  22965. this.y = y;
  22966. }
  22967. return StickValues;
  22968. })();
  22969. BABYLON.StickValues = StickValues;
  22970. var Gamepad = (function () {
  22971. function Gamepad(id, index, browserGamepad) {
  22972. this.id = id;
  22973. this.index = index;
  22974. this.browserGamepad = browserGamepad;
  22975. if (this.browserGamepad.axes.length >= 2) {
  22976. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  22977. }
  22978. if (this.browserGamepad.axes.length >= 4) {
  22979. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  22980. }
  22981. }
  22982. Gamepad.prototype.onleftstickchanged = function (callback) {
  22983. this._onleftstickchanged = callback;
  22984. };
  22985. Gamepad.prototype.onrightstickchanged = function (callback) {
  22986. this._onrightstickchanged = callback;
  22987. };
  22988. Object.defineProperty(Gamepad.prototype, "leftStick", {
  22989. get: function () {
  22990. return this._leftStick;
  22991. },
  22992. set: function (newValues) {
  22993. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  22994. this._onleftstickchanged(newValues);
  22995. }
  22996. this._leftStick = newValues;
  22997. },
  22998. enumerable: true,
  22999. configurable: true
  23000. });
  23001. Object.defineProperty(Gamepad.prototype, "rightStick", {
  23002. get: function () {
  23003. return this._rightStick;
  23004. },
  23005. set: function (newValues) {
  23006. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  23007. this._onrightstickchanged(newValues);
  23008. }
  23009. this._rightStick = newValues;
  23010. },
  23011. enumerable: true,
  23012. configurable: true
  23013. });
  23014. Gamepad.prototype.update = function () {
  23015. if (this._leftStick) {
  23016. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  23017. }
  23018. if (this._rightStick) {
  23019. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  23020. }
  23021. };
  23022. return Gamepad;
  23023. })();
  23024. BABYLON.Gamepad = Gamepad;
  23025. var GenericPad = (function (_super) {
  23026. __extends(GenericPad, _super);
  23027. function GenericPad(id, index, gamepad) {
  23028. _super.call(this, id, index, gamepad);
  23029. this.id = id;
  23030. this.index = index;
  23031. this.gamepad = gamepad;
  23032. this._buttons = new Array(gamepad.buttons.length);
  23033. }
  23034. GenericPad.prototype.onbuttondown = function (callback) {
  23035. this._onbuttondown = callback;
  23036. };
  23037. GenericPad.prototype.onbuttonup = function (callback) {
  23038. this._onbuttonup = callback;
  23039. };
  23040. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  23041. if (newValue !== currentValue) {
  23042. if (this._onbuttondown && newValue === 1) {
  23043. this._onbuttondown(buttonIndex);
  23044. }
  23045. if (this._onbuttonup && newValue === 0) {
  23046. this._onbuttonup(buttonIndex);
  23047. }
  23048. }
  23049. return newValue;
  23050. };
  23051. GenericPad.prototype.update = function () {
  23052. _super.prototype.update.call(this);
  23053. for (var index = 0; index < this._buttons.length; index++) {
  23054. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  23055. }
  23056. };
  23057. return GenericPad;
  23058. })(Gamepad);
  23059. BABYLON.GenericPad = GenericPad;
  23060. (function (Xbox360Button) {
  23061. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  23062. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  23063. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  23064. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  23065. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  23066. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  23067. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  23068. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  23069. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  23070. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  23071. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  23072. var Xbox360Button = BABYLON.Xbox360Button;
  23073. (function (Xbox360Dpad) {
  23074. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  23075. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  23076. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  23077. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  23078. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  23079. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  23080. var Xbox360Pad = (function (_super) {
  23081. __extends(Xbox360Pad, _super);
  23082. function Xbox360Pad() {
  23083. _super.apply(this, arguments);
  23084. this._leftTrigger = 0;
  23085. this._rightTrigger = 0;
  23086. this._buttonA = 0;
  23087. this._buttonB = 0;
  23088. this._buttonX = 0;
  23089. this._buttonY = 0;
  23090. this._buttonBack = 0;
  23091. this._buttonStart = 0;
  23092. this._buttonLB = 0;
  23093. this._buttonRB = 0;
  23094. this._buttonLeftStick = 0;
  23095. this._buttonRightStick = 0;
  23096. this._dPadUp = 0;
  23097. this._dPadDown = 0;
  23098. this._dPadLeft = 0;
  23099. this._dPadRight = 0;
  23100. }
  23101. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  23102. this._onlefttriggerchanged = callback;
  23103. };
  23104. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  23105. this._onrighttriggerchanged = callback;
  23106. };
  23107. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  23108. get: function () {
  23109. return this._leftTrigger;
  23110. },
  23111. set: function (newValue) {
  23112. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  23113. this._onlefttriggerchanged(newValue);
  23114. }
  23115. this._leftTrigger = newValue;
  23116. },
  23117. enumerable: true,
  23118. configurable: true
  23119. });
  23120. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  23121. get: function () {
  23122. return this._rightTrigger;
  23123. },
  23124. set: function (newValue) {
  23125. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  23126. this._onrighttriggerchanged(newValue);
  23127. }
  23128. this._rightTrigger = newValue;
  23129. },
  23130. enumerable: true,
  23131. configurable: true
  23132. });
  23133. Xbox360Pad.prototype.onbuttondown = function (callback) {
  23134. this._onbuttondown = callback;
  23135. };
  23136. Xbox360Pad.prototype.onbuttonup = function (callback) {
  23137. this._onbuttonup = callback;
  23138. };
  23139. Xbox360Pad.prototype.ondpaddown = function (callback) {
  23140. this._ondpaddown = callback;
  23141. };
  23142. Xbox360Pad.prototype.ondpadup = function (callback) {
  23143. this._ondpadup = callback;
  23144. };
  23145. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  23146. if (newValue !== currentValue) {
  23147. if (this._onbuttondown && newValue === 1) {
  23148. this._onbuttondown(buttonType);
  23149. }
  23150. if (this._onbuttonup && newValue === 0) {
  23151. this._onbuttonup(buttonType);
  23152. }
  23153. }
  23154. return newValue;
  23155. };
  23156. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  23157. if (newValue !== currentValue) {
  23158. if (this._ondpaddown && newValue === 1) {
  23159. this._ondpaddown(buttonType);
  23160. }
  23161. if (this._ondpadup && newValue === 0) {
  23162. this._ondpadup(buttonType);
  23163. }
  23164. }
  23165. return newValue;
  23166. };
  23167. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  23168. get: function () {
  23169. return this._buttonA;
  23170. },
  23171. set: function (value) {
  23172. this._buttonA = this._setButtonValue(value, this._buttonA, 0 /* A */);
  23173. },
  23174. enumerable: true,
  23175. configurable: true
  23176. });
  23177. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  23178. get: function () {
  23179. return this._buttonB;
  23180. },
  23181. set: function (value) {
  23182. this._buttonB = this._setButtonValue(value, this._buttonB, 1 /* B */);
  23183. },
  23184. enumerable: true,
  23185. configurable: true
  23186. });
  23187. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  23188. get: function () {
  23189. return this._buttonX;
  23190. },
  23191. set: function (value) {
  23192. this._buttonX = this._setButtonValue(value, this._buttonX, 2 /* X */);
  23193. },
  23194. enumerable: true,
  23195. configurable: true
  23196. });
  23197. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  23198. get: function () {
  23199. return this._buttonY;
  23200. },
  23201. set: function (value) {
  23202. this._buttonY = this._setButtonValue(value, this._buttonY, 3 /* Y */);
  23203. },
  23204. enumerable: true,
  23205. configurable: true
  23206. });
  23207. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  23208. get: function () {
  23209. return this._buttonStart;
  23210. },
  23211. set: function (value) {
  23212. this._buttonStart = this._setButtonValue(value, this._buttonStart, 4 /* Start */);
  23213. },
  23214. enumerable: true,
  23215. configurable: true
  23216. });
  23217. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  23218. get: function () {
  23219. return this._buttonBack;
  23220. },
  23221. set: function (value) {
  23222. this._buttonBack = this._setButtonValue(value, this._buttonBack, 5 /* Back */);
  23223. },
  23224. enumerable: true,
  23225. configurable: true
  23226. });
  23227. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  23228. get: function () {
  23229. return this._buttonLB;
  23230. },
  23231. set: function (value) {
  23232. this._buttonLB = this._setButtonValue(value, this._buttonLB, 6 /* LB */);
  23233. },
  23234. enumerable: true,
  23235. configurable: true
  23236. });
  23237. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  23238. get: function () {
  23239. return this._buttonRB;
  23240. },
  23241. set: function (value) {
  23242. this._buttonRB = this._setButtonValue(value, this._buttonRB, 7 /* RB */);
  23243. },
  23244. enumerable: true,
  23245. configurable: true
  23246. });
  23247. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  23248. get: function () {
  23249. return this._buttonLeftStick;
  23250. },
  23251. set: function (value) {
  23252. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, 8 /* LeftStick */);
  23253. },
  23254. enumerable: true,
  23255. configurable: true
  23256. });
  23257. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  23258. get: function () {
  23259. return this._buttonRightStick;
  23260. },
  23261. set: function (value) {
  23262. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, 9 /* RightStick */);
  23263. },
  23264. enumerable: true,
  23265. configurable: true
  23266. });
  23267. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  23268. get: function () {
  23269. return this._dPadUp;
  23270. },
  23271. set: function (value) {
  23272. this._dPadUp = this._setDPadValue(value, this._dPadUp, 0 /* Up */);
  23273. },
  23274. enumerable: true,
  23275. configurable: true
  23276. });
  23277. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  23278. get: function () {
  23279. return this._dPadDown;
  23280. },
  23281. set: function (value) {
  23282. this._dPadDown = this._setDPadValue(value, this._dPadDown, 1 /* Down */);
  23283. },
  23284. enumerable: true,
  23285. configurable: true
  23286. });
  23287. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  23288. get: function () {
  23289. return this._dPadLeft;
  23290. },
  23291. set: function (value) {
  23292. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, 2 /* Left */);
  23293. },
  23294. enumerable: true,
  23295. configurable: true
  23296. });
  23297. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  23298. get: function () {
  23299. return this._dPadRight;
  23300. },
  23301. set: function (value) {
  23302. this._dPadRight = this._setDPadValue(value, this._dPadRight, 3 /* Right */);
  23303. },
  23304. enumerable: true,
  23305. configurable: true
  23306. });
  23307. Xbox360Pad.prototype.update = function () {
  23308. _super.prototype.update.call(this);
  23309. this.buttonA = this.browserGamepad.buttons[0].value;
  23310. this.buttonB = this.browserGamepad.buttons[1].value;
  23311. this.buttonX = this.browserGamepad.buttons[2].value;
  23312. this.buttonY = this.browserGamepad.buttons[3].value;
  23313. this.buttonLB = this.browserGamepad.buttons[4].value;
  23314. this.buttonRB = this.browserGamepad.buttons[5].value;
  23315. this.leftTrigger = this.browserGamepad.buttons[6].value;
  23316. this.rightTrigger = this.browserGamepad.buttons[7].value;
  23317. this.buttonBack = this.browserGamepad.buttons[8].value;
  23318. this.buttonStart = this.browserGamepad.buttons[9].value;
  23319. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  23320. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  23321. this.dPadUp = this.browserGamepad.buttons[12].value;
  23322. this.dPadDown = this.browserGamepad.buttons[13].value;
  23323. this.dPadLeft = this.browserGamepad.buttons[14].value;
  23324. this.dPadRight = this.browserGamepad.buttons[15].value;
  23325. };
  23326. return Xbox360Pad;
  23327. })(Gamepad);
  23328. BABYLON.Xbox360Pad = Xbox360Pad;
  23329. })(BABYLON || (BABYLON = {}));
  23330. //# sourceMappingURL=babylon.gamepads.js.map
  23331. var BABYLON;
  23332. (function (BABYLON) {
  23333. // We're mainly based on the logic defined into the FreeCamera code
  23334. var GamepadCamera = (function (_super) {
  23335. __extends(GamepadCamera, _super);
  23336. function GamepadCamera(name, position, scene) {
  23337. var _this = this;
  23338. _super.call(this, name, position, scene);
  23339. this.angularSensibility = 200;
  23340. this.moveSensibility = 75;
  23341. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  23342. _this._onNewGameConnected(gamepad);
  23343. });
  23344. }
  23345. GamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  23346. // Only the first gamepad can control the camera
  23347. if (gamepad.index === 0) {
  23348. this._gamepad = gamepad;
  23349. }
  23350. };
  23351. GamepadCamera.prototype._checkInputs = function () {
  23352. if (!this._gamepad) {
  23353. return;
  23354. }
  23355. var LSValues = this._gamepad.leftStick;
  23356. var normalizedLX = LSValues.x / this.moveSensibility;
  23357. var normalizedLY = LSValues.y / this.moveSensibility;
  23358. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  23359. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  23360. var RSValues = this._gamepad.rightStick;
  23361. var normalizedRX = RSValues.x / this.angularSensibility;
  23362. var normalizedRY = RSValues.y / this.angularSensibility;
  23363. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  23364. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  23365. ;
  23366. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  23367. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x, 0, -LSValues.y), cameraTransform);
  23368. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  23369. this.cameraRotation = this.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  23370. };
  23371. GamepadCamera.prototype.dispose = function () {
  23372. this._gamepads.dispose();
  23373. _super.prototype.dispose.call(this);
  23374. };
  23375. return GamepadCamera;
  23376. })(BABYLON.FreeCamera);
  23377. BABYLON.GamepadCamera = GamepadCamera;
  23378. })(BABYLON || (BABYLON = {}));
  23379. //# sourceMappingURL=babylon.gamepadCamera.js.map
  23380. var BABYLON;
  23381. (function (BABYLON) {
  23382. var LinesMesh = (function (_super) {
  23383. __extends(LinesMesh, _super);
  23384. function LinesMesh(name, scene, updatable) {
  23385. if (typeof updatable === "undefined") { updatable = false; }
  23386. _super.call(this, name, scene);
  23387. this.color = new BABYLON.Color3(1, 1, 1);
  23388. this.alpha = 1;
  23389. this._indices = new Array();
  23390. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  23391. attributes: ["position"],
  23392. uniforms: ["worldViewProjection", "color"],
  23393. needAlphaBlending: true
  23394. });
  23395. }
  23396. Object.defineProperty(LinesMesh.prototype, "material", {
  23397. get: function () {
  23398. return this._colorShader;
  23399. },
  23400. enumerable: true,
  23401. configurable: true
  23402. });
  23403. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  23404. get: function () {
  23405. return false;
  23406. },
  23407. enumerable: true,
  23408. configurable: true
  23409. });
  23410. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  23411. get: function () {
  23412. return false;
  23413. },
  23414. enumerable: true,
  23415. configurable: true
  23416. });
  23417. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  23418. var engine = this.getScene().getEngine();
  23419. var indexToBind = this._geometry.getIndexBuffer();
  23420. // VBOs
  23421. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  23422. // Color
  23423. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  23424. };
  23425. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  23426. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  23427. return;
  23428. }
  23429. var engine = this.getScene().getEngine();
  23430. // Draw order
  23431. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  23432. };
  23433. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  23434. return null;
  23435. };
  23436. LinesMesh.prototype.dispose = function (doNotRecurse) {
  23437. this._colorShader.dispose();
  23438. _super.prototype.dispose.call(this, doNotRecurse);
  23439. };
  23440. return LinesMesh;
  23441. })(BABYLON.Mesh);
  23442. BABYLON.LinesMesh = LinesMesh;
  23443. })(BABYLON || (BABYLON = {}));
  23444. //# sourceMappingURL=babylon.linesMesh.js.map
  23445. var BABYLON;
  23446. (function (BABYLON) {
  23447. var OutlineRenderer = (function () {
  23448. function OutlineRenderer(scene) {
  23449. this._scene = scene;
  23450. }
  23451. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  23452. if (typeof useOverlay === "undefined") { useOverlay = false; }
  23453. var scene = this._scene;
  23454. var engine = this._scene.getEngine();
  23455. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  23456. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  23457. return;
  23458. }
  23459. var mesh = subMesh.getRenderingMesh();
  23460. var material = subMesh.getMaterial();
  23461. engine.enableEffect(this._effect);
  23462. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  23463. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  23464. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  23465. // Bones
  23466. var useBones = mesh.skeleton && scene.skeletonsEnabled && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  23467. if (useBones) {
  23468. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  23469. }
  23470. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  23471. // Alpha test
  23472. if (material && material.needAlphaTesting()) {
  23473. var alphaTexture = material.getAlphaTestTexture();
  23474. this._effect.setTexture("diffuseSampler", alphaTexture);
  23475. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  23476. }
  23477. if (hardwareInstancedRendering) {
  23478. mesh._renderWithInstances(subMesh, BABYLON.Material.TriangleFillMode, batch, this._effect, engine);
  23479. } else {
  23480. if (batch.renderSelf[subMesh._id]) {
  23481. this._effect.setMatrix("world", mesh.getWorldMatrix());
  23482. // Draw
  23483. mesh._draw(subMesh, BABYLON.Material.TriangleFillMode);
  23484. }
  23485. if (batch.visibleInstances[subMesh._id]) {
  23486. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  23487. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  23488. this._effect.setMatrix("world", instance.getWorldMatrix());
  23489. // Draw
  23490. mesh._draw(subMesh, BABYLON.Material.TriangleFillMode);
  23491. }
  23492. }
  23493. }
  23494. };
  23495. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  23496. var defines = [];
  23497. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  23498. var mesh = subMesh.getMesh();
  23499. var material = subMesh.getMaterial();
  23500. // Alpha test
  23501. if (material && material.needAlphaTesting()) {
  23502. defines.push("#define ALPHATEST");
  23503. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  23504. attribs.push(BABYLON.VertexBuffer.UVKind);
  23505. defines.push("#define UV1");
  23506. }
  23507. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  23508. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  23509. defines.push("#define UV2");
  23510. }
  23511. }
  23512. // Bones
  23513. if (mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  23514. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  23515. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  23516. defines.push("#define BONES");
  23517. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  23518. }
  23519. // Instances
  23520. if (useInstances) {
  23521. defines.push("#define INSTANCES");
  23522. attribs.push("world0");
  23523. attribs.push("world1");
  23524. attribs.push("world2");
  23525. attribs.push("world3");
  23526. }
  23527. // Get correct effect
  23528. var join = defines.join("\n");
  23529. if (this._cachedDefines != join) {
  23530. this._cachedDefines = join;
  23531. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  23532. }
  23533. return this._effect.isReady();
  23534. };
  23535. return OutlineRenderer;
  23536. })();
  23537. BABYLON.OutlineRenderer = OutlineRenderer;
  23538. })(BABYLON || (BABYLON = {}));
  23539. //# sourceMappingURL=babylon.outlineRenderer.js.map
  23540. var BABYLON;
  23541. (function (BABYLON) {
  23542. var MeshAssetTask = (function () {
  23543. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  23544. this.name = name;
  23545. this.meshesNames = meshesNames;
  23546. this.rootUrl = rootUrl;
  23547. this.sceneFilename = sceneFilename;
  23548. this.isCompleted = false;
  23549. }
  23550. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  23551. var _this = this;
  23552. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  23553. _this.loadedMeshes = meshes;
  23554. _this.loadedParticleSystems = particleSystems;
  23555. _this.loadedSkeletons = skeletons;
  23556. _this.isCompleted = true;
  23557. if (_this.onSuccess) {
  23558. _this.onSuccess(_this);
  23559. }
  23560. onSuccess();
  23561. }, null, function () {
  23562. if (_this.onError) {
  23563. _this.onError(_this);
  23564. }
  23565. onError();
  23566. });
  23567. };
  23568. return MeshAssetTask;
  23569. })();
  23570. BABYLON.MeshAssetTask = MeshAssetTask;
  23571. var TextFileAssetTask = (function () {
  23572. function TextFileAssetTask(name, url) {
  23573. this.name = name;
  23574. this.url = url;
  23575. this.isCompleted = false;
  23576. }
  23577. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  23578. var _this = this;
  23579. BABYLON.Tools.LoadFile(this.url, function (data) {
  23580. _this.text = data;
  23581. _this.isCompleted = true;
  23582. if (_this.onSuccess) {
  23583. _this.onSuccess(_this);
  23584. }
  23585. onSuccess();
  23586. }, null, scene.database, false, function () {
  23587. if (_this.onError) {
  23588. _this.onError(_this);
  23589. }
  23590. onError();
  23591. });
  23592. };
  23593. return TextFileAssetTask;
  23594. })();
  23595. BABYLON.TextFileAssetTask = TextFileAssetTask;
  23596. var BinaryFileAssetTask = (function () {
  23597. function BinaryFileAssetTask(name, url) {
  23598. this.name = name;
  23599. this.url = url;
  23600. this.isCompleted = false;
  23601. }
  23602. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  23603. var _this = this;
  23604. BABYLON.Tools.LoadFile(this.url, function (data) {
  23605. _this.data = data;
  23606. _this.isCompleted = true;
  23607. if (_this.onSuccess) {
  23608. _this.onSuccess(_this);
  23609. }
  23610. onSuccess();
  23611. }, null, scene.database, true, function () {
  23612. if (_this.onError) {
  23613. _this.onError(_this);
  23614. }
  23615. onError();
  23616. });
  23617. };
  23618. return BinaryFileAssetTask;
  23619. })();
  23620. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  23621. var ImageAssetTask = (function () {
  23622. function ImageAssetTask(name, url) {
  23623. this.name = name;
  23624. this.url = url;
  23625. this.isCompleted = false;
  23626. }
  23627. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  23628. var _this = this;
  23629. var img = new Image();
  23630. img.onload = function () {
  23631. _this.image = img;
  23632. _this.isCompleted = true;
  23633. if (_this.onSuccess) {
  23634. _this.onSuccess(_this);
  23635. }
  23636. onSuccess();
  23637. };
  23638. img.onerror = function () {
  23639. if (_this.onError) {
  23640. _this.onError(_this);
  23641. }
  23642. onError();
  23643. };
  23644. img.src = this.url;
  23645. };
  23646. return ImageAssetTask;
  23647. })();
  23648. BABYLON.ImageAssetTask = ImageAssetTask;
  23649. var TextureAssetTask = (function () {
  23650. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  23651. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  23652. this.name = name;
  23653. this.url = url;
  23654. this.noMipmap = noMipmap;
  23655. this.invertY = invertY;
  23656. this.samplingMode = samplingMode;
  23657. this.isCompleted = false;
  23658. }
  23659. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  23660. var _this = this;
  23661. var onload = function () {
  23662. _this.isCompleted = true;
  23663. if (_this.onSuccess) {
  23664. _this.onSuccess(_this);
  23665. }
  23666. onSuccess();
  23667. };
  23668. var onerror = function () {
  23669. if (_this.onError) {
  23670. _this.onError(_this);
  23671. }
  23672. onError();
  23673. };
  23674. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onError);
  23675. };
  23676. return TextureAssetTask;
  23677. })();
  23678. BABYLON.TextureAssetTask = TextureAssetTask;
  23679. var AssetsManager = (function () {
  23680. function AssetsManager(scene) {
  23681. this._tasks = new Array();
  23682. this._waitingTasksCount = 0;
  23683. this.useDefaultLoadingScreen = true;
  23684. this._scene = scene;
  23685. }
  23686. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  23687. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  23688. this._tasks.push(task);
  23689. return task;
  23690. };
  23691. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  23692. var task = new TextFileAssetTask(taskName, url);
  23693. this._tasks.push(task);
  23694. return task;
  23695. };
  23696. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  23697. var task = new BinaryFileAssetTask(taskName, url);
  23698. this._tasks.push(task);
  23699. return task;
  23700. };
  23701. AssetsManager.prototype.addImageTask = function (taskName, url) {
  23702. var task = new ImageAssetTask(taskName, url);
  23703. this._tasks.push(task);
  23704. return task;
  23705. };
  23706. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  23707. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  23708. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  23709. this._tasks.push(task);
  23710. return task;
  23711. };
  23712. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  23713. this._waitingTasksCount--;
  23714. if (this._waitingTasksCount === 0) {
  23715. if (this.onFinish) {
  23716. this.onFinish(this._tasks);
  23717. }
  23718. this._scene.getEngine().hideLoadingUI();
  23719. }
  23720. };
  23721. AssetsManager.prototype._runTask = function (task) {
  23722. var _this = this;
  23723. task.run(this._scene, function () {
  23724. if (_this.onTaskSuccess) {
  23725. _this.onTaskSuccess(task);
  23726. }
  23727. _this._decreaseWaitingTasksCount();
  23728. }, function () {
  23729. if (_this.onTaskError) {
  23730. _this.onTaskError(task);
  23731. }
  23732. _this._decreaseWaitingTasksCount();
  23733. });
  23734. };
  23735. AssetsManager.prototype.reset = function () {
  23736. this._tasks = new Array();
  23737. return this;
  23738. };
  23739. AssetsManager.prototype.load = function () {
  23740. this._waitingTasksCount = this._tasks.length;
  23741. if (this._waitingTasksCount === 0) {
  23742. if (this.onFinish) {
  23743. this.onFinish(this._tasks);
  23744. }
  23745. return this;
  23746. }
  23747. if (this.useDefaultLoadingScreen) {
  23748. this._scene.getEngine().displayLoadingUI();
  23749. }
  23750. for (var index = 0; index < this._tasks.length; index++) {
  23751. var task = this._tasks[index];
  23752. this._runTask(task);
  23753. }
  23754. return this;
  23755. };
  23756. return AssetsManager;
  23757. })();
  23758. BABYLON.AssetsManager = AssetsManager;
  23759. })(BABYLON || (BABYLON = {}));
  23760. //# sourceMappingURL=babylon.assetsManager.js.map
  23761. var BABYLON;
  23762. (function (BABYLON) {
  23763. var VRDeviceOrientationCamera = (function (_super) {
  23764. __extends(VRDeviceOrientationCamera, _super);
  23765. function VRDeviceOrientationCamera(name, position, scene) {
  23766. _super.call(this, name, position, scene);
  23767. this._alpha = 0;
  23768. this._beta = 0;
  23769. this._gamma = 0;
  23770. }
  23771. VRDeviceOrientationCamera.prototype._onOrientationEvent = function (evt) {
  23772. this._alpha = +evt.alpha | 0;
  23773. this._beta = +evt.beta | 0;
  23774. this._gamma = +evt.gamma | 0;
  23775. if (this._gamma < 0) {
  23776. this._gamma = 90 + this._gamma;
  23777. } else {
  23778. // Incline it in the correct angle.
  23779. this._gamma = 270 - this._gamma;
  23780. }
  23781. this.rotation.x = this._gamma / 180.0 * Math.PI;
  23782. this.rotation.y = -this._alpha / 180.0 * Math.PI;
  23783. this.rotation.z = this._beta / 180.0 * Math.PI;
  23784. };
  23785. return VRDeviceOrientationCamera;
  23786. })(BABYLON.OculusCamera);
  23787. BABYLON.VRDeviceOrientationCamera = VRDeviceOrientationCamera;
  23788. })(BABYLON || (BABYLON = {}));
  23789. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  23790. var BABYLON;
  23791. (function (BABYLON) {
  23792. var WebVRCamera = (function (_super) {
  23793. __extends(WebVRCamera, _super);
  23794. function WebVRCamera(name, position, scene) {
  23795. _super.call(this, name, position, scene);
  23796. this._hmdDevice = null;
  23797. this._sensorDevice = null;
  23798. this._cacheState = null;
  23799. this._cacheQuaternion = new BABYLON.Quaternion();
  23800. this._cacheRotation = BABYLON.Vector3.Zero();
  23801. this._vrEnabled = false;
  23802. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  23803. }
  23804. WebVRCamera.prototype._getWebVRDevices = function (devices) {
  23805. var size = devices.length;
  23806. var i = 0;
  23807. // Reset devices.
  23808. this._sensorDevice = null;
  23809. this._hmdDevice = null;
  23810. while (i < size && this._hmdDevice === null) {
  23811. if (devices[i] instanceof HMDVRDevice) {
  23812. this._hmdDevice = devices[i];
  23813. }
  23814. i++;
  23815. }
  23816. i = 0;
  23817. while (i < size && this._sensorDevice === null) {
  23818. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  23819. this._sensorDevice = devices[i];
  23820. }
  23821. i++;
  23822. }
  23823. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  23824. };
  23825. WebVRCamera.prototype._update = function () {
  23826. if (this._vrEnabled) {
  23827. this._cacheState = this._sensorDevice.getState();
  23828. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  23829. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  23830. this.rotation.x = -this._cacheRotation.z;
  23831. this.rotation.y = -this._cacheRotation.y;
  23832. this.rotation.z = this._cacheRotation.x;
  23833. }
  23834. _super.prototype._update.call(this);
  23835. };
  23836. WebVRCamera.prototype.attachControl = function (element, noPreventDefault) {
  23837. _super.prototype.attachControl.call(this, element, noPreventDefault);
  23838. if (navigator.getVRDevices) {
  23839. navigator.getVRDevices().then(this._getWebVRDevices);
  23840. } else if (navigator.mozGetVRDevices) {
  23841. navigator.mozGetVRDevices(this._getWebVRDevices);
  23842. }
  23843. };
  23844. WebVRCamera.prototype.detachControl = function (element) {
  23845. _super.prototype.detachControl.call(this, element);
  23846. this._vrEnabled = false;
  23847. };
  23848. return WebVRCamera;
  23849. })(BABYLON.OculusCamera);
  23850. BABYLON.WebVRCamera = WebVRCamera;
  23851. })(BABYLON || (BABYLON = {}));
  23852. //# sourceMappingURL=babylon.webVRCamera.js.map
  23853. var BABYLON;
  23854. (function (BABYLON) {
  23855. // Standard optimizations
  23856. var SceneOptimization = (function () {
  23857. function SceneOptimization(priority) {
  23858. if (typeof priority === "undefined") { priority = 0; }
  23859. this.priority = priority;
  23860. this.apply = function (scene) {
  23861. return true;
  23862. };
  23863. }
  23864. return SceneOptimization;
  23865. })();
  23866. BABYLON.SceneOptimization = SceneOptimization;
  23867. var TextureOptimization = (function (_super) {
  23868. __extends(TextureOptimization, _super);
  23869. function TextureOptimization(priority, maximumSize) {
  23870. if (typeof priority === "undefined") { priority = 0; }
  23871. if (typeof maximumSize === "undefined") { maximumSize = 1024; }
  23872. var _this = this;
  23873. _super.call(this, priority);
  23874. this.priority = priority;
  23875. this.maximumSize = maximumSize;
  23876. this.apply = function (scene) {
  23877. var allDone = true;
  23878. for (var index = 0; index < scene.textures.length; index++) {
  23879. var texture = scene.textures[index];
  23880. if (!texture.canRescale) {
  23881. continue;
  23882. }
  23883. var currentSize = texture.getSize();
  23884. var maxDimension = Math.max(currentSize.width, currentSize.height);
  23885. if (maxDimension > _this.maximumSize) {
  23886. texture.scale(0.5);
  23887. allDone = false;
  23888. }
  23889. }
  23890. return allDone;
  23891. };
  23892. }
  23893. return TextureOptimization;
  23894. })(SceneOptimization);
  23895. BABYLON.TextureOptimization = TextureOptimization;
  23896. var HardwareScalingOptimization = (function (_super) {
  23897. __extends(HardwareScalingOptimization, _super);
  23898. function HardwareScalingOptimization(priority, maximumScale) {
  23899. if (typeof priority === "undefined") { priority = 0; }
  23900. if (typeof maximumScale === "undefined") { maximumScale = 2; }
  23901. var _this = this;
  23902. _super.call(this, priority);
  23903. this.priority = priority;
  23904. this.maximumScale = maximumScale;
  23905. this._currentScale = 1;
  23906. this.apply = function (scene) {
  23907. _this._currentScale++;
  23908. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  23909. return _this._currentScale >= _this.maximumScale;
  23910. };
  23911. }
  23912. return HardwareScalingOptimization;
  23913. })(SceneOptimization);
  23914. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  23915. var ShadowsOptimization = (function (_super) {
  23916. __extends(ShadowsOptimization, _super);
  23917. function ShadowsOptimization() {
  23918. _super.apply(this, arguments);
  23919. this.apply = function (scene) {
  23920. scene.shadowsEnabled = false;
  23921. return true;
  23922. };
  23923. }
  23924. return ShadowsOptimization;
  23925. })(SceneOptimization);
  23926. BABYLON.ShadowsOptimization = ShadowsOptimization;
  23927. var PostProcessesOptimization = (function (_super) {
  23928. __extends(PostProcessesOptimization, _super);
  23929. function PostProcessesOptimization() {
  23930. _super.apply(this, arguments);
  23931. this.apply = function (scene) {
  23932. scene.postProcessesEnabled = false;
  23933. return true;
  23934. };
  23935. }
  23936. return PostProcessesOptimization;
  23937. })(SceneOptimization);
  23938. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  23939. var LensFlaresOptimization = (function (_super) {
  23940. __extends(LensFlaresOptimization, _super);
  23941. function LensFlaresOptimization() {
  23942. _super.apply(this, arguments);
  23943. this.apply = function (scene) {
  23944. scene.lensFlaresEnabled = false;
  23945. return true;
  23946. };
  23947. }
  23948. return LensFlaresOptimization;
  23949. })(SceneOptimization);
  23950. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  23951. var ParticlesOptimization = (function (_super) {
  23952. __extends(ParticlesOptimization, _super);
  23953. function ParticlesOptimization() {
  23954. _super.apply(this, arguments);
  23955. this.apply = function (scene) {
  23956. scene.particlesEnabled = false;
  23957. return true;
  23958. };
  23959. }
  23960. return ParticlesOptimization;
  23961. })(SceneOptimization);
  23962. BABYLON.ParticlesOptimization = ParticlesOptimization;
  23963. var RenderTargetsOptimization = (function (_super) {
  23964. __extends(RenderTargetsOptimization, _super);
  23965. function RenderTargetsOptimization() {
  23966. _super.apply(this, arguments);
  23967. this.apply = function (scene) {
  23968. scene.renderTargetsEnabled = false;
  23969. return true;
  23970. };
  23971. }
  23972. return RenderTargetsOptimization;
  23973. })(SceneOptimization);
  23974. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  23975. var MergeMeshesOptimization = (function (_super) {
  23976. __extends(MergeMeshesOptimization, _super);
  23977. function MergeMeshesOptimization() {
  23978. _super.apply(this, arguments);
  23979. var _this = this;
  23980. this._canBeMerged = function (abstractMesh) {
  23981. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  23982. return false;
  23983. }
  23984. var mesh = abstractMesh;
  23985. if (!mesh.isVisible || !mesh.isEnabled()) {
  23986. return false;
  23987. }
  23988. if (mesh.instances.length > 0) {
  23989. return false;
  23990. }
  23991. if (mesh.skeleton || mesh.hasLODLevels) {
  23992. return false;
  23993. }
  23994. return true;
  23995. };
  23996. this.apply = function (scene) {
  23997. var globalPool = scene.meshes.slice(0);
  23998. var globalLength = globalPool.length;
  23999. for (var index = 0; index < globalLength; index++) {
  24000. var currentPool = new Array();
  24001. var current = globalPool[index];
  24002. // Checks
  24003. if (!_this._canBeMerged(current)) {
  24004. continue;
  24005. }
  24006. currentPool.push(current);
  24007. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  24008. var otherMesh = globalPool[subIndex];
  24009. if (!_this._canBeMerged(otherMesh)) {
  24010. continue;
  24011. }
  24012. if (otherMesh.material !== current.material) {
  24013. continue;
  24014. }
  24015. if (otherMesh.checkCollisions !== current.checkCollisions) {
  24016. continue;
  24017. }
  24018. currentPool.push(otherMesh);
  24019. globalLength--;
  24020. globalPool.splice(subIndex, 1);
  24021. subIndex--;
  24022. }
  24023. if (currentPool.length < 2) {
  24024. continue;
  24025. }
  24026. // Merge meshes
  24027. BABYLON.Mesh.MergeMeshes(currentPool);
  24028. }
  24029. return true;
  24030. };
  24031. }
  24032. return MergeMeshesOptimization;
  24033. })(SceneOptimization);
  24034. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  24035. // Options
  24036. var SceneOptimizerOptions = (function () {
  24037. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  24038. if (typeof targetFrameRate === "undefined") { targetFrameRate = 60; }
  24039. if (typeof trackerDuration === "undefined") { trackerDuration = 2000; }
  24040. this.targetFrameRate = targetFrameRate;
  24041. this.trackerDuration = trackerDuration;
  24042. this.optimizations = new Array();
  24043. }
  24044. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  24045. var result = new SceneOptimizerOptions(targetFrameRate);
  24046. var priority = 0;
  24047. result.optimizations.push(new MergeMeshesOptimization(priority));
  24048. result.optimizations.push(new ShadowsOptimization(priority));
  24049. result.optimizations.push(new LensFlaresOptimization(priority));
  24050. // Next priority
  24051. priority++;
  24052. result.optimizations.push(new PostProcessesOptimization(priority));
  24053. result.optimizations.push(new ParticlesOptimization(priority));
  24054. // Next priority
  24055. priority++;
  24056. result.optimizations.push(new TextureOptimization(priority, 1024));
  24057. return result;
  24058. };
  24059. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  24060. var result = new SceneOptimizerOptions(targetFrameRate);
  24061. var priority = 0;
  24062. result.optimizations.push(new MergeMeshesOptimization(priority));
  24063. result.optimizations.push(new ShadowsOptimization(priority));
  24064. result.optimizations.push(new LensFlaresOptimization(priority));
  24065. // Next priority
  24066. priority++;
  24067. result.optimizations.push(new PostProcessesOptimization(priority));
  24068. result.optimizations.push(new ParticlesOptimization(priority));
  24069. // Next priority
  24070. priority++;
  24071. result.optimizations.push(new TextureOptimization(priority, 512));
  24072. // Next priority
  24073. priority++;
  24074. result.optimizations.push(new RenderTargetsOptimization(priority));
  24075. // Next priority
  24076. priority++;
  24077. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  24078. return result;
  24079. };
  24080. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  24081. var result = new SceneOptimizerOptions(targetFrameRate);
  24082. var priority = 0;
  24083. result.optimizations.push(new MergeMeshesOptimization(priority));
  24084. result.optimizations.push(new ShadowsOptimization(priority));
  24085. result.optimizations.push(new LensFlaresOptimization(priority));
  24086. // Next priority
  24087. priority++;
  24088. result.optimizations.push(new PostProcessesOptimization(priority));
  24089. result.optimizations.push(new ParticlesOptimization(priority));
  24090. // Next priority
  24091. priority++;
  24092. result.optimizations.push(new TextureOptimization(priority, 256));
  24093. // Next priority
  24094. priority++;
  24095. result.optimizations.push(new RenderTargetsOptimization(priority));
  24096. // Next priority
  24097. priority++;
  24098. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  24099. return result;
  24100. };
  24101. return SceneOptimizerOptions;
  24102. })();
  24103. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  24104. // Scene optimizer tool
  24105. var SceneOptimizer = (function () {
  24106. function SceneOptimizer() {
  24107. }
  24108. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  24109. // TODO: add an epsilon
  24110. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  24111. if (onSuccess) {
  24112. onSuccess();
  24113. }
  24114. return;
  24115. }
  24116. // Apply current level of optimizations
  24117. var allDone = true;
  24118. var noOptimizationApplied = true;
  24119. for (var index = 0; index < options.optimizations.length; index++) {
  24120. var optimization = options.optimizations[index];
  24121. if (optimization.priority === currentPriorityLevel) {
  24122. noOptimizationApplied = false;
  24123. allDone = allDone && optimization.apply(scene);
  24124. }
  24125. }
  24126. // If no optimization was applied, this is a failure :(
  24127. if (noOptimizationApplied) {
  24128. if (onFailure) {
  24129. onFailure();
  24130. }
  24131. return;
  24132. }
  24133. // If all optimizations were done, move to next level
  24134. if (allDone) {
  24135. currentPriorityLevel++;
  24136. }
  24137. // Let's the system running for a specific amount of time before checking FPS
  24138. scene.executeWhenReady(function () {
  24139. setTimeout(function () {
  24140. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  24141. }, options.trackerDuration);
  24142. });
  24143. };
  24144. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  24145. if (!options) {
  24146. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  24147. }
  24148. // Let's the system running for a specific amount of time before checking FPS
  24149. scene.executeWhenReady(function () {
  24150. setTimeout(function () {
  24151. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  24152. }, options.trackerDuration);
  24153. });
  24154. };
  24155. return SceneOptimizer;
  24156. })();
  24157. BABYLON.SceneOptimizer = SceneOptimizer;
  24158. })(BABYLON || (BABYLON = {}));
  24159. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  24160. var BABYLON;
  24161. (function (BABYLON) {
  24162. (function (Internals) {
  24163. var MeshLODLevel = (function () {
  24164. function MeshLODLevel(distance, mesh) {
  24165. this.distance = distance;
  24166. this.mesh = mesh;
  24167. }
  24168. return MeshLODLevel;
  24169. })();
  24170. Internals.MeshLODLevel = MeshLODLevel;
  24171. })(BABYLON.Internals || (BABYLON.Internals = {}));
  24172. var Internals = BABYLON.Internals;
  24173. })(BABYLON || (BABYLON = {}));
  24174. //# sourceMappingURL=babylon.meshLODLevel.js.map
  24175. var BABYLON;
  24176. (function (BABYLON) {
  24177. var AudioEngine = (function () {
  24178. function AudioEngine() {
  24179. this.audioContext = null;
  24180. this.canUseWebAudio = false;
  24181. try {
  24182. if (typeof AudioContext !== 'undefined') {
  24183. this.audioContext = new AudioContext();
  24184. this.canUseWebAudio = true;
  24185. } else if (typeof webkitAudioContext !== 'undefined') {
  24186. this.audioContext = new webkitAudioContext();
  24187. this.canUseWebAudio = true;
  24188. }
  24189. } catch (e) {
  24190. this.canUseWebAudio = false;
  24191. }
  24192. // create a global volume gain node
  24193. if (this.canUseWebAudio) {
  24194. this.masterGain = this.audioContext.createGain();
  24195. this.masterGain.gain.value = 1;
  24196. this.masterGain.connect(this.audioContext.destination);
  24197. }
  24198. }
  24199. AudioEngine.prototype.getGlobalVolume = function () {
  24200. if (this.canUseWebAudio) {
  24201. return this.masterGain.gain.value;
  24202. } else {
  24203. return -1;
  24204. }
  24205. };
  24206. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  24207. if (this.canUseWebAudio) {
  24208. this.masterGain.gain.value = newVolume;
  24209. }
  24210. };
  24211. return AudioEngine;
  24212. })();
  24213. BABYLON.AudioEngine = AudioEngine;
  24214. })(BABYLON || (BABYLON = {}));
  24215. //# sourceMappingURL=babylon.audioengine.js.map
  24216. var BABYLON;
  24217. (function (BABYLON) {
  24218. var Sound = (function () {
  24219. /**
  24220. * Create a sound and attach it to a scene
  24221. * @param name Name of your sound
  24222. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  24223. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  24224. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel
  24225. */
  24226. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  24227. var _this = this;
  24228. this.autoplay = false;
  24229. this.loop = false;
  24230. this.useCustomAttenuation = false;
  24231. this.spatialSound = false;
  24232. this.refDistance = 1;
  24233. this.rolloffFactor = 1;
  24234. this.maxDistance = 100;
  24235. this.distanceModel = "linear";
  24236. this.panningModel = "HRTF";
  24237. this.startTime = 0;
  24238. this.startOffset = 0;
  24239. this._position = BABYLON.Vector3.Zero();
  24240. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  24241. this._volume = 1;
  24242. this._isLoaded = false;
  24243. this._isReadyToPlay = false;
  24244. this._isPlaying = false;
  24245. this._isDirectional = false;
  24246. // Used if you'd like to create a directional sound.
  24247. // If not set, the sound will be omnidirectional
  24248. this._coneInnerAngle = 360;
  24249. this._coneOuterAngle = 360;
  24250. this._coneOuterGain = 0;
  24251. this._name = name;
  24252. this._scene = scene;
  24253. this._audioEngine = this._scene.getEngine().getAudioEngine();
  24254. this._readyToPlayCallback = readyToPlayCallback;
  24255. // Default custom attenuation function is a linear attenuation
  24256. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  24257. if (currentDistance < maxDistance) {
  24258. return currentVolume * (1 - currentDistance / maxDistance);
  24259. } else {
  24260. return 0;
  24261. }
  24262. };
  24263. if (options) {
  24264. this.autoplay = options.autoplay || false;
  24265. this.loop = options.loop || false;
  24266. this._volume = options.volume || 1;
  24267. this.spatialSound = options.spatialSound || false;
  24268. this.maxDistance = options.maxDistance || 100;
  24269. this.useCustomAttenuation = options.useCustomAttenation || false;
  24270. this.rolloffFactor = options.rolloffFactor || 1;
  24271. this.refDistance = options.refDistance || 1;
  24272. this.distanceModel = options.distanceModel || "linear";
  24273. this.panningModel = options.panningModel || "HRTF";
  24274. }
  24275. if (this._audioEngine.canUseWebAudio) {
  24276. this._soundGain = this._audioEngine.audioContext.createGain();
  24277. this._soundGain.gain.value = this._volume;
  24278. if (this.spatialSound) {
  24279. this._createSpatialParameters();
  24280. } else {
  24281. this._audioNode = this._soundGain;
  24282. }
  24283. this._scene.mainSoundTrack.AddSound(this);
  24284. if (typeof (urlOrArrayBuffer) === "string") {
  24285. BABYLON.Tools.LoadFile(urlOrArrayBuffer, function (data) {
  24286. _this._soundLoaded(data);
  24287. }, null, null, true);
  24288. } else {
  24289. if (urlOrArrayBuffer instanceof ArrayBuffer) {
  24290. this._soundLoaded(urlOrArrayBuffer);
  24291. } else {
  24292. BABYLON.Tools.Error("Parameter must be a URL to the sound or an ArrayBuffer of the sound.");
  24293. }
  24294. }
  24295. }
  24296. }
  24297. Sound.prototype.updateOptions = function (options) {
  24298. if (options) {
  24299. this.loop = options.loop || this.loop;
  24300. this.maxDistance = options.maxDistance || this.maxDistance;
  24301. this.useCustomAttenuation = options.useCustomAttenation || this.useCustomAttenuation;
  24302. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  24303. this.refDistance = options.refDistance || this.refDistance;
  24304. this.distanceModel = options.distanceModel || this.distanceModel;
  24305. this.panningModel = options.panningModel || this.panningModel;
  24306. }
  24307. };
  24308. Sound.prototype._createSpatialParameters = function () {
  24309. this._soundPanner = this._audioEngine.audioContext.createPanner();
  24310. if (this.useCustomAttenuation) {
  24311. // Tricks to disable in a way embedded Web Audio attenuation
  24312. this._soundPanner.distanceModel = "linear";
  24313. this._soundPanner.maxDistance = Number.MAX_VALUE;
  24314. this._soundPanner.refDistance = 1;
  24315. this._soundPanner.rolloffFactor = 1;
  24316. this._soundPanner.panningModel = "HRTF";
  24317. } else {
  24318. this._soundPanner.distanceModel = this.distanceModel;
  24319. this._soundPanner.maxDistance = this.maxDistance;
  24320. this._soundPanner.refDistance = this.refDistance;
  24321. this._soundPanner.rolloffFactor = this.rolloffFactor;
  24322. this._soundPanner.panningModel = this.panningModel;
  24323. }
  24324. this._soundPanner.connect(this._soundGain);
  24325. this._audioNode = this._soundPanner;
  24326. };
  24327. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  24328. if (this._audioEngine.canUseWebAudio) {
  24329. this._audioNode.disconnect();
  24330. this._audioNode.connect(soundTrackAudioNode);
  24331. }
  24332. };
  24333. /**
  24334. * Transform this sound into a directional source
  24335. * @param coneInnerAngle Size of the inner cone in degree
  24336. * @param coneOuterAngle Size of the outer cone in degree
  24337. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  24338. */
  24339. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  24340. if (coneOuterAngle < coneInnerAngle) {
  24341. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  24342. return;
  24343. }
  24344. this._coneInnerAngle = coneInnerAngle;
  24345. this._coneOuterAngle = coneOuterAngle;
  24346. this._coneOuterGain = coneOuterGain;
  24347. this._isDirectional = true;
  24348. if (this._isPlaying && this.loop) {
  24349. this.stop();
  24350. this.play();
  24351. }
  24352. };
  24353. Sound.prototype.setPosition = function (newPosition) {
  24354. this._position = newPosition;
  24355. if (this._isPlaying && this.spatialSound) {
  24356. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  24357. }
  24358. };
  24359. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  24360. this._localDirection = newLocalDirection;
  24361. if (this._connectedMesh && this._isPlaying) {
  24362. this._updateDirection();
  24363. }
  24364. };
  24365. Sound.prototype._updateDirection = function () {
  24366. var mat = this._connectedMesh.getWorldMatrix();
  24367. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  24368. direction.normalize();
  24369. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  24370. };
  24371. Sound.prototype.updateDistanceFromListener = function () {
  24372. if (this._connectedMesh && this.useCustomAttenuation) {
  24373. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  24374. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  24375. }
  24376. };
  24377. Sound.prototype.setAttenuationFunction = function (callback) {
  24378. this._customAttenuationFunction = callback;
  24379. };
  24380. /**
  24381. * Play the sound
  24382. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  24383. */
  24384. Sound.prototype.play = function (time) {
  24385. if (this._isReadyToPlay) {
  24386. try {
  24387. var startTime = time ? this._audioEngine.audioContext.currentTime + time : 0;
  24388. this._soundSource = this._audioEngine.audioContext.createBufferSource();
  24389. this._soundSource.buffer = this._audioBuffer;
  24390. if (this.spatialSound) {
  24391. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  24392. if (this._isDirectional) {
  24393. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  24394. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  24395. this._soundPanner.coneOuterGain = this._coneOuterGain;
  24396. if (this._connectedMesh) {
  24397. this._updateDirection();
  24398. } else {
  24399. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  24400. }
  24401. }
  24402. }
  24403. this._soundSource.connect(this._audioNode);
  24404. this._soundSource.loop = this.loop;
  24405. this.startTime = startTime;
  24406. this._soundSource.start(startTime, this.startOffset % this._soundSource.buffer.duration);
  24407. this._isPlaying = true;
  24408. } catch (ex) {
  24409. BABYLON.Tools.Error("Error while trying to play audio: " + this._name + ", " + ex.message);
  24410. }
  24411. }
  24412. };
  24413. /**
  24414. * Stop the sound
  24415. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  24416. */
  24417. Sound.prototype.stop = function (time) {
  24418. var stopTime = time ? this._audioEngine.audioContext.currentTime + time : 0;
  24419. this._soundSource.stop(stopTime);
  24420. this._isPlaying = false;
  24421. };
  24422. Sound.prototype.pause = function () {
  24423. this._soundSource.stop(0);
  24424. this.startOffset += this._audioEngine.audioContext.currentTime - this.startTime;
  24425. };
  24426. Sound.prototype.setVolume = function (newVolume) {
  24427. this._volume = newVolume;
  24428. this._soundGain.gain.value = newVolume;
  24429. };
  24430. Sound.prototype.getVolume = function () {
  24431. return this._volume;
  24432. };
  24433. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  24434. var _this = this;
  24435. this._connectedMesh = meshToConnectTo;
  24436. if (!this.spatialSound) {
  24437. this._createSpatialParameters();
  24438. this.spatialSound = true;
  24439. if (this._isPlaying && this.loop) {
  24440. this.stop();
  24441. this.play();
  24442. }
  24443. }
  24444. meshToConnectTo.registerAfterWorldMatrixUpdate(function (connectedMesh) {
  24445. return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh);
  24446. });
  24447. };
  24448. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  24449. this.setPosition(connectedMesh.position);
  24450. if (this._isDirectional && this._isPlaying) {
  24451. this._updateDirection();
  24452. }
  24453. };
  24454. Sound.prototype._soundLoaded = function (audioData) {
  24455. var _this = this;
  24456. this._isLoaded = true;
  24457. this._audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  24458. _this._audioBuffer = buffer;
  24459. _this._isReadyToPlay = true;
  24460. if (_this.autoplay) {
  24461. _this.play();
  24462. }
  24463. if (_this._readyToPlayCallback) {
  24464. _this._readyToPlayCallback();
  24465. }
  24466. }, function (error) {
  24467. BABYLON.Tools.Error("Error while decoding audio data: " + error.err);
  24468. });
  24469. };
  24470. return Sound;
  24471. })();
  24472. BABYLON.Sound = Sound;
  24473. })(BABYLON || (BABYLON = {}));
  24474. //# sourceMappingURL=babylon.sound.js.map
  24475. var BABYLON;
  24476. (function (BABYLON) {
  24477. var SoundTrack = (function () {
  24478. function SoundTrack(scene, options) {
  24479. this.id = -1;
  24480. this._isMainTrack = false;
  24481. this._scene = scene;
  24482. this._audioEngine = scene.getEngine().getAudioEngine();
  24483. this.soundCollection = new Array();
  24484. if (this._audioEngine.canUseWebAudio) {
  24485. this._trackGain = this._audioEngine.audioContext.createGain();
  24486. //this._trackConvolver = this._audioEngine.audioContext.createConvolver();
  24487. //this._trackConvolver.connect(this._trackGain);
  24488. this._trackGain.connect(this._audioEngine.masterGain);
  24489. if (options) {
  24490. if (options.volume) {
  24491. this._trackGain.gain.value = options.volume;
  24492. }
  24493. if (options.mainTrack) {
  24494. this._isMainTrack = options.mainTrack;
  24495. }
  24496. }
  24497. }
  24498. if (!this._isMainTrack) {
  24499. this._scene.soundTracks.push(this);
  24500. this.id = this._scene.soundTracks.length - 1;
  24501. }
  24502. }
  24503. SoundTrack.prototype.AddSound = function (sound) {
  24504. sound.connectToSoundTrackAudioNode(this._trackGain);
  24505. if (sound.soundTrackId) {
  24506. if (sound.soundTrackId === -1) {
  24507. this._scene.mainSoundTrack.RemoveSound(sound);
  24508. } else {
  24509. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  24510. }
  24511. }
  24512. this.soundCollection.push(sound);
  24513. sound.soundTrackId = this.id;
  24514. };
  24515. SoundTrack.prototype.RemoveSound = function (sound) {
  24516. var index = this.soundCollection.indexOf(sound);
  24517. if (index !== -1) {
  24518. this.soundCollection.splice(index, 1);
  24519. }
  24520. };
  24521. SoundTrack.prototype.setVolume = function (newVolume) {
  24522. if (this._audioEngine.canUseWebAudio) {
  24523. this._trackGain.gain.value = newVolume;
  24524. }
  24525. };
  24526. return SoundTrack;
  24527. })();
  24528. BABYLON.SoundTrack = SoundTrack;
  24529. })(BABYLON || (BABYLON = {}));
  24530. //# sourceMappingURL=babylon.soundtrack.js.map
  24531. var BABYLON;
  24532. (function (BABYLON) {
  24533. var DebugLayer = (function () {
  24534. function DebugLayer(scene) {
  24535. var _this = this;
  24536. this._enabled = false;
  24537. this._labelsEnabled = false;
  24538. this._displayStatistics = true;
  24539. this._displayTree = false;
  24540. this._displayLogs = false;
  24541. this._identityMatrix = BABYLON.Matrix.Identity();
  24542. this.axisRatio = 0.02;
  24543. this.accentColor = "orange";
  24544. this._scene = scene;
  24545. this._syncPositions = function () {
  24546. var engine = _this._scene.getEngine();
  24547. var canvasRect = engine.getRenderingCanvasClientRect();
  24548. if (_this._showUI) {
  24549. _this._statsDiv.style.left = (canvasRect.width - 310) + "px";
  24550. _this._statsDiv.style.top = (canvasRect.height - 370) + "px";
  24551. _this._statsDiv.style.width = "300px";
  24552. _this._statsDiv.style.height = "360px";
  24553. _this._statsSubsetDiv.style.maxHeight = (canvasRect.height - 60) + "px";
  24554. _this._optionsDiv.style.left = "0px";
  24555. _this._optionsDiv.style.top = "10px";
  24556. _this._optionsDiv.style.width = "200px";
  24557. _this._optionsDiv.style.height = "auto";
  24558. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  24559. _this._logDiv.style.left = "0px";
  24560. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  24561. _this._logDiv.style.width = "600px";
  24562. _this._logDiv.style.height = "160px";
  24563. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  24564. _this._treeDiv.style.top = "10px";
  24565. _this._treeDiv.style.width = "300px";
  24566. _this._treeDiv.style.height = "auto";
  24567. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 430) + "px";
  24568. }
  24569. _this._globalDiv.style.left = canvasRect.left + "px";
  24570. _this._globalDiv.style.top = canvasRect.top + "px";
  24571. _this._drawingCanvas.style.left = "0px";
  24572. _this._drawingCanvas.style.top = "0px";
  24573. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  24574. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  24575. var devicePixelRatio = window.devicePixelRatio || 1;
  24576. var context = _this._drawingContext;
  24577. var backingStoreRatio = context.webkitBackingStorePixelRatio || context.mozBackingStorePixelRatio || context.msBackingStorePixelRatio || context.oBackingStorePixelRatio || context.backingStorePixelRatio || 1;
  24578. _this._ratio = devicePixelRatio / backingStoreRatio;
  24579. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  24580. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  24581. };
  24582. this._onCanvasClick = function (evt) {
  24583. _this._clickPosition = {
  24584. x: evt.clientX * _this._ratio,
  24585. y: evt.clientY * _this._ratio
  24586. };
  24587. };
  24588. this._syncData = function () {
  24589. if (_this._showUI) {
  24590. if (_this._displayStatistics) {
  24591. _this._displayStats();
  24592. _this._statsDiv.style.display = "";
  24593. } else {
  24594. _this._statsDiv.style.display = "none";
  24595. }
  24596. if (_this._displayLogs) {
  24597. _this._logDiv.style.display = "";
  24598. } else {
  24599. _this._logDiv.style.display = "none";
  24600. }
  24601. if (_this._displayTree) {
  24602. _this._treeDiv.style.display = "";
  24603. if (_this._needToRefreshMeshesTree) {
  24604. _this._needToRefreshMeshesTree = false;
  24605. _this._refreshMeshesTreeContent();
  24606. }
  24607. } else {
  24608. _this._treeDiv.style.display = "none";
  24609. }
  24610. }
  24611. if (_this._labelsEnabled || !_this._showUI) {
  24612. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  24613. var engine = _this._scene.getEngine();
  24614. var viewport = _this._scene.activeCamera.viewport;
  24615. var globalViewport = viewport.toGlobal(engine);
  24616. // Meshes
  24617. var meshes = _this._scene.getActiveMeshes();
  24618. for (var index = 0; index < meshes.length; index++) {
  24619. var mesh = meshes.data[index];
  24620. var position = mesh.getBoundingInfo().boundingSphere.center;
  24621. var projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._scene.getTransformMatrix(), globalViewport);
  24622. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  24623. _this._renderAxis(projectedPosition, mesh, globalViewport);
  24624. }
  24625. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  24626. _this._renderLabel(mesh.name, projectedPosition, 12, function () {
  24627. mesh.renderOverlay = !mesh.renderOverlay;
  24628. }, function () {
  24629. return mesh.renderOverlay ? 'red' : 'black';
  24630. });
  24631. }
  24632. }
  24633. // Cameras
  24634. var cameras = _this._scene.cameras;
  24635. for (index = 0; index < cameras.length; index++) {
  24636. var camera = cameras[index];
  24637. if (camera === _this._scene.activeCamera) {
  24638. continue;
  24639. }
  24640. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._scene.getTransformMatrix(), globalViewport);
  24641. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  24642. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  24643. _this._scene.activeCamera.detachControl(engine.getRenderingCanvas());
  24644. _this._scene.activeCamera = camera;
  24645. _this._scene.activeCamera.attachControl(engine.getRenderingCanvas());
  24646. }, function () {
  24647. return "purple";
  24648. });
  24649. }
  24650. }
  24651. // Lights
  24652. var lights = _this._scene.lights;
  24653. for (index = 0; index < lights.length; index++) {
  24654. var light = lights[index];
  24655. if (light.position) {
  24656. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._scene.getTransformMatrix(), globalViewport);
  24657. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  24658. _this._renderLabel(light.name, projectedPosition, -20, function () {
  24659. light.setEnabled(!light.isEnabled());
  24660. }, function () {
  24661. return light.isEnabled() ? "orange" : "gray";
  24662. });
  24663. }
  24664. }
  24665. }
  24666. }
  24667. _this._clickPosition = undefined;
  24668. };
  24669. }
  24670. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  24671. while (this._treeSubsetDiv.hasChildNodes()) {
  24672. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  24673. }
  24674. // Add meshes
  24675. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  24676. sortedArray.sort(function (a, b) {
  24677. if (a.name === b.name) {
  24678. return 0;
  24679. }
  24680. return (a.name > b.name) ? 1 : -1;
  24681. });
  24682. for (var index = 0; index < sortedArray.length; index++) {
  24683. var mesh = sortedArray[index];
  24684. if (!mesh.isEnabled()) {
  24685. continue;
  24686. }
  24687. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  24688. m.isVisible = element.checked;
  24689. }, mesh);
  24690. }
  24691. };
  24692. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  24693. this._drawingContext.beginPath();
  24694. this._drawingContext.moveTo(zero.x, zero.y);
  24695. this._drawingContext.lineTo(unit.x, unit.y);
  24696. this._drawingContext.strokeStyle = color;
  24697. this._drawingContext.lineWidth = 4;
  24698. this._drawingContext.stroke();
  24699. this._drawingContext.font = "normal 14px Segoe UI";
  24700. this._drawingContext.fillStyle = color;
  24701. this._drawingContext.fillText(label, unitText.x, unitText.y);
  24702. };
  24703. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  24704. var position = mesh.getBoundingInfo().boundingSphere.center;
  24705. var worldMatrix = mesh.getWorldMatrix();
  24706. var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._scene.getTransformMatrix());
  24707. var unit = (unprojectedVector.subtract(position)).length();
  24708. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  24709. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  24710. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  24711. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  24712. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  24713. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  24714. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  24715. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  24716. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  24717. };
  24718. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  24719. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  24720. this._drawingContext.font = "normal 12px Segoe UI";
  24721. var textMetrics = this._drawingContext.measureText(text);
  24722. var centerX = projectedPosition.x - textMetrics.width / 2;
  24723. var centerY = projectedPosition.y;
  24724. if (this._isClickInsideRect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  24725. onClick();
  24726. }
  24727. this._drawingContext.beginPath();
  24728. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  24729. this._drawingContext.fillStyle = getFillStyle();
  24730. this._drawingContext.globalAlpha = 0.5;
  24731. this._drawingContext.fill();
  24732. this._drawingContext.globalAlpha = 1.0;
  24733. this._drawingContext.strokeStyle = '#FFFFFF';
  24734. this._drawingContext.lineWidth = 1;
  24735. this._drawingContext.stroke();
  24736. this._drawingContext.fillStyle = "#FFFFFF";
  24737. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  24738. this._drawingContext.beginPath();
  24739. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  24740. this._drawingContext.fill();
  24741. }
  24742. };
  24743. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  24744. if (!this._clickPosition) {
  24745. return false;
  24746. }
  24747. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  24748. return false;
  24749. }
  24750. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  24751. return false;
  24752. }
  24753. return true;
  24754. };
  24755. DebugLayer.prototype.isVisible = function () {
  24756. return this._enabled;
  24757. };
  24758. DebugLayer.prototype.hide = function () {
  24759. if (!this._enabled) {
  24760. return;
  24761. }
  24762. this._enabled = false;
  24763. var engine = this._scene.getEngine();
  24764. this._scene.unregisterAfterRender(this._syncData);
  24765. document.body.removeChild(this._globalDiv);
  24766. window.removeEventListener("resize", this._syncPositions);
  24767. this._scene.forceShowBoundingBoxes = false;
  24768. this._scene.forceWireframe = false;
  24769. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  24770. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  24771. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  24772. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  24773. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  24774. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  24775. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  24776. this._scene.shadowsEnabled = true;
  24777. this._scene.particlesEnabled = true;
  24778. this._scene.postProcessesEnabled = true;
  24779. this._scene.collisionsEnabled = true;
  24780. this._scene.lightsEnabled = true;
  24781. this._scene.texturesEnabled = true;
  24782. this._scene.lensFlaresEnabled = true;
  24783. this._scene.proceduralTexturesEnabled = true;
  24784. this._scene.renderTargetsEnabled = true;
  24785. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  24786. };
  24787. DebugLayer.prototype.show = function (showUI) {
  24788. if (typeof showUI === "undefined") { showUI = true; }
  24789. if (this._enabled) {
  24790. return;
  24791. }
  24792. this._enabled = true;
  24793. this._showUI = showUI;
  24794. var engine = this._scene.getEngine();
  24795. this._globalDiv = document.createElement("div");
  24796. document.body.appendChild(this._globalDiv);
  24797. this._generateDOMelements();
  24798. window.addEventListener("resize", this._syncPositions);
  24799. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  24800. this._syncPositions();
  24801. this._scene.registerAfterRender(this._syncData);
  24802. };
  24803. DebugLayer.prototype._clearLabels = function () {
  24804. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  24805. for (var index = 0; index < this._scene.meshes.length; index++) {
  24806. var mesh = this._scene.meshes[index];
  24807. mesh.renderOverlay = false;
  24808. }
  24809. };
  24810. DebugLayer.prototype._generateheader = function (root, text) {
  24811. var header = document.createElement("div");
  24812. header.innerHTML = text + "&nbsp;";
  24813. header.style.textAlign = "right";
  24814. header.style.width = "100%";
  24815. header.style.color = "white";
  24816. header.style.backgroundColor = "Black";
  24817. header.style.padding = "5px 5px 4px 0px";
  24818. header.style.marginLeft = "-5px";
  24819. header.style.fontWeight = "bold";
  24820. root.appendChild(header);
  24821. };
  24822. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  24823. var label = document.createElement("label");
  24824. label.innerHTML = title;
  24825. label.style.color = color;
  24826. root.appendChild(label);
  24827. root.appendChild(document.createElement("br"));
  24828. };
  24829. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  24830. if (typeof tag === "undefined") { tag = null; }
  24831. var label = document.createElement("label");
  24832. var boundingBoxesCheckbox = document.createElement("input");
  24833. boundingBoxesCheckbox.type = "checkbox";
  24834. boundingBoxesCheckbox.checked = initialState;
  24835. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  24836. task(evt.target, tag);
  24837. });
  24838. label.appendChild(boundingBoxesCheckbox);
  24839. var container = document.createElement("span");
  24840. var leftPart = document.createElement("span");
  24841. var rightPart = document.createElement("span");
  24842. rightPart.style.cssFloat = "right";
  24843. leftPart.innerHTML = leftTitle;
  24844. rightPart.innerHTML = rightTitle;
  24845. rightPart.style.fontSize = "12px";
  24846. rightPart.style.maxWidth = "200px";
  24847. container.appendChild(leftPart);
  24848. container.appendChild(rightPart);
  24849. label.appendChild(container);
  24850. root.appendChild(label);
  24851. root.appendChild(document.createElement("br"));
  24852. };
  24853. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  24854. if (typeof tag === "undefined") { tag = null; }
  24855. var label = document.createElement("label");
  24856. var boundingBoxesCheckbox = document.createElement("input");
  24857. boundingBoxesCheckbox.type = "checkbox";
  24858. boundingBoxesCheckbox.checked = initialState;
  24859. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  24860. task(evt.target, tag);
  24861. });
  24862. label.appendChild(boundingBoxesCheckbox);
  24863. label.appendChild(document.createTextNode(title));
  24864. root.appendChild(label);
  24865. root.appendChild(document.createElement("br"));
  24866. };
  24867. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  24868. if (typeof tag === "undefined") { tag = null; }
  24869. var label = document.createElement("label");
  24870. var boundingBoxesRadio = document.createElement("input");
  24871. boundingBoxesRadio.type = "radio";
  24872. boundingBoxesRadio.name = name;
  24873. boundingBoxesRadio.checked = initialState;
  24874. boundingBoxesRadio.addEventListener("change", function (evt) {
  24875. task(evt.target, tag);
  24876. });
  24877. label.appendChild(boundingBoxesRadio);
  24878. label.appendChild(document.createTextNode(title));
  24879. root.appendChild(label);
  24880. root.appendChild(document.createElement("br"));
  24881. };
  24882. DebugLayer.prototype._generateDOMelements = function () {
  24883. var _this = this;
  24884. this._globalDiv.id = "DebugLayer";
  24885. this._globalDiv.style.position = "absolute";
  24886. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  24887. this._globalDiv.style.fontSize = "14px";
  24888. this._globalDiv.style.color = "white";
  24889. // Drawing canvas
  24890. this._drawingCanvas = document.createElement("canvas");
  24891. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  24892. this._drawingCanvas.style.position = "absolute";
  24893. this._drawingCanvas.style.pointerEvents = "none";
  24894. this._drawingContext = this._drawingCanvas.getContext("2d");
  24895. this._globalDiv.appendChild(this._drawingCanvas);
  24896. if (this._showUI) {
  24897. var background = "rgba(128, 128, 128, 0.4)";
  24898. var border = "rgb(180, 180, 180) solid 1px";
  24899. // Stats
  24900. this._statsDiv = document.createElement("div");
  24901. this._statsDiv.id = "DebugLayerStats";
  24902. this._statsDiv.style.border = border;
  24903. this._statsDiv.style.position = "absolute";
  24904. this._statsDiv.style.background = background;
  24905. this._statsDiv.style.padding = "0px 0px 0px 5px";
  24906. this._statsDiv.style.pointerEvents = "none";
  24907. this._statsDiv.style.overflowY = "auto";
  24908. this._generateheader(this._statsDiv, "STATISTICS");
  24909. this._statsSubsetDiv = document.createElement("div");
  24910. this._statsSubsetDiv.style.paddingTop = "5px";
  24911. this._statsSubsetDiv.style.paddingBottom = "5px";
  24912. this._statsDiv.appendChild(this._statsSubsetDiv);
  24913. // Tree
  24914. this._treeDiv = document.createElement("div");
  24915. this._treeDiv.id = "DebugLayerTree";
  24916. this._treeDiv.style.border = border;
  24917. this._treeDiv.style.position = "absolute";
  24918. this._treeDiv.style.background = background;
  24919. this._treeDiv.style.padding = "0px 0px 0px 5px";
  24920. this._treeDiv.style.display = "none";
  24921. this._generateheader(this._treeDiv, "MESHES TREE");
  24922. this._treeSubsetDiv = document.createElement("div");
  24923. this._treeSubsetDiv.style.paddingTop = "5px";
  24924. this._treeSubsetDiv.style.paddingRight = "5px";
  24925. this._treeSubsetDiv.style.overflowY = "auto";
  24926. this._treeSubsetDiv.style.maxHeight = "300px";
  24927. this._treeDiv.appendChild(this._treeSubsetDiv);
  24928. this._needToRefreshMeshesTree = true;
  24929. // Logs
  24930. this._logDiv = document.createElement("div");
  24931. this._logDiv.style.border = border;
  24932. this._logDiv.id = "DebugLayerLogs";
  24933. this._logDiv.style.position = "absolute";
  24934. this._logDiv.style.background = background;
  24935. this._logDiv.style.padding = "0px 0px 0px 5px";
  24936. this._logDiv.style.display = "none";
  24937. this._generateheader(this._logDiv, "LOGS");
  24938. this._logSubsetDiv = document.createElement("div");
  24939. this._logSubsetDiv.style.height = "127px";
  24940. this._logSubsetDiv.style.paddingTop = "5px";
  24941. this._logSubsetDiv.style.overflowY = "auto";
  24942. this._logSubsetDiv.style.fontSize = "12px";
  24943. this._logSubsetDiv.style.fontFamily = "consolas";
  24944. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  24945. this._logDiv.appendChild(this._logSubsetDiv);
  24946. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  24947. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  24948. };
  24949. // Options
  24950. this._optionsDiv = document.createElement("div");
  24951. this._optionsDiv.id = "DebugLayerOptions";
  24952. this._optionsDiv.style.border = border;
  24953. this._optionsDiv.style.position = "absolute";
  24954. this._optionsDiv.style.background = background;
  24955. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  24956. this._optionsDiv.style.overflowY = "auto";
  24957. this._generateheader(this._optionsDiv, "OPTIONS");
  24958. this._optionsSubsetDiv = document.createElement("div");
  24959. this._optionsSubsetDiv.style.paddingTop = "5px";
  24960. this._optionsSubsetDiv.style.paddingBottom = "5px";
  24961. this._optionsSubsetDiv.style.overflowY = "auto";
  24962. this._optionsSubsetDiv.style.maxHeight = "200px";
  24963. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  24964. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  24965. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) {
  24966. _this._displayStatistics = element.checked;
  24967. });
  24968. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) {
  24969. _this._displayLogs = element.checked;
  24970. });
  24971. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  24972. _this._displayTree = element.checked;
  24973. _this._needToRefreshMeshesTree = true;
  24974. });
  24975. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) {
  24976. _this._scene.forceShowBoundingBoxes = element.checked;
  24977. });
  24978. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  24979. _this._labelsEnabled = element.checked;
  24980. if (!_this._labelsEnabled) {
  24981. _this._clearLabels();
  24982. }
  24983. });
  24984. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  24985. if (element.checked) {
  24986. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  24987. } else {
  24988. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  24989. }
  24990. });
  24991. ;
  24992. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  24993. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  24994. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  24995. if (element.checked) {
  24996. _this._scene.forceWireframe = false;
  24997. _this._scene.forcePointsCloud = false;
  24998. }
  24999. });
  25000. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  25001. if (element.checked) {
  25002. _this._scene.forceWireframe = true;
  25003. _this._scene.forcePointsCloud = false;
  25004. }
  25005. });
  25006. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  25007. if (element.checked) {
  25008. _this._scene.forceWireframe = false;
  25009. _this._scene.forcePointsCloud = true;
  25010. }
  25011. });
  25012. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  25013. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  25014. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) {
  25015. BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked;
  25016. });
  25017. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) {
  25018. BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked;
  25019. });
  25020. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) {
  25021. BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked;
  25022. });
  25023. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) {
  25024. BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked;
  25025. });
  25026. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) {
  25027. BABYLON.StandardMaterial.BumpTextureEnabled = element.checked;
  25028. });
  25029. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) {
  25030. BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked;
  25031. });
  25032. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) {
  25033. BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked;
  25034. });
  25035. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) {
  25036. BABYLON.StandardMaterial.FresnelEnabled = element.checked;
  25037. });
  25038. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  25039. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  25040. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) {
  25041. _this._scene.animationsEnabled = element.checked;
  25042. });
  25043. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) {
  25044. _this._scene.collisionsEnabled = element.checked;
  25045. });
  25046. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) {
  25047. _this._scene.fogEnabled = element.checked;
  25048. });
  25049. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) {
  25050. _this._scene.lensFlaresEnabled = element.checked;
  25051. });
  25052. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) {
  25053. _this._scene.lightsEnabled = element.checked;
  25054. });
  25055. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) {
  25056. _this._scene.particlesEnabled = element.checked;
  25057. });
  25058. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) {
  25059. _this._scene.postProcessesEnabled = element.checked;
  25060. });
  25061. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) {
  25062. _this._scene.proceduralTexturesEnabled = element.checked;
  25063. });
  25064. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) {
  25065. _this._scene.renderTargetsEnabled = element.checked;
  25066. });
  25067. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) {
  25068. _this._scene.shadowsEnabled = element.checked;
  25069. });
  25070. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) {
  25071. _this._scene.skeletonsEnabled = element.checked;
  25072. });
  25073. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) {
  25074. _this._scene.texturesEnabled = element.checked;
  25075. });
  25076. this._globalDiv.appendChild(this._statsDiv);
  25077. this._globalDiv.appendChild(this._logDiv);
  25078. this._globalDiv.appendChild(this._optionsDiv);
  25079. this._globalDiv.appendChild(this._treeDiv);
  25080. }
  25081. };
  25082. DebugLayer.prototype._displayStats = function () {
  25083. var scene = this._scene;
  25084. var engine = scene.getEngine();
  25085. this._statsSubsetDiv.innerHTML = "Babylon.js v" + BABYLON.Engine.Version + " - <b>" + BABYLON.Tools.Format(engine.getFps(), 0) + " fps</b><br><br>" + "Total meshes: " + scene.meshes.length + "<br>" + "Total vertices: " + scene.getTotalVertices() + "<br>" + "Active meshes: " + scene.getActiveMeshes().length + "<br>" + "Active vertices: " + scene.getActiveVertices() + "<br>" + "Active bones: " + scene.getActiveBones() + "<br>" + "Active particles: " + scene.getActiveParticles() + "<br><br>" + "Frame duration: " + BABYLON.Tools.Format(scene.getLastFrameDuration()) + " ms<br>" + "<b>Draw calls: " + engine.drawCalls + "</b><br><br>" + "<i>Evaluate Active Meshes duration:</i> " + BABYLON.Tools.Format(scene.getEvaluateActiveMeshesDuration()) + " ms<br>" + "<i>Render Targets duration:</i> " + BABYLON.Tools.Format(scene.getRenderTargetsDuration()) + " ms<br>" + "<i>Particles duration:</i> " + BABYLON.Tools.Format(scene.getParticlesDuration()) + " ms<br>" + "<i>Sprites duration:</i> " + BABYLON.Tools.Format(scene.getSpritesDuration()) + " ms<br>" + "<i>Render duration:</i> <b>" + BABYLON.Tools.Format(scene.getRenderDuration()) + " ms</b>";
  25086. };
  25087. return DebugLayer;
  25088. })();
  25089. BABYLON.DebugLayer = DebugLayer;
  25090. })(BABYLON || (BABYLON = {}));
  25091. //# sourceMappingURL=babylon.debugLayer.js.map
  25092. var BABYLON;
  25093. (function (BABYLON) {
  25094. var RawTexture = (function (_super) {
  25095. __extends(RawTexture, _super);
  25096. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  25097. if (typeof generateMipMaps === "undefined") { generateMipMaps = true; }
  25098. if (typeof invertY === "undefined") { invertY = false; }
  25099. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  25100. _super.call(this, null, scene, !generateMipMaps, invertY);
  25101. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  25102. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  25103. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  25104. }
  25105. // Statics
  25106. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  25107. if (typeof generateMipMaps === "undefined") { generateMipMaps = true; }
  25108. if (typeof invertY === "undefined") { invertY = false; }
  25109. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  25110. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  25111. };
  25112. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  25113. if (typeof generateMipMaps === "undefined") { generateMipMaps = true; }
  25114. if (typeof invertY === "undefined") { invertY = false; }
  25115. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  25116. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  25117. };
  25118. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  25119. if (typeof generateMipMaps === "undefined") { generateMipMaps = true; }
  25120. if (typeof invertY === "undefined") { invertY = false; }
  25121. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  25122. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  25123. };
  25124. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  25125. if (typeof generateMipMaps === "undefined") { generateMipMaps = true; }
  25126. if (typeof invertY === "undefined") { invertY = false; }
  25127. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  25128. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  25129. };
  25130. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  25131. if (typeof generateMipMaps === "undefined") { generateMipMaps = true; }
  25132. if (typeof invertY === "undefined") { invertY = false; }
  25133. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  25134. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  25135. };
  25136. return RawTexture;
  25137. })(BABYLON.Texture);
  25138. BABYLON.RawTexture = RawTexture;
  25139. })(BABYLON || (BABYLON = {}));
  25140. //# sourceMappingURL=babylon.rawTexture.js.map
  25141. var BABYLON;
  25142. (function (BABYLON) {
  25143. var IndexedVector2 = (function (_super) {
  25144. __extends(IndexedVector2, _super);
  25145. function IndexedVector2(original, index) {
  25146. _super.call(this, original.x, original.y);
  25147. this.index = index;
  25148. }
  25149. return IndexedVector2;
  25150. })(BABYLON.Vector2);
  25151. var PolygonPoints = (function () {
  25152. function PolygonPoints() {
  25153. this.elements = new Array();
  25154. }
  25155. PolygonPoints.prototype.add = function (originalPoints) {
  25156. var _this = this;
  25157. var result = new Array();
  25158. originalPoints.forEach(function (point) {
  25159. if (result.length === 0 || !(BABYLON.Tools.WithinEpsilon(point.x, result[0].x, 0.00001) && BABYLON.Tools.WithinEpsilon(point.y, result[0].y, 0.00001))) {
  25160. var newPoint = new IndexedVector2(point, _this.elements.length);
  25161. result.push(newPoint);
  25162. _this.elements.push(newPoint);
  25163. }
  25164. });
  25165. return result;
  25166. };
  25167. PolygonPoints.prototype.computeBounds = function () {
  25168. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  25169. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  25170. this.elements.forEach(function (point) {
  25171. // x
  25172. if (point.x < lmin.x) {
  25173. lmin.x = point.x;
  25174. } else if (point.x > lmax.x) {
  25175. lmax.x = point.x;
  25176. }
  25177. // y
  25178. if (point.y < lmin.y) {
  25179. lmin.y = point.y;
  25180. } else if (point.y > lmax.y) {
  25181. lmax.y = point.y;
  25182. }
  25183. });
  25184. return {
  25185. min: lmin,
  25186. max: lmax,
  25187. width: lmax.x - lmin.x,
  25188. height: lmax.y - lmin.y
  25189. };
  25190. };
  25191. return PolygonPoints;
  25192. })();
  25193. var Polygon = (function () {
  25194. function Polygon() {
  25195. }
  25196. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  25197. return [
  25198. new BABYLON.Vector2(xmin, ymin),
  25199. new BABYLON.Vector2(xmax, ymin),
  25200. new BABYLON.Vector2(xmax, ymax),
  25201. new BABYLON.Vector2(xmin, ymax)
  25202. ];
  25203. };
  25204. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  25205. if (typeof cx === "undefined") { cx = 0; }
  25206. if (typeof cy === "undefined") { cy = 0; }
  25207. if (typeof numberOfSides === "undefined") { numberOfSides = 32; }
  25208. var result = new Array();
  25209. var angle = 0;
  25210. var increment = (Math.PI * 2) / numberOfSides;
  25211. for (var i = 0; i < numberOfSides; i++) {
  25212. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  25213. angle -= increment;
  25214. }
  25215. return result;
  25216. };
  25217. Polygon.Parse = function (input) {
  25218. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) {
  25219. return (!isNaN(val));
  25220. });
  25221. var i, result = [];
  25222. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  25223. result.push(new poly2tri.Point(floats[i], floats[i + 1]));
  25224. }
  25225. return result;
  25226. };
  25227. Polygon.StartingAt = function (x, y) {
  25228. return BABYLON.Path2.StartingAt(x, y);
  25229. };
  25230. return Polygon;
  25231. })();
  25232. BABYLON.Polygon = Polygon;
  25233. var PolygonMeshBuilder = (function () {
  25234. function PolygonMeshBuilder(name, contours, scene) {
  25235. this._points = new PolygonPoints();
  25236. if (!("poly2tri" in window)) {
  25237. throw "PolygonMeshBuilder cannot be used because poly2tri is not referenced";
  25238. }
  25239. this._name = name;
  25240. this._scene = scene;
  25241. var points;
  25242. if (contours instanceof BABYLON.Path2) {
  25243. points = contours.getPoints();
  25244. } else {
  25245. points = contours;
  25246. }
  25247. this._swctx = new poly2tri.SweepContext(this._points.add(points));
  25248. }
  25249. PolygonMeshBuilder.prototype.addHole = function (hole) {
  25250. this._swctx.addHole(this._points.add(hole));
  25251. return this;
  25252. };
  25253. PolygonMeshBuilder.prototype.build = function (updatable) {
  25254. if (typeof updatable === "undefined") { updatable = false; }
  25255. var result = new BABYLON.Mesh(this._name, this._scene);
  25256. var normals = [];
  25257. var positions = [];
  25258. var uvs = [];
  25259. var bounds = this._points.computeBounds();
  25260. this._points.elements.forEach(function (p) {
  25261. normals.push(0, 1.0, 0);
  25262. positions.push(p.x, 0, p.y);
  25263. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  25264. });
  25265. var indices = [];
  25266. this._swctx.triangulate();
  25267. this._swctx.getTriangles().forEach(function (triangle) {
  25268. triangle.getPoints().forEach(function (point) {
  25269. indices.push(point.index);
  25270. });
  25271. });
  25272. result.setVerticesData(positions, BABYLON.VertexBuffer.PositionKind, updatable);
  25273. result.setVerticesData(normals, BABYLON.VertexBuffer.NormalKind, updatable);
  25274. result.setVerticesData(uvs, BABYLON.VertexBuffer.UVKind, updatable);
  25275. result.setIndices(indices);
  25276. return result;
  25277. };
  25278. return PolygonMeshBuilder;
  25279. })();
  25280. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  25281. })(BABYLON || (BABYLON = {}));
  25282. //# sourceMappingURL=babylon.polygonMesh.js.map