babylon.2.0-alpha.debug.js 1.0 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628
  1. var BABYLON;
  2. (function (BABYLON) {
  3. var Color3 = (function () {
  4. function Color3(r, g, b) {
  5. if (typeof r === "undefined") { r = 0; }
  6. if (typeof g === "undefined") { g = 0; }
  7. if (typeof b === "undefined") { b = 0; }
  8. this.r = r;
  9. this.g = g;
  10. this.b = b;
  11. }
  12. Color3.prototype.toString = function () {
  13. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  14. };
  15. Color3.prototype.toArray = function (array, index) {
  16. if (index === undefined) {
  17. index = 0;
  18. }
  19. array[index] = this.r;
  20. array[index + 1] = this.g;
  21. array[index + 2] = this.b;
  22. };
  23. Color3.prototype.toColor4 = function (alpha) {
  24. if (typeof alpha === "undefined") { alpha = 1; }
  25. return new Color4(this.r, this.g, this.b, alpha);
  26. };
  27. Color3.prototype.asArray = function () {
  28. var result = [];
  29. this.toArray(result, 0);
  30. return result;
  31. };
  32. Color3.prototype.toLuminance = function () {
  33. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  34. };
  35. Color3.prototype.multiply = function (otherColor) {
  36. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  37. };
  38. Color3.prototype.multiplyToRef = function (otherColor, result) {
  39. result.r = this.r * otherColor.r;
  40. result.g = this.g * otherColor.g;
  41. result.b = this.b * otherColor.b;
  42. };
  43. Color3.prototype.equals = function (otherColor) {
  44. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  45. };
  46. Color3.prototype.scale = function (scale) {
  47. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  48. };
  49. Color3.prototype.scaleToRef = function (scale, result) {
  50. result.r = this.r * scale;
  51. result.g = this.g * scale;
  52. result.b = this.b * scale;
  53. };
  54. Color3.prototype.add = function (otherColor) {
  55. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  56. };
  57. Color3.prototype.addToRef = function (otherColor, result) {
  58. result.r = this.r + otherColor.r;
  59. result.g = this.g + otherColor.g;
  60. result.b = this.b + otherColor.b;
  61. };
  62. Color3.prototype.subtract = function (otherColor) {
  63. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  64. };
  65. Color3.prototype.subtractToRef = function (otherColor, result) {
  66. result.r = this.r - otherColor.r;
  67. result.g = this.g - otherColor.g;
  68. result.b = this.b - otherColor.b;
  69. };
  70. Color3.prototype.clone = function () {
  71. return new Color3(this.r, this.g, this.b);
  72. };
  73. Color3.prototype.copyFrom = function (source) {
  74. this.r = source.r;
  75. this.g = source.g;
  76. this.b = source.b;
  77. };
  78. Color3.prototype.copyFromFloats = function (r, g, b) {
  79. this.r = r;
  80. this.g = g;
  81. this.b = b;
  82. };
  83. Color3.FromArray = function (array) {
  84. return new Color3(array[0], array[1], array[2]);
  85. };
  86. Color3.FromInts = function (r, g, b) {
  87. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  88. };
  89. Color3.Lerp = function (start, end, amount) {
  90. var r = start.r + ((end.r - start.r) * amount);
  91. var g = start.g + ((end.g - start.g) * amount);
  92. var b = start.b + ((end.b - start.b) * amount);
  93. return new Color3(r, g, b);
  94. };
  95. Color3.Red = function () {
  96. return new Color3(1, 0, 0);
  97. };
  98. Color3.Green = function () {
  99. return new Color3(0, 1, 0);
  100. };
  101. Color3.Blue = function () {
  102. return new Color3(0, 0, 1);
  103. };
  104. Color3.Black = function () {
  105. return new Color3(0, 0, 0);
  106. };
  107. Color3.White = function () {
  108. return new Color3(1, 1, 1);
  109. };
  110. Color3.Purple = function () {
  111. return new Color3(0.5, 0, 0.5);
  112. };
  113. Color3.Magenta = function () {
  114. return new Color3(1, 0, 1);
  115. };
  116. Color3.Yellow = function () {
  117. return new Color3(1, 1, 0);
  118. };
  119. Color3.Gray = function () {
  120. return new Color3(0.5, 0.5, 0.5);
  121. };
  122. return Color3;
  123. })();
  124. BABYLON.Color3 = Color3;
  125. var Color4 = (function () {
  126. function Color4(r, g, b, a) {
  127. this.r = r;
  128. this.g = g;
  129. this.b = b;
  130. this.a = a;
  131. }
  132. Color4.prototype.addInPlace = function (right) {
  133. this.r += right.r;
  134. this.g += right.g;
  135. this.b += right.b;
  136. this.a += right.a;
  137. };
  138. Color4.prototype.asArray = function () {
  139. var result = [];
  140. this.toArray(result, 0);
  141. return result;
  142. };
  143. Color4.prototype.toArray = function (array, index) {
  144. if (index === undefined) {
  145. index = 0;
  146. }
  147. array[index] = this.r;
  148. array[index + 1] = this.g;
  149. array[index + 2] = this.b;
  150. array[index + 3] = this.a;
  151. };
  152. Color4.prototype.add = function (right) {
  153. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  154. };
  155. Color4.prototype.subtract = function (right) {
  156. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  157. };
  158. Color4.prototype.subtractToRef = function (right, result) {
  159. result.r = this.r - right.r;
  160. result.g = this.g - right.g;
  161. result.b = this.b - right.b;
  162. result.a = this.a - right.a;
  163. };
  164. Color4.prototype.scale = function (scale) {
  165. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  166. };
  167. Color4.prototype.scaleToRef = function (scale, result) {
  168. result.r = this.r * scale;
  169. result.g = this.g * scale;
  170. result.b = this.b * scale;
  171. result.a = this.a * scale;
  172. };
  173. Color4.prototype.toString = function () {
  174. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  175. };
  176. Color4.prototype.clone = function () {
  177. return new Color4(this.r, this.g, this.b, this.a);
  178. };
  179. Color4.Lerp = function (left, right, amount) {
  180. var result = new Color4(0, 0, 0, 0);
  181. BABYLON.Color4.LerpToRef(left, right, amount, result);
  182. return result;
  183. };
  184. Color4.LerpToRef = function (left, right, amount, result) {
  185. result.r = left.r + (right.r - left.r) * amount;
  186. result.g = left.g + (right.g - left.g) * amount;
  187. result.b = left.b + (right.b - left.b) * amount;
  188. result.a = left.a + (right.a - left.a) * amount;
  189. };
  190. Color4.FromArray = function (array, offset) {
  191. if (typeof offset === "undefined") { offset = 0; }
  192. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  193. };
  194. Color4.FromInts = function (r, g, b, a) {
  195. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  196. };
  197. return Color4;
  198. })();
  199. BABYLON.Color4 = Color4;
  200. var Vector2 = (function () {
  201. function Vector2(x, y) {
  202. this.x = x;
  203. this.y = y;
  204. }
  205. Vector2.prototype.toString = function () {
  206. return "{X: " + this.x + " Y:" + this.y + "}";
  207. };
  208. Vector2.prototype.toArray = function (array, index) {
  209. if (index === undefined) {
  210. index = 0;
  211. }
  212. array[index] = this.x;
  213. array[index + 1] = this.y;
  214. };
  215. Vector2.prototype.asArray = function () {
  216. var result = [];
  217. this.toArray(result, 0);
  218. return result;
  219. };
  220. Vector2.prototype.copyFrom = function (source) {
  221. this.x = source.x;
  222. this.y = source.y;
  223. };
  224. Vector2.prototype.copyFromFloats = function (x, y) {
  225. this.x = x;
  226. this.y = y;
  227. };
  228. Vector2.prototype.add = function (otherVector) {
  229. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  230. };
  231. Vector2.prototype.addVector3 = function (otherVector) {
  232. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  233. };
  234. Vector2.prototype.subtract = function (otherVector) {
  235. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  236. };
  237. Vector2.prototype.subtractInPlace = function (otherVector) {
  238. this.x -= otherVector.x;
  239. this.y -= otherVector.y;
  240. };
  241. Vector2.prototype.multiplyInPlace = function (otherVector) {
  242. this.x *= otherVector.x;
  243. this.y *= otherVector.y;
  244. };
  245. Vector2.prototype.multiply = function (otherVector) {
  246. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  247. };
  248. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  249. result.x = this.x * otherVector.x;
  250. result.y = this.y * otherVector.y;
  251. };
  252. Vector2.prototype.multiplyByFloats = function (x, y) {
  253. return new Vector2(this.x * x, this.y * y);
  254. };
  255. Vector2.prototype.divide = function (otherVector) {
  256. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  257. };
  258. Vector2.prototype.divideToRef = function (otherVector, result) {
  259. result.x = this.x / otherVector.x;
  260. result.y = this.y / otherVector.y;
  261. };
  262. Vector2.prototype.negate = function () {
  263. return new Vector2(-this.x, -this.y);
  264. };
  265. Vector2.prototype.scaleInPlace = function (scale) {
  266. this.x *= scale;
  267. this.y *= scale;
  268. return this;
  269. };
  270. Vector2.prototype.scale = function (scale) {
  271. return new Vector2(this.x * scale, this.y * scale);
  272. };
  273. Vector2.prototype.equals = function (otherVector) {
  274. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  275. };
  276. Vector2.prototype.length = function () {
  277. return Math.sqrt(this.x * this.x + this.y * this.y);
  278. };
  279. Vector2.prototype.lengthSquared = function () {
  280. return (this.x * this.x + this.y * this.y);
  281. };
  282. Vector2.prototype.normalize = function () {
  283. var len = this.length();
  284. if (len === 0)
  285. return this;
  286. var num = 1.0 / len;
  287. this.x *= num;
  288. this.y *= num;
  289. return this;
  290. };
  291. Vector2.prototype.clone = function () {
  292. return new Vector2(this.x, this.y);
  293. };
  294. Vector2.Zero = function () {
  295. return new Vector2(0, 0);
  296. };
  297. Vector2.FromArray = function (array, offset) {
  298. if (!offset) {
  299. offset = 0;
  300. }
  301. return new Vector2(array[offset], array[offset + 1]);
  302. };
  303. Vector2.FromArrayToRef = function (array, offset, result) {
  304. result.x = array[offset];
  305. result.y = array[offset + 1];
  306. };
  307. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  308. var squared = amount * amount;
  309. var cubed = amount * squared;
  310. 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));
  311. 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));
  312. return new Vector2(x, y);
  313. };
  314. Vector2.Clamp = function (value, min, max) {
  315. var x = value.x;
  316. x = (x > max.x) ? max.x : x;
  317. x = (x < min.x) ? min.x : x;
  318. var y = value.y;
  319. y = (y > max.y) ? max.y : y;
  320. y = (y < min.y) ? min.y : y;
  321. return new Vector2(x, y);
  322. };
  323. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  324. var squared = amount * amount;
  325. var cubed = amount * squared;
  326. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  327. var part2 = (-2.0 * cubed) + (3.0 * squared);
  328. var part3 = (cubed - (2.0 * squared)) + amount;
  329. var part4 = cubed - squared;
  330. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  331. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  332. return new Vector2(x, y);
  333. };
  334. Vector2.Lerp = function (start, end, amount) {
  335. var x = start.x + ((end.x - start.x) * amount);
  336. var y = start.y + ((end.y - start.y) * amount);
  337. return new Vector2(x, y);
  338. };
  339. Vector2.Dot = function (left, right) {
  340. return left.x * right.x + left.y * right.y;
  341. };
  342. Vector2.Normalize = function (vector) {
  343. var newVector = vector.clone();
  344. newVector.normalize();
  345. return newVector;
  346. };
  347. Vector2.Minimize = function (left, right) {
  348. var x = (left.x < right.x) ? left.x : right.x;
  349. var y = (left.y < right.y) ? left.y : right.y;
  350. return new Vector2(x, y);
  351. };
  352. Vector2.Maximize = function (left, right) {
  353. var x = (left.x > right.x) ? left.x : right.x;
  354. var y = (left.y > right.y) ? left.y : right.y;
  355. return new Vector2(x, y);
  356. };
  357. Vector2.Transform = function (vector, transformation) {
  358. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]);
  359. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]);
  360. return new Vector2(x, y);
  361. };
  362. Vector2.Distance = function (value1, value2) {
  363. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  364. };
  365. Vector2.DistanceSquared = function (value1, value2) {
  366. var x = value1.x - value2.x;
  367. var y = value1.y - value2.y;
  368. return (x * x) + (y * y);
  369. };
  370. return Vector2;
  371. })();
  372. BABYLON.Vector2 = Vector2;
  373. var Vector3 = (function () {
  374. function Vector3(x, y, z) {
  375. this.x = x;
  376. this.y = y;
  377. this.z = z;
  378. }
  379. Vector3.prototype.toString = function () {
  380. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  381. };
  382. Vector3.prototype.asArray = function () {
  383. var result = [];
  384. this.toArray(result, 0);
  385. return result;
  386. };
  387. Vector3.prototype.toArray = function (array, index) {
  388. if (index === undefined) {
  389. index = 0;
  390. }
  391. array[index] = this.x;
  392. array[index + 1] = this.y;
  393. array[index + 2] = this.z;
  394. };
  395. Vector3.prototype.addInPlace = function (otherVector) {
  396. this.x += otherVector.x;
  397. this.y += otherVector.y;
  398. this.z += otherVector.z;
  399. };
  400. Vector3.prototype.add = function (otherVector) {
  401. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  402. };
  403. Vector3.prototype.addToRef = function (otherVector, result) {
  404. result.x = this.x + otherVector.x;
  405. result.y = this.y + otherVector.y;
  406. result.z = this.z + otherVector.z;
  407. };
  408. Vector3.prototype.subtractInPlace = function (otherVector) {
  409. this.x -= otherVector.x;
  410. this.y -= otherVector.y;
  411. this.z -= otherVector.z;
  412. };
  413. Vector3.prototype.subtract = function (otherVector) {
  414. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  415. };
  416. Vector3.prototype.subtractToRef = function (otherVector, result) {
  417. result.x = this.x - otherVector.x;
  418. result.y = this.y - otherVector.y;
  419. result.z = this.z - otherVector.z;
  420. };
  421. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  422. return new Vector3(this.x - x, this.y - y, this.z - z);
  423. };
  424. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  425. result.x = this.x - x;
  426. result.y = this.y - y;
  427. result.z = this.z - z;
  428. };
  429. Vector3.prototype.negate = function () {
  430. return new Vector3(-this.x, -this.y, -this.z);
  431. };
  432. Vector3.prototype.scaleInPlace = function (scale) {
  433. this.x *= scale;
  434. this.y *= scale;
  435. this.z *= scale;
  436. return this;
  437. };
  438. Vector3.prototype.scale = function (scale) {
  439. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  440. };
  441. Vector3.prototype.scaleToRef = function (scale, result) {
  442. result.x = this.x * scale;
  443. result.y = this.y * scale;
  444. result.z = this.z * scale;
  445. };
  446. Vector3.prototype.equals = function (otherVector) {
  447. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  448. };
  449. Vector3.prototype.equalsWithEpsilon = function (otherVector) {
  450. 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;
  451. };
  452. Vector3.prototype.equalsToFloats = function (x, y, z) {
  453. return this.x === x && this.y === y && this.z === z;
  454. };
  455. Vector3.prototype.multiplyInPlace = function (otherVector) {
  456. this.x *= otherVector.x;
  457. this.y *= otherVector.y;
  458. this.z *= otherVector.z;
  459. };
  460. Vector3.prototype.multiply = function (otherVector) {
  461. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  462. };
  463. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  464. result.x = this.x * otherVector.x;
  465. result.y = this.y * otherVector.y;
  466. result.z = this.z * otherVector.z;
  467. };
  468. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  469. return new Vector3(this.x * x, this.y * y, this.z * z);
  470. };
  471. Vector3.prototype.divide = function (otherVector) {
  472. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  473. };
  474. Vector3.prototype.divideToRef = function (otherVector, result) {
  475. result.x = this.x / otherVector.x;
  476. result.y = this.y / otherVector.y;
  477. result.z = this.z / otherVector.z;
  478. };
  479. Vector3.prototype.MinimizeInPlace = function (other) {
  480. if (other.x < this.x)
  481. this.x = other.x;
  482. if (other.y < this.y)
  483. this.y = other.y;
  484. if (other.z < this.z)
  485. this.z = other.z;
  486. };
  487. Vector3.prototype.MaximizeInPlace = function (other) {
  488. if (other.x > this.x)
  489. this.x = other.x;
  490. if (other.y > this.y)
  491. this.y = other.y;
  492. if (other.z > this.z)
  493. this.z = other.z;
  494. };
  495. Vector3.prototype.length = function () {
  496. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  497. };
  498. Vector3.prototype.lengthSquared = function () {
  499. return (this.x * this.x + this.y * this.y + this.z * this.z);
  500. };
  501. Vector3.prototype.normalize = function () {
  502. var len = this.length();
  503. if (len === 0)
  504. return this;
  505. var num = 1.0 / len;
  506. this.x *= num;
  507. this.y *= num;
  508. this.z *= num;
  509. return this;
  510. };
  511. Vector3.prototype.clone = function () {
  512. return new Vector3(this.x, this.y, this.z);
  513. };
  514. Vector3.prototype.copyFrom = function (source) {
  515. this.x = source.x;
  516. this.y = source.y;
  517. this.z = source.z;
  518. };
  519. Vector3.prototype.copyFromFloats = function (x, y, z) {
  520. this.x = x;
  521. this.y = y;
  522. this.z = z;
  523. };
  524. Vector3.FromArray = function (array, offset) {
  525. if (!offset) {
  526. offset = 0;
  527. }
  528. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  529. };
  530. Vector3.FromArrayToRef = function (array, offset, result) {
  531. result.x = array[offset];
  532. result.y = array[offset + 1];
  533. result.z = array[offset + 2];
  534. };
  535. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  536. result.x = array[offset];
  537. result.y = array[offset + 1];
  538. result.z = array[offset + 2];
  539. };
  540. Vector3.FromFloatsToRef = function (x, y, z, result) {
  541. result.x = x;
  542. result.y = y;
  543. result.z = z;
  544. };
  545. Vector3.Zero = function () {
  546. return new Vector3(0, 0, 0);
  547. };
  548. Vector3.Up = function () {
  549. return new Vector3(0, 1.0, 0);
  550. };
  551. Vector3.TransformCoordinates = function (vector, transformation) {
  552. var result = Vector3.Zero();
  553. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  554. return result;
  555. };
  556. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  557. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  558. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  559. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  560. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  561. result.x = x / w;
  562. result.y = y / w;
  563. result.z = z / w;
  564. };
  565. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  566. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  567. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  568. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  569. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  570. result.x = rx / rw;
  571. result.y = ry / rw;
  572. result.z = rz / rw;
  573. };
  574. Vector3.TransformNormal = function (vector, transformation) {
  575. var result = Vector3.Zero();
  576. Vector3.TransformNormalToRef(vector, transformation, result);
  577. return result;
  578. };
  579. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  580. result.x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  581. result.y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  582. result.z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  583. };
  584. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  585. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  586. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  587. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  588. };
  589. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  590. var squared = amount * amount;
  591. var cubed = amount * squared;
  592. 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));
  593. 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));
  594. 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));
  595. return new Vector3(x, y, z);
  596. };
  597. Vector3.Clamp = function (value, min, max) {
  598. var x = value.x;
  599. x = (x > max.x) ? max.x : x;
  600. x = (x < min.x) ? min.x : x;
  601. var y = value.y;
  602. y = (y > max.y) ? max.y : y;
  603. y = (y < min.y) ? min.y : y;
  604. var z = value.z;
  605. z = (z > max.z) ? max.z : z;
  606. z = (z < min.z) ? min.z : z;
  607. return new Vector3(x, y, z);
  608. };
  609. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  610. var squared = amount * amount;
  611. var cubed = amount * squared;
  612. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  613. var part2 = (-2.0 * cubed) + (3.0 * squared);
  614. var part3 = (cubed - (2.0 * squared)) + amount;
  615. var part4 = cubed - squared;
  616. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  617. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  618. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  619. return new Vector3(x, y, z);
  620. };
  621. Vector3.Lerp = function (start, end, amount) {
  622. var x = start.x + ((end.x - start.x) * amount);
  623. var y = start.y + ((end.y - start.y) * amount);
  624. var z = start.z + ((end.z - start.z) * amount);
  625. return new Vector3(x, y, z);
  626. };
  627. Vector3.Dot = function (left, right) {
  628. return (left.x * right.x + left.y * right.y + left.z * right.z);
  629. };
  630. Vector3.Cross = function (left, right) {
  631. var result = Vector3.Zero();
  632. Vector3.CrossToRef(left, right, result);
  633. return result;
  634. };
  635. Vector3.CrossToRef = function (left, right, result) {
  636. result.x = left.y * right.z - left.z * right.y;
  637. result.y = left.z * right.x - left.x * right.z;
  638. result.z = left.x * right.y - left.y * right.x;
  639. };
  640. Vector3.Normalize = function (vector) {
  641. var result = Vector3.Zero();
  642. Vector3.NormalizeToRef(vector, result);
  643. return result;
  644. };
  645. Vector3.NormalizeToRef = function (vector, result) {
  646. result.copyFrom(vector);
  647. result.normalize();
  648. };
  649. Vector3.Project = function (vector, world, transform, viewport) {
  650. var cw = viewport.width;
  651. var ch = viewport.height;
  652. var cx = viewport.x;
  653. var cy = viewport.y;
  654. var viewportMatrix = BABYLON.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);
  655. var finalMatrix = world.multiply(transform).multiply(viewportMatrix);
  656. return Vector3.TransformCoordinates(vector, finalMatrix);
  657. };
  658. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  659. var matrix = world.multiply(view).multiply(projection);
  660. matrix.invert();
  661. source.x = source.x / viewportWidth * 2 - 1;
  662. source.y = -(source.y / viewportHeight * 2 - 1);
  663. var vector = BABYLON.Vector3.TransformCoordinates(source, matrix);
  664. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  665. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  666. vector = vector.scale(1.0 / num);
  667. }
  668. return vector;
  669. };
  670. Vector3.Minimize = function (left, right) {
  671. var min = left.clone();
  672. min.MinimizeInPlace(right);
  673. return min;
  674. };
  675. Vector3.Maximize = function (left, right) {
  676. var max = left.clone();
  677. max.MaximizeInPlace(right);
  678. return max;
  679. };
  680. Vector3.Distance = function (value1, value2) {
  681. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  682. };
  683. Vector3.DistanceSquared = function (value1, value2) {
  684. var x = value1.x - value2.x;
  685. var y = value1.y - value2.y;
  686. var z = value1.z - value2.z;
  687. return (x * x) + (y * y) + (z * z);
  688. };
  689. Vector3.Center = function (value1, value2) {
  690. var center = value1.add(value2);
  691. center.scaleInPlace(0.5);
  692. return center;
  693. };
  694. return Vector3;
  695. })();
  696. BABYLON.Vector3 = Vector3;
  697. var Quaternion = (function () {
  698. function Quaternion(x, y, z, w) {
  699. if (typeof x === "undefined") { x = 0; }
  700. if (typeof y === "undefined") { y = 0; }
  701. if (typeof z === "undefined") { z = 0; }
  702. if (typeof w === "undefined") { w = 1; }
  703. this.x = x;
  704. this.y = y;
  705. this.z = z;
  706. this.w = w;
  707. }
  708. Quaternion.prototype.toString = function () {
  709. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  710. };
  711. Quaternion.prototype.asArray = function () {
  712. return [this.x, this.y, this.z, this.w];
  713. };
  714. Quaternion.prototype.equals = function (otherQuaternion) {
  715. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  716. };
  717. Quaternion.prototype.clone = function () {
  718. return new Quaternion(this.x, this.y, this.z, this.w);
  719. };
  720. Quaternion.prototype.copyFrom = function (other) {
  721. this.x = other.x;
  722. this.y = other.y;
  723. this.z = other.z;
  724. this.w = other.w;
  725. };
  726. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  727. this.x = x;
  728. this.y = y;
  729. this.z = z;
  730. this.w = w;
  731. };
  732. Quaternion.prototype.add = function (other) {
  733. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  734. };
  735. Quaternion.prototype.subtract = function (other) {
  736. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  737. };
  738. Quaternion.prototype.scale = function (value) {
  739. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  740. };
  741. Quaternion.prototype.multiply = function (q1) {
  742. var result = new Quaternion(0, 0, 0, 1.0);
  743. this.multiplyToRef(q1, result);
  744. return result;
  745. };
  746. Quaternion.prototype.multiplyToRef = function (q1, result) {
  747. result.x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  748. result.y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  749. result.z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  750. result.w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  751. };
  752. Quaternion.prototype.length = function () {
  753. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  754. };
  755. Quaternion.prototype.normalize = function () {
  756. var length = 1.0 / this.length();
  757. this.x *= length;
  758. this.y *= length;
  759. this.z *= length;
  760. this.w *= length;
  761. };
  762. Quaternion.prototype.toEulerAngles = function () {
  763. var result = Vector3.Zero();
  764. this.toEulerAnglesToRef(result);
  765. return result;
  766. };
  767. Quaternion.prototype.toEulerAnglesToRef = function (result) {
  768. var qx = this.x;
  769. var qy = this.y;
  770. var qz = this.z;
  771. var qw = this.w;
  772. var sqx = qx * qx;
  773. var sqy = qy * qy;
  774. var sqz = qz * qz;
  775. var yaw = Math.atan2(2.0 * (qy * qw - qx * qz), 1.0 - 2.0 * (sqy + sqz));
  776. var pitch = Math.asin(2.0 * (qx * qy + qz * qw));
  777. var roll = Math.atan2(2.0 * (qx * qw - qy * qz), 1.0 - 2.0 * (sqx + sqz));
  778. var gimbaLockTest = qx * qy + qz * qw;
  779. if (gimbaLockTest > 0.499) {
  780. yaw = 2.0 * Math.atan2(qx, qw);
  781. roll = 0;
  782. } else if (gimbaLockTest < -0.499) {
  783. yaw = -2.0 * Math.atan2(qx, qw);
  784. roll = 0;
  785. }
  786. result.x = pitch;
  787. result.y = yaw;
  788. result.z = roll;
  789. };
  790. Quaternion.prototype.toRotationMatrix = function (result) {
  791. var xx = this.x * this.x;
  792. var yy = this.y * this.y;
  793. var zz = this.z * this.z;
  794. var xy = this.x * this.y;
  795. var zw = this.z * this.w;
  796. var zx = this.z * this.x;
  797. var yw = this.y * this.w;
  798. var yz = this.y * this.z;
  799. var xw = this.x * this.w;
  800. result.m[0] = 1.0 - (2.0 * (yy + zz));
  801. result.m[1] = 2.0 * (xy + zw);
  802. result.m[2] = 2.0 * (zx - yw);
  803. result.m[3] = 0;
  804. result.m[4] = 2.0 * (xy - zw);
  805. result.m[5] = 1.0 - (2.0 * (zz + xx));
  806. result.m[6] = 2.0 * (yz + xw);
  807. result.m[7] = 0;
  808. result.m[8] = 2.0 * (zx + yw);
  809. result.m[9] = 2.0 * (yz - xw);
  810. result.m[10] = 1.0 - (2.0 * (yy + xx));
  811. result.m[11] = 0;
  812. result.m[12] = 0;
  813. result.m[13] = 0;
  814. result.m[14] = 0;
  815. result.m[15] = 1.0;
  816. };
  817. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  818. var data = matrix.m;
  819. var m11 = data[0], m12 = data[4], m13 = data[8];
  820. var m21 = data[1], m22 = data[5], m23 = data[9];
  821. var m31 = data[2], m32 = data[6], m33 = data[10];
  822. var trace = m11 + m22 + m33;
  823. var s;
  824. if (trace > 0) {
  825. s = 0.5 / Math.sqrt(trace + 1.0);
  826. this.w = 0.25 / s;
  827. this.x = (m32 - m23) * s;
  828. this.y = (m13 - m31) * s;
  829. this.z = (m21 - m12) * s;
  830. return;
  831. }
  832. if (m11 > m22 && m11 > m33) {
  833. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  834. this.w = (m32 - m23) / s;
  835. this.x = 0.25 * s;
  836. this.y = (m12 + m21) / s;
  837. this.z = (m13 + m31) / s;
  838. return;
  839. }
  840. if (m22 > m33) {
  841. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  842. this.w = (m13 - m31) / s;
  843. this.x = (m12 + m21) / s;
  844. this.y = 0.25 * s;
  845. this.z = (m23 + m32) / s;
  846. return;
  847. }
  848. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  849. this.w = (m21 - m12) / s;
  850. this.x = (m13 + m31) / s;
  851. this.y = (m23 + m32) / s;
  852. this.z = 0.25 * s;
  853. };
  854. Quaternion.Inverse = function (q) {
  855. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  856. };
  857. Quaternion.RotationAxis = function (axis, angle) {
  858. var result = new Quaternion();
  859. var sin = Math.sin(angle / 2);
  860. result.w = Math.cos(angle / 2);
  861. result.x = axis.x * sin;
  862. result.y = axis.y * sin;
  863. result.z = axis.z * sin;
  864. return result;
  865. };
  866. Quaternion.FromArray = function (array, offset) {
  867. if (!offset) {
  868. offset = 0;
  869. }
  870. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  871. };
  872. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  873. var result = new Quaternion();
  874. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  875. return result;
  876. };
  877. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  878. var halfRoll = roll * 0.5;
  879. var halfPitch = pitch * 0.5;
  880. var halfYaw = yaw * 0.5;
  881. var sinRoll = Math.sin(halfRoll);
  882. var cosRoll = Math.cos(halfRoll);
  883. var sinPitch = Math.sin(halfPitch);
  884. var cosPitch = Math.cos(halfPitch);
  885. var sinYaw = Math.sin(halfYaw);
  886. var cosYaw = Math.cos(halfYaw);
  887. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  888. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  889. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  890. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  891. };
  892. Quaternion.Slerp = function (left, right, amount) {
  893. var num2;
  894. var num3;
  895. var num = amount;
  896. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  897. var flag = false;
  898. if (num4 < 0) {
  899. flag = true;
  900. num4 = -num4;
  901. }
  902. if (num4 > 0.999999) {
  903. num3 = 1 - num;
  904. num2 = flag ? -num : num;
  905. } else {
  906. var num5 = Math.acos(num4);
  907. var num6 = (1.0 / Math.sin(num5));
  908. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  909. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  910. }
  911. 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));
  912. };
  913. return Quaternion;
  914. })();
  915. BABYLON.Quaternion = Quaternion;
  916. var Matrix = (function () {
  917. function Matrix() {
  918. this.m = new Float32Array(16);
  919. }
  920. Matrix.prototype.isIdentity = function () {
  921. if (this.m[0] != 1.0 || this.m[5] != 1.0 || this.m[10] != 1.0 || this.m[15] != 1.0)
  922. return false;
  923. 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)
  924. return false;
  925. return true;
  926. };
  927. Matrix.prototype.determinant = function () {
  928. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  929. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  930. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  931. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  932. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  933. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  934. 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))));
  935. };
  936. Matrix.prototype.toArray = function () {
  937. return this.m;
  938. };
  939. Matrix.prototype.asArray = function () {
  940. return this.toArray();
  941. };
  942. Matrix.prototype.invert = function () {
  943. this.invertToRef(this);
  944. };
  945. Matrix.prototype.invertToRef = function (other) {
  946. var l1 = this.m[0];
  947. var l2 = this.m[1];
  948. var l3 = this.m[2];
  949. var l4 = this.m[3];
  950. var l5 = this.m[4];
  951. var l6 = this.m[5];
  952. var l7 = this.m[6];
  953. var l8 = this.m[7];
  954. var l9 = this.m[8];
  955. var l10 = this.m[9];
  956. var l11 = this.m[10];
  957. var l12 = this.m[11];
  958. var l13 = this.m[12];
  959. var l14 = this.m[13];
  960. var l15 = this.m[14];
  961. var l16 = this.m[15];
  962. var l17 = (l11 * l16) - (l12 * l15);
  963. var l18 = (l10 * l16) - (l12 * l14);
  964. var l19 = (l10 * l15) - (l11 * l14);
  965. var l20 = (l9 * l16) - (l12 * l13);
  966. var l21 = (l9 * l15) - (l11 * l13);
  967. var l22 = (l9 * l14) - (l10 * l13);
  968. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  969. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  970. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  971. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  972. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  973. var l28 = (l7 * l16) - (l8 * l15);
  974. var l29 = (l6 * l16) - (l8 * l14);
  975. var l30 = (l6 * l15) - (l7 * l14);
  976. var l31 = (l5 * l16) - (l8 * l13);
  977. var l32 = (l5 * l15) - (l7 * l13);
  978. var l33 = (l5 * l14) - (l6 * l13);
  979. var l34 = (l7 * l12) - (l8 * l11);
  980. var l35 = (l6 * l12) - (l8 * l10);
  981. var l36 = (l6 * l11) - (l7 * l10);
  982. var l37 = (l5 * l12) - (l8 * l9);
  983. var l38 = (l5 * l11) - (l7 * l9);
  984. var l39 = (l5 * l10) - (l6 * l9);
  985. other.m[0] = l23 * l27;
  986. other.m[4] = l24 * l27;
  987. other.m[8] = l25 * l27;
  988. other.m[12] = l26 * l27;
  989. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  990. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  991. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  992. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  993. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  994. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  995. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  996. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  997. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  998. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  999. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  1000. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  1001. };
  1002. Matrix.prototype.setTranslation = function (vector3) {
  1003. this.m[12] = vector3.x;
  1004. this.m[13] = vector3.y;
  1005. this.m[14] = vector3.z;
  1006. };
  1007. Matrix.prototype.multiply = function (other) {
  1008. var result = new Matrix();
  1009. this.multiplyToRef(other, result);
  1010. return result;
  1011. };
  1012. Matrix.prototype.copyFrom = function (other) {
  1013. for (var index = 0; index < 16; index++) {
  1014. this.m[index] = other.m[index];
  1015. }
  1016. };
  1017. Matrix.prototype.copyToArray = function (array, offset) {
  1018. if (typeof offset === "undefined") { offset = 0; }
  1019. for (var index = 0; index < 16; index++) {
  1020. array[offset + index] = this.m[index];
  1021. }
  1022. };
  1023. Matrix.prototype.multiplyToRef = function (other, result) {
  1024. this.multiplyToArray(other, result.m, 0);
  1025. };
  1026. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1027. var tm0 = this.m[0];
  1028. var tm1 = this.m[1];
  1029. var tm2 = this.m[2];
  1030. var tm3 = this.m[3];
  1031. var tm4 = this.m[4];
  1032. var tm5 = this.m[5];
  1033. var tm6 = this.m[6];
  1034. var tm7 = this.m[7];
  1035. var tm8 = this.m[8];
  1036. var tm9 = this.m[9];
  1037. var tm10 = this.m[10];
  1038. var tm11 = this.m[11];
  1039. var tm12 = this.m[12];
  1040. var tm13 = this.m[13];
  1041. var tm14 = this.m[14];
  1042. var tm15 = this.m[15];
  1043. var om0 = other.m[0];
  1044. var om1 = other.m[1];
  1045. var om2 = other.m[2];
  1046. var om3 = other.m[3];
  1047. var om4 = other.m[4];
  1048. var om5 = other.m[5];
  1049. var om6 = other.m[6];
  1050. var om7 = other.m[7];
  1051. var om8 = other.m[8];
  1052. var om9 = other.m[9];
  1053. var om10 = other.m[10];
  1054. var om11 = other.m[11];
  1055. var om12 = other.m[12];
  1056. var om13 = other.m[13];
  1057. var om14 = other.m[14];
  1058. var om15 = other.m[15];
  1059. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1060. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1061. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1062. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1063. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1064. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1065. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1066. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1067. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1068. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1069. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1070. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1071. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1072. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1073. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1074. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1075. };
  1076. Matrix.prototype.equals = function (value) {
  1077. 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]);
  1078. };
  1079. Matrix.prototype.clone = function () {
  1080. 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]);
  1081. };
  1082. Matrix.FromArray = function (array, offset) {
  1083. var result = new Matrix();
  1084. if (!offset) {
  1085. offset = 0;
  1086. }
  1087. Matrix.FromArrayToRef(array, offset, result);
  1088. return result;
  1089. };
  1090. Matrix.FromArrayToRef = function (array, offset, result) {
  1091. for (var index = 0; index < 16; index++) {
  1092. result.m[index] = array[index + offset];
  1093. }
  1094. };
  1095. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  1096. result.m[0] = initialM11;
  1097. result.m[1] = initialM12;
  1098. result.m[2] = initialM13;
  1099. result.m[3] = initialM14;
  1100. result.m[4] = initialM21;
  1101. result.m[5] = initialM22;
  1102. result.m[6] = initialM23;
  1103. result.m[7] = initialM24;
  1104. result.m[8] = initialM31;
  1105. result.m[9] = initialM32;
  1106. result.m[10] = initialM33;
  1107. result.m[11] = initialM34;
  1108. result.m[12] = initialM41;
  1109. result.m[13] = initialM42;
  1110. result.m[14] = initialM43;
  1111. result.m[15] = initialM44;
  1112. };
  1113. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  1114. var result = new Matrix();
  1115. result.m[0] = initialM11;
  1116. result.m[1] = initialM12;
  1117. result.m[2] = initialM13;
  1118. result.m[3] = initialM14;
  1119. result.m[4] = initialM21;
  1120. result.m[5] = initialM22;
  1121. result.m[6] = initialM23;
  1122. result.m[7] = initialM24;
  1123. result.m[8] = initialM31;
  1124. result.m[9] = initialM32;
  1125. result.m[10] = initialM33;
  1126. result.m[11] = initialM34;
  1127. result.m[12] = initialM41;
  1128. result.m[13] = initialM42;
  1129. result.m[14] = initialM43;
  1130. result.m[15] = initialM44;
  1131. return result;
  1132. };
  1133. Matrix.Identity = function () {
  1134. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  1135. };
  1136. Matrix.IdentityToRef = function (result) {
  1137. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  1138. };
  1139. Matrix.Zero = function () {
  1140. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  1141. };
  1142. Matrix.RotationX = function (angle) {
  1143. var result = new Matrix();
  1144. Matrix.RotationXToRef(angle, result);
  1145. return result;
  1146. };
  1147. Matrix.RotationXToRef = function (angle, result) {
  1148. var s = Math.sin(angle);
  1149. var c = Math.cos(angle);
  1150. result.m[0] = 1.0;
  1151. result.m[15] = 1.0;
  1152. result.m[5] = c;
  1153. result.m[10] = c;
  1154. result.m[9] = -s;
  1155. result.m[6] = s;
  1156. result.m[1] = 0;
  1157. result.m[2] = 0;
  1158. result.m[3] = 0;
  1159. result.m[4] = 0;
  1160. result.m[7] = 0;
  1161. result.m[8] = 0;
  1162. result.m[11] = 0;
  1163. result.m[12] = 0;
  1164. result.m[13] = 0;
  1165. result.m[14] = 0;
  1166. };
  1167. Matrix.RotationY = function (angle) {
  1168. var result = new Matrix();
  1169. Matrix.RotationYToRef(angle, result);
  1170. return result;
  1171. };
  1172. Matrix.RotationYToRef = function (angle, result) {
  1173. var s = Math.sin(angle);
  1174. var c = Math.cos(angle);
  1175. result.m[5] = 1.0;
  1176. result.m[15] = 1.0;
  1177. result.m[0] = c;
  1178. result.m[2] = -s;
  1179. result.m[8] = s;
  1180. result.m[10] = c;
  1181. result.m[1] = 0;
  1182. result.m[3] = 0;
  1183. result.m[4] = 0;
  1184. result.m[6] = 0;
  1185. result.m[7] = 0;
  1186. result.m[9] = 0;
  1187. result.m[11] = 0;
  1188. result.m[12] = 0;
  1189. result.m[13] = 0;
  1190. result.m[14] = 0;
  1191. };
  1192. Matrix.RotationZ = function (angle) {
  1193. var result = new Matrix();
  1194. Matrix.RotationZToRef(angle, result);
  1195. return result;
  1196. };
  1197. Matrix.RotationZToRef = function (angle, result) {
  1198. var s = Math.sin(angle);
  1199. var c = Math.cos(angle);
  1200. result.m[10] = 1.0;
  1201. result.m[15] = 1.0;
  1202. result.m[0] = c;
  1203. result.m[1] = s;
  1204. result.m[4] = -s;
  1205. result.m[5] = c;
  1206. result.m[2] = 0;
  1207. result.m[3] = 0;
  1208. result.m[6] = 0;
  1209. result.m[7] = 0;
  1210. result.m[8] = 0;
  1211. result.m[9] = 0;
  1212. result.m[11] = 0;
  1213. result.m[12] = 0;
  1214. result.m[13] = 0;
  1215. result.m[14] = 0;
  1216. };
  1217. Matrix.RotationAxis = function (axis, angle) {
  1218. var s = Math.sin(-angle);
  1219. var c = Math.cos(-angle);
  1220. var c1 = 1 - c;
  1221. axis.normalize();
  1222. var result = Matrix.Zero();
  1223. result.m[0] = (axis.x * axis.x) * c1 + c;
  1224. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  1225. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  1226. result.m[3] = 0.0;
  1227. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  1228. result.m[5] = (axis.y * axis.y) * c1 + c;
  1229. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  1230. result.m[7] = 0.0;
  1231. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  1232. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  1233. result.m[10] = (axis.z * axis.z) * c1 + c;
  1234. result.m[11] = 0.0;
  1235. result.m[15] = 1.0;
  1236. return result;
  1237. };
  1238. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1239. var result = new Matrix();
  1240. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1241. return result;
  1242. };
  1243. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1244. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  1245. this._tempQuaternion.toRotationMatrix(result);
  1246. };
  1247. Matrix.Scaling = function (x, y, z) {
  1248. var result = Matrix.Zero();
  1249. Matrix.ScalingToRef(x, y, z, result);
  1250. return result;
  1251. };
  1252. Matrix.ScalingToRef = function (x, y, z, result) {
  1253. result.m[0] = x;
  1254. result.m[1] = 0;
  1255. result.m[2] = 0;
  1256. result.m[3] = 0;
  1257. result.m[4] = 0;
  1258. result.m[5] = y;
  1259. result.m[6] = 0;
  1260. result.m[7] = 0;
  1261. result.m[8] = 0;
  1262. result.m[9] = 0;
  1263. result.m[10] = z;
  1264. result.m[11] = 0;
  1265. result.m[12] = 0;
  1266. result.m[13] = 0;
  1267. result.m[14] = 0;
  1268. result.m[15] = 1.0;
  1269. };
  1270. Matrix.Translation = function (x, y, z) {
  1271. var result = Matrix.Identity();
  1272. Matrix.TranslationToRef(x, y, z, result);
  1273. return result;
  1274. };
  1275. Matrix.TranslationToRef = function (x, y, z, result) {
  1276. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  1277. };
  1278. Matrix.LookAtLH = function (eye, target, up) {
  1279. var result = Matrix.Zero();
  1280. Matrix.LookAtLHToRef(eye, target, up, result);
  1281. return result;
  1282. };
  1283. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  1284. target.subtractToRef(eye, this._zAxis);
  1285. this._zAxis.normalize();
  1286. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  1287. this._xAxis.normalize();
  1288. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  1289. this._yAxis.normalize();
  1290. var ex = -Vector3.Dot(this._xAxis, eye);
  1291. var ey = -Vector3.Dot(this._yAxis, eye);
  1292. var ez = -Vector3.Dot(this._zAxis, eye);
  1293. 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);
  1294. };
  1295. Matrix.OrthoLH = function (width, height, znear, zfar) {
  1296. var hw = 2.0 / width;
  1297. var hh = 2.0 / height;
  1298. var id = 1.0 / (zfar - znear);
  1299. var nid = znear / (znear - zfar);
  1300. return Matrix.FromValues(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1);
  1301. };
  1302. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  1303. var matrix = Matrix.Zero();
  1304. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  1305. return matrix;
  1306. };
  1307. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  1308. result.m[0] = 2.0 / (right - left);
  1309. result.m[1] = result.m[2] = result.m[3] = 0;
  1310. result.m[5] = 2.0 / (top - bottom);
  1311. result.m[4] = result.m[6] = result.m[7] = 0;
  1312. result.m[10] = -1.0 / (znear - zfar);
  1313. result.m[8] = result.m[9] = result.m[11] = 0;
  1314. result.m[12] = (left + right) / (left - right);
  1315. result.m[13] = (top + bottom) / (bottom - top);
  1316. result.m[14] = znear / (znear - zfar);
  1317. result.m[15] = 1.0;
  1318. };
  1319. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  1320. var matrix = Matrix.Zero();
  1321. matrix.m[0] = (2.0 * znear) / width;
  1322. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  1323. matrix.m[5] = (2.0 * znear) / height;
  1324. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  1325. matrix.m[10] = -zfar / (znear - zfar);
  1326. matrix.m[8] = matrix.m[9] = 0.0;
  1327. matrix.m[11] = 1.0;
  1328. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  1329. matrix.m[14] = (znear * zfar) / (znear - zfar);
  1330. return matrix;
  1331. };
  1332. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  1333. var matrix = Matrix.Zero();
  1334. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  1335. return matrix;
  1336. };
  1337. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result) {
  1338. var tan = 1.0 / (Math.tan(fov * 0.5));
  1339. result.m[0] = tan / aspect;
  1340. result.m[1] = result.m[2] = result.m[3] = 0.0;
  1341. result.m[5] = tan;
  1342. result.m[4] = result.m[6] = result.m[7] = 0.0;
  1343. result.m[8] = result.m[9] = 0.0;
  1344. result.m[10] = -zfar / (znear - zfar);
  1345. result.m[11] = 1.0;
  1346. result.m[12] = result.m[13] = result.m[15] = 0.0;
  1347. result.m[14] = (znear * zfar) / (znear - zfar);
  1348. };
  1349. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  1350. var cw = viewport.width;
  1351. var ch = viewport.height;
  1352. var cx = viewport.x;
  1353. var cy = viewport.y;
  1354. 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);
  1355. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  1356. };
  1357. Matrix.Transpose = function (matrix) {
  1358. var result = new Matrix();
  1359. result.m[0] = matrix.m[0];
  1360. result.m[1] = matrix.m[4];
  1361. result.m[2] = matrix.m[8];
  1362. result.m[3] = matrix.m[12];
  1363. result.m[4] = matrix.m[1];
  1364. result.m[5] = matrix.m[5];
  1365. result.m[6] = matrix.m[9];
  1366. result.m[7] = matrix.m[13];
  1367. result.m[8] = matrix.m[2];
  1368. result.m[9] = matrix.m[6];
  1369. result.m[10] = matrix.m[10];
  1370. result.m[11] = matrix.m[14];
  1371. result.m[12] = matrix.m[3];
  1372. result.m[13] = matrix.m[7];
  1373. result.m[14] = matrix.m[11];
  1374. result.m[15] = matrix.m[15];
  1375. return result;
  1376. };
  1377. Matrix.Reflection = function (plane) {
  1378. var matrix = new Matrix();
  1379. Matrix.ReflectionToRef(plane, matrix);
  1380. return matrix;
  1381. };
  1382. Matrix.ReflectionToRef = function (plane, result) {
  1383. plane.normalize();
  1384. var x = plane.normal.x;
  1385. var y = plane.normal.y;
  1386. var z = plane.normal.z;
  1387. var temp = -2 * x;
  1388. var temp2 = -2 * y;
  1389. var temp3 = -2 * z;
  1390. result.m[0] = (temp * x) + 1;
  1391. result.m[1] = temp2 * x;
  1392. result.m[2] = temp3 * x;
  1393. result.m[3] = 0.0;
  1394. result.m[4] = temp * y;
  1395. result.m[5] = (temp2 * y) + 1;
  1396. result.m[6] = temp3 * y;
  1397. result.m[7] = 0.0;
  1398. result.m[8] = temp * z;
  1399. result.m[9] = temp2 * z;
  1400. result.m[10] = (temp3 * z) + 1;
  1401. result.m[11] = 0.0;
  1402. result.m[12] = temp * plane.d;
  1403. result.m[13] = temp2 * plane.d;
  1404. result.m[14] = temp3 * plane.d;
  1405. result.m[15] = 1.0;
  1406. };
  1407. Matrix._tempQuaternion = new Quaternion();
  1408. Matrix._xAxis = Vector3.Zero();
  1409. Matrix._yAxis = Vector3.Zero();
  1410. Matrix._zAxis = Vector3.Zero();
  1411. return Matrix;
  1412. })();
  1413. BABYLON.Matrix = Matrix;
  1414. var Plane = (function () {
  1415. function Plane(a, b, c, d) {
  1416. this.normal = new Vector3(a, b, c);
  1417. this.d = d;
  1418. }
  1419. Plane.prototype.asArray = function () {
  1420. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  1421. };
  1422. Plane.prototype.clone = function () {
  1423. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  1424. };
  1425. Plane.prototype.normalize = function () {
  1426. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  1427. var magnitude = 0;
  1428. if (norm != 0) {
  1429. magnitude = 1.0 / norm;
  1430. }
  1431. this.normal.x *= magnitude;
  1432. this.normal.y *= magnitude;
  1433. this.normal.z *= magnitude;
  1434. this.d *= magnitude;
  1435. };
  1436. Plane.prototype.transform = function (transformation) {
  1437. var transposedMatrix = BABYLON.Matrix.Transpose(transformation);
  1438. var x = this.normal.x;
  1439. var y = this.normal.y;
  1440. var z = this.normal.z;
  1441. var d = this.d;
  1442. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  1443. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  1444. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  1445. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  1446. return new BABYLON.Plane(normalX, normalY, normalZ, finalD);
  1447. };
  1448. Plane.prototype.dotCoordinate = function (point) {
  1449. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  1450. };
  1451. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  1452. var x1 = point2.x - point1.x;
  1453. var y1 = point2.y - point1.y;
  1454. var z1 = point2.z - point1.z;
  1455. var x2 = point3.x - point1.x;
  1456. var y2 = point3.y - point1.y;
  1457. var z2 = point3.z - point1.z;
  1458. var yz = (y1 * z2) - (z1 * y2);
  1459. var xz = (z1 * x2) - (x1 * z2);
  1460. var xy = (x1 * y2) - (y1 * x2);
  1461. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  1462. var invPyth;
  1463. if (pyth != 0) {
  1464. invPyth = 1.0 / pyth;
  1465. } else {
  1466. invPyth = 0;
  1467. }
  1468. this.normal.x = yz * invPyth;
  1469. this.normal.y = xz * invPyth;
  1470. this.normal.z = xy * invPyth;
  1471. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  1472. };
  1473. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  1474. var dot = Vector3.Dot(this.normal, direction);
  1475. return (dot <= epsilon);
  1476. };
  1477. Plane.prototype.signedDistanceTo = function (point) {
  1478. return Vector3.Dot(point, this.normal) + this.d;
  1479. };
  1480. Plane.FromArray = function (array) {
  1481. return new BABYLON.Plane(array[0], array[1], array[2], array[3]);
  1482. };
  1483. Plane.FromPoints = function (point1, point2, point3) {
  1484. var result = new BABYLON.Plane(0, 0, 0, 0);
  1485. result.copyFromPoints(point1, point2, point3);
  1486. return result;
  1487. };
  1488. Plane.FromPositionAndNormal = function (origin, normal) {
  1489. var result = new BABYLON.Plane(0, 0, 0, 0);
  1490. normal.normalize();
  1491. result.normal = normal;
  1492. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  1493. return result;
  1494. };
  1495. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  1496. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  1497. return Vector3.Dot(point, normal) + d;
  1498. };
  1499. return Plane;
  1500. })();
  1501. BABYLON.Plane = Plane;
  1502. var Viewport = (function () {
  1503. function Viewport(x, y, width, height) {
  1504. this.x = x;
  1505. this.y = y;
  1506. this.width = width;
  1507. this.height = height;
  1508. }
  1509. Viewport.prototype.toGlobal = function (engine) {
  1510. var width = engine.getRenderWidth();
  1511. var height = engine.getRenderHeight();
  1512. return new Viewport(this.x * width, this.y * height, this.width * width, this.height * height);
  1513. };
  1514. return Viewport;
  1515. })();
  1516. BABYLON.Viewport = Viewport;
  1517. var Frustum = (function () {
  1518. function Frustum() {
  1519. }
  1520. Frustum.GetPlanes = function (transform) {
  1521. var frustumPlanes = [];
  1522. for (var index = 0; index < 6; index++) {
  1523. frustumPlanes.push(new Plane(0, 0, 0, 0));
  1524. }
  1525. Frustum.GetPlanesToRef(transform, frustumPlanes);
  1526. return frustumPlanes;
  1527. };
  1528. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  1529. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  1530. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  1531. frustumPlanes[0].normal.z = transform.m[10] + transform.m[10];
  1532. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  1533. frustumPlanes[0].normalize();
  1534. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  1535. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  1536. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  1537. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  1538. frustumPlanes[1].normalize();
  1539. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  1540. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  1541. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  1542. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  1543. frustumPlanes[2].normalize();
  1544. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  1545. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  1546. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  1547. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  1548. frustumPlanes[3].normalize();
  1549. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  1550. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  1551. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  1552. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  1553. frustumPlanes[4].normalize();
  1554. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  1555. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  1556. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  1557. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  1558. frustumPlanes[5].normalize();
  1559. };
  1560. return Frustum;
  1561. })();
  1562. BABYLON.Frustum = Frustum;
  1563. var Ray = (function () {
  1564. function Ray(origin, direction) {
  1565. this.origin = origin;
  1566. this.direction = direction;
  1567. }
  1568. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  1569. var d = 0.0;
  1570. var maxValue = Number.MAX_VALUE;
  1571. if (Math.abs(this.direction.x) < 0.0000001) {
  1572. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  1573. return false;
  1574. }
  1575. } else {
  1576. var inv = 1.0 / this.direction.x;
  1577. var min = (minimum.x - this.origin.x) * inv;
  1578. var max = (maximum.x - this.origin.x) * inv;
  1579. if (min > max) {
  1580. var temp = min;
  1581. min = max;
  1582. max = temp;
  1583. }
  1584. d = Math.max(min, d);
  1585. maxValue = Math.min(max, maxValue);
  1586. if (d > maxValue) {
  1587. return false;
  1588. }
  1589. }
  1590. if (Math.abs(this.direction.y) < 0.0000001) {
  1591. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  1592. return false;
  1593. }
  1594. } else {
  1595. inv = 1.0 / this.direction.y;
  1596. min = (minimum.y - this.origin.y) * inv;
  1597. max = (maximum.y - this.origin.y) * inv;
  1598. if (min > max) {
  1599. temp = min;
  1600. min = max;
  1601. max = temp;
  1602. }
  1603. d = Math.max(min, d);
  1604. maxValue = Math.min(max, maxValue);
  1605. if (d > maxValue) {
  1606. return false;
  1607. }
  1608. }
  1609. if (Math.abs(this.direction.z) < 0.0000001) {
  1610. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  1611. return false;
  1612. }
  1613. } else {
  1614. inv = 1.0 / this.direction.z;
  1615. min = (minimum.z - this.origin.z) * inv;
  1616. max = (maximum.z - this.origin.z) * inv;
  1617. if (min > max) {
  1618. temp = min;
  1619. min = max;
  1620. max = temp;
  1621. }
  1622. d = Math.max(min, d);
  1623. maxValue = Math.min(max, maxValue);
  1624. if (d > maxValue) {
  1625. return false;
  1626. }
  1627. }
  1628. return true;
  1629. };
  1630. Ray.prototype.intersectsBox = function (box) {
  1631. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  1632. };
  1633. Ray.prototype.intersectsSphere = function (sphere) {
  1634. var x = sphere.center.x - this.origin.x;
  1635. var y = sphere.center.y - this.origin.y;
  1636. var z = sphere.center.z - this.origin.z;
  1637. var pyth = (x * x) + (y * y) + (z * z);
  1638. var rr = sphere.radius * sphere.radius;
  1639. if (pyth <= rr) {
  1640. return true;
  1641. }
  1642. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  1643. if (dot < 0.0) {
  1644. return false;
  1645. }
  1646. var temp = pyth - (dot * dot);
  1647. return temp <= rr;
  1648. };
  1649. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  1650. if (!this._edge1) {
  1651. this._edge1 = BABYLON.Vector3.Zero();
  1652. this._edge2 = BABYLON.Vector3.Zero();
  1653. this._pvec = BABYLON.Vector3.Zero();
  1654. this._tvec = BABYLON.Vector3.Zero();
  1655. this._qvec = BABYLON.Vector3.Zero();
  1656. }
  1657. vertex1.subtractToRef(vertex0, this._edge1);
  1658. vertex2.subtractToRef(vertex0, this._edge2);
  1659. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  1660. var det = Vector3.Dot(this._edge1, this._pvec);
  1661. if (det === 0) {
  1662. return null;
  1663. }
  1664. var invdet = 1 / det;
  1665. this.origin.subtractToRef(vertex0, this._tvec);
  1666. var bu = Vector3.Dot(this._tvec, this._pvec) * invdet;
  1667. if (bu < 0 || bu > 1.0) {
  1668. return null;
  1669. }
  1670. Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  1671. var bv = Vector3.Dot(this.direction, this._qvec) * invdet;
  1672. if (bv < 0 || bu + bv > 1.0) {
  1673. return null;
  1674. }
  1675. return new BABYLON.IntersectionInfo(bu, bv, Vector3.Dot(this._edge2, this._qvec) * invdet);
  1676. };
  1677. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  1678. var start = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  1679. var end = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  1680. var direction = end.subtract(start);
  1681. direction.normalize();
  1682. return new Ray(start, direction);
  1683. };
  1684. Ray.Transform = function (ray, matrix) {
  1685. var newOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, matrix);
  1686. var newDirection = BABYLON.Vector3.TransformNormal(ray.direction, matrix);
  1687. return new Ray(newOrigin, newDirection);
  1688. };
  1689. return Ray;
  1690. })();
  1691. BABYLON.Ray = Ray;
  1692. (function (Space) {
  1693. Space[Space["LOCAL"] = 0] = "LOCAL";
  1694. Space[Space["WORLD"] = 1] = "WORLD";
  1695. })(BABYLON.Space || (BABYLON.Space = {}));
  1696. var Space = BABYLON.Space;
  1697. var Axis = (function () {
  1698. function Axis() {
  1699. }
  1700. Axis.X = new BABYLON.Vector3(1, 0, 0);
  1701. Axis.Y = new BABYLON.Vector3(0, 1, 0);
  1702. Axis.Z = new BABYLON.Vector3(0, 0, 1);
  1703. return Axis;
  1704. })();
  1705. BABYLON.Axis = Axis;
  1706. ;
  1707. })(BABYLON || (BABYLON = {}));
  1708. var BABYLON;
  1709. (function (BABYLON) {
  1710. var screenshotCanvas;
  1711. var fpsRange = 60;
  1712. var previousFramesDuration = [];
  1713. var fps = 60;
  1714. var deltaTime = 0;
  1715. var cloneValue = function (source, destinationObject) {
  1716. if (!source)
  1717. return null;
  1718. if (source instanceof BABYLON.Mesh) {
  1719. return null;
  1720. }
  1721. if (source instanceof BABYLON.SubMesh) {
  1722. return source.clone(destinationObject);
  1723. } else if (source.clone) {
  1724. return source.clone();
  1725. }
  1726. return null;
  1727. };
  1728. var Tools = (function () {
  1729. function Tools() {
  1730. }
  1731. Tools.GetFilename = function (path) {
  1732. var index = path.lastIndexOf("/");
  1733. if (index < 0)
  1734. return path;
  1735. return path.substring(index + 1);
  1736. };
  1737. Tools.GetDOMTextContent = function (element) {
  1738. var result = "";
  1739. var child = element.firstChild;
  1740. while (child) {
  1741. if (child.nodeType == 3) {
  1742. result += child.textContent;
  1743. }
  1744. child = child.nextSibling;
  1745. }
  1746. return result;
  1747. };
  1748. Tools.ToDegrees = function (angle) {
  1749. return angle * 180 / Math.PI;
  1750. };
  1751. Tools.ToRadians = function (angle) {
  1752. return angle * Math.PI / 180;
  1753. };
  1754. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount) {
  1755. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  1756. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  1757. for (var index = indexStart; index < indexStart + indexCount; index++) {
  1758. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  1759. minimum = BABYLON.Vector3.Minimize(current, minimum);
  1760. maximum = BABYLON.Vector3.Maximize(current, maximum);
  1761. }
  1762. return {
  1763. minimum: minimum,
  1764. maximum: maximum
  1765. };
  1766. };
  1767. Tools.ExtractMinAndMax = function (positions, start, count) {
  1768. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  1769. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  1770. for (var index = start; index < start + count; index++) {
  1771. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  1772. minimum = BABYLON.Vector3.Minimize(current, minimum);
  1773. maximum = BABYLON.Vector3.Maximize(current, maximum);
  1774. }
  1775. return {
  1776. minimum: minimum,
  1777. maximum: maximum
  1778. };
  1779. };
  1780. Tools.MakeArray = function (obj, allowsNullUndefined) {
  1781. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  1782. return undefined;
  1783. return Array.isArray(obj) ? obj : [obj];
  1784. };
  1785. Tools.GetPointerPrefix = function () {
  1786. var eventPrefix = "pointer";
  1787. if (!navigator.pointerEnabled) {
  1788. eventPrefix = "mouse";
  1789. }
  1790. return eventPrefix;
  1791. };
  1792. Tools.QueueNewFrame = function (func) {
  1793. if (window.requestAnimationFrame)
  1794. window.requestAnimationFrame(func);
  1795. else if (window.msRequestAnimationFrame)
  1796. window.msRequestAnimationFrame(func);
  1797. else if (window.webkitRequestAnimationFrame)
  1798. window.webkitRequestAnimationFrame(func);
  1799. else if (window.mozRequestAnimationFrame)
  1800. window.mozRequestAnimationFrame(func);
  1801. else if (window.oRequestAnimationFrame)
  1802. window.oRequestAnimationFrame(func);
  1803. else {
  1804. window.setTimeout(func, 16);
  1805. }
  1806. };
  1807. Tools.RequestFullscreen = function (element) {
  1808. if (element.requestFullscreen)
  1809. element.requestFullscreen();
  1810. else if (element.msRequestFullscreen)
  1811. element.msRequestFullscreen();
  1812. else if (element.webkitRequestFullscreen)
  1813. element.webkitRequestFullscreen();
  1814. else if (element.mozRequestFullScreen)
  1815. element.mozRequestFullScreen();
  1816. };
  1817. Tools.ExitFullscreen = function () {
  1818. if (document.exitFullscreen) {
  1819. document.exitFullscreen();
  1820. } else if (document.mozCancelFullScreen) {
  1821. document.mozCancelFullScreen();
  1822. } else if (document.webkitCancelFullScreen) {
  1823. document.webkitCancelFullScreen();
  1824. } else if (document.msCancelFullScreen) {
  1825. document.msCancelFullScreen();
  1826. }
  1827. };
  1828. Tools.CleanUrl = function (url) {
  1829. url = url.replace(/#/mg, "%23");
  1830. return url;
  1831. };
  1832. Tools.LoadImage = function (url, onload, onerror, database) {
  1833. url = Tools.CleanUrl(url);
  1834. var img = new Image();
  1835. if (url.substr(0, 5) != "data:")
  1836. img.crossOrigin = 'anonymous';
  1837. img.onload = function () {
  1838. onload(img);
  1839. };
  1840. img.onerror = function (err) {
  1841. onerror(img, err);
  1842. };
  1843. var noIndexedDB = function () {
  1844. img.src = url;
  1845. };
  1846. var loadFromIndexedDB = function () {
  1847. database.loadImageFromDB(url, img);
  1848. };
  1849. if (database && database.enableTexturesOffline && BABYLON.Database.isUASupportingBlobStorage) {
  1850. database.openAsync(loadFromIndexedDB, noIndexedDB);
  1851. } else {
  1852. if (url.indexOf("file:") === -1) {
  1853. noIndexedDB();
  1854. } else {
  1855. try {
  1856. var textureName = url.substring(5);
  1857. var blobURL;
  1858. try {
  1859. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  1860. } catch (ex) {
  1861. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  1862. }
  1863. img.src = blobURL;
  1864. } catch (e) {
  1865. Tools.Log("Error while trying to load texture: " + textureName);
  1866. img.src = null;
  1867. }
  1868. }
  1869. }
  1870. return img;
  1871. };
  1872. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  1873. url = Tools.CleanUrl(url);
  1874. var noIndexedDB = function () {
  1875. var request = new XMLHttpRequest();
  1876. var loadUrl = Tools.BaseUrl + url;
  1877. request.open('GET', loadUrl, true);
  1878. if (useArrayBuffer) {
  1879. request.responseType = "arraybuffer";
  1880. }
  1881. request.onprogress = progressCallBack;
  1882. request.onreadystatechange = function () {
  1883. if (request.readyState == 4) {
  1884. if (request.status == 200 || BABYLON.Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  1885. callback(!useArrayBuffer ? request.responseText : request.response);
  1886. } else {
  1887. if (onError) {
  1888. onError();
  1889. } else {
  1890. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  1891. }
  1892. }
  1893. }
  1894. };
  1895. request.send(null);
  1896. };
  1897. var loadFromIndexedDB = function () {
  1898. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  1899. };
  1900. if (url.indexOf("file:") !== -1) {
  1901. var fileName = url.substring(5);
  1902. BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, true);
  1903. } else {
  1904. if (database && database.enableSceneOffline) {
  1905. database.openAsync(loadFromIndexedDB, noIndexedDB);
  1906. } else {
  1907. noIndexedDB();
  1908. }
  1909. }
  1910. };
  1911. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  1912. var reader = new FileReader();
  1913. reader.onload = function (e) {
  1914. callback(e.target.result);
  1915. };
  1916. reader.onprogress = progressCallback;
  1917. reader.readAsDataURL(fileToLoad);
  1918. };
  1919. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  1920. var reader = new FileReader();
  1921. reader.onload = function (e) {
  1922. callback(e.target.result);
  1923. };
  1924. reader.onprogress = progressCallBack;
  1925. if (!useArrayBuffer) {
  1926. reader.readAsText(fileToLoad);
  1927. } else {
  1928. reader.readAsArrayBuffer(fileToLoad);
  1929. }
  1930. };
  1931. Tools.CheckExtends = function (v, min, max) {
  1932. if (v.x < min.x)
  1933. min.x = v.x;
  1934. if (v.y < min.y)
  1935. min.y = v.y;
  1936. if (v.z < min.z)
  1937. min.z = v.z;
  1938. if (v.x > max.x)
  1939. max.x = v.x;
  1940. if (v.y > max.y)
  1941. max.y = v.y;
  1942. if (v.z > max.z)
  1943. max.z = v.z;
  1944. };
  1945. Tools.WithinEpsilon = function (a, b) {
  1946. var num = a - b;
  1947. return -1.401298E-45 <= num && num <= 1.401298E-45;
  1948. };
  1949. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  1950. for (var prop in source) {
  1951. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  1952. continue;
  1953. }
  1954. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  1955. continue;
  1956. }
  1957. var sourceValue = source[prop];
  1958. var typeOfSourceValue = typeof sourceValue;
  1959. if (typeOfSourceValue == "function") {
  1960. continue;
  1961. }
  1962. if (typeOfSourceValue == "object") {
  1963. if (sourceValue instanceof Array) {
  1964. destination[prop] = [];
  1965. if (sourceValue.length > 0) {
  1966. if (typeof sourceValue[0] == "object") {
  1967. for (var index = 0; index < sourceValue.length; index++) {
  1968. var clonedValue = cloneValue(sourceValue[index], destination);
  1969. if (destination[prop].indexOf(clonedValue) === -1) {
  1970. destination[prop].push(clonedValue);
  1971. }
  1972. }
  1973. } else {
  1974. destination[prop] = sourceValue.slice(0);
  1975. }
  1976. }
  1977. } else {
  1978. destination[prop] = cloneValue(sourceValue, destination);
  1979. }
  1980. } else {
  1981. destination[prop] = sourceValue;
  1982. }
  1983. }
  1984. };
  1985. Tools.IsEmpty = function (obj) {
  1986. for (var i in obj) {
  1987. return false;
  1988. }
  1989. return true;
  1990. };
  1991. Tools.RegisterTopRootEvents = function (events) {
  1992. for (var index = 0; index < events.length; index++) {
  1993. var event = events[index];
  1994. window.addEventListener(event.name, event.handler, false);
  1995. try {
  1996. if (window.parent) {
  1997. window.parent.addEventListener(event.name, event.handler, false);
  1998. }
  1999. } catch (e) {
  2000. }
  2001. }
  2002. };
  2003. Tools.UnregisterTopRootEvents = function (events) {
  2004. for (var index = 0; index < events.length; index++) {
  2005. var event = events[index];
  2006. window.removeEventListener(event.name, event.handler);
  2007. try {
  2008. if (window.parent) {
  2009. window.parent.removeEventListener(event.name, event.handler);
  2010. }
  2011. } catch (e) {
  2012. }
  2013. }
  2014. };
  2015. Tools.GetFps = function () {
  2016. return fps;
  2017. };
  2018. Tools.GetDeltaTime = function () {
  2019. return deltaTime;
  2020. };
  2021. Tools._MeasureFps = function () {
  2022. previousFramesDuration.push((new Date).getTime());
  2023. var length = previousFramesDuration.length;
  2024. if (length >= 2) {
  2025. deltaTime = previousFramesDuration[length - 1] - previousFramesDuration[length - 2];
  2026. }
  2027. if (length >= fpsRange) {
  2028. if (length > fpsRange) {
  2029. previousFramesDuration.splice(0, 1);
  2030. length = previousFramesDuration.length;
  2031. }
  2032. var sum = 0;
  2033. for (var id = 0; id < length - 1; id++) {
  2034. sum += previousFramesDuration[id + 1] - previousFramesDuration[id];
  2035. }
  2036. fps = 1000.0 / (sum / (length - 1));
  2037. }
  2038. };
  2039. Tools.CreateScreenshot = function (engine, camera, size) {
  2040. var width;
  2041. var height;
  2042. var scene = camera.getScene();
  2043. var previousCamera = null;
  2044. if (scene.activeCamera !== camera) {
  2045. previousCamera = scene.activeCamera;
  2046. scene.activeCamera = camera;
  2047. }
  2048. if (size.precision) {
  2049. width = Math.round(engine.getRenderWidth() * size.precision);
  2050. height = Math.round(width / engine.getAspectRatio(camera));
  2051. size = { width: width, height: height };
  2052. } else if (size.width && size.height) {
  2053. width = size.width;
  2054. height = size.height;
  2055. } else if (size.width && !size.height) {
  2056. width = size.width;
  2057. height = Math.round(width / engine.getAspectRatio(camera));
  2058. size = { width: width, height: height };
  2059. } else if (size.height && !size.width) {
  2060. height = size.height;
  2061. width = Math.round(height * engine.getAspectRatio(camera));
  2062. size = { width: width, height: height };
  2063. } else if (!isNaN(size)) {
  2064. height = size;
  2065. width = size;
  2066. } else {
  2067. Tools.Error("Invalid 'size' parameter !");
  2068. return;
  2069. }
  2070. var texture = new BABYLON.RenderTargetTexture("screenShot", size, engine.scenes[0], false, false);
  2071. texture.renderList = engine.scenes[0].meshes;
  2072. texture.onAfterRender = function () {
  2073. var numberOfChannelsByLine = width * 4;
  2074. var halfHeight = height / 2;
  2075. var data = engine.readPixels(0, 0, width, height);
  2076. for (var i = 0; i < halfHeight; i++) {
  2077. for (var j = 0; j < numberOfChannelsByLine; j++) {
  2078. var currentCell = j + i * numberOfChannelsByLine;
  2079. var targetLine = height - i - 1;
  2080. var targetCell = j + targetLine * numberOfChannelsByLine;
  2081. var temp = data[currentCell];
  2082. data[currentCell] = data[targetCell];
  2083. data[targetCell] = temp;
  2084. }
  2085. }
  2086. if (!screenshotCanvas) {
  2087. screenshotCanvas = document.createElement('canvas');
  2088. }
  2089. screenshotCanvas.width = width;
  2090. screenshotCanvas.height = height;
  2091. var context = screenshotCanvas.getContext('2d');
  2092. var imageData = context.createImageData(width, height);
  2093. imageData.data.set(data);
  2094. context.putImageData(imageData, 0, 0);
  2095. var base64Image = screenshotCanvas.toDataURL();
  2096. if (("download" in document.createElement("a"))) {
  2097. var a = window.document.createElement("a");
  2098. a.href = base64Image;
  2099. var date = new Date();
  2100. var stringDate = date.getFullYear() + "/" + date.getMonth() + "/" + date.getDate() + "-" + date.getHours() + ":" + date.getMinutes();
  2101. a.setAttribute("download", "screenshot-" + stringDate + ".png");
  2102. window.document.body.appendChild(a);
  2103. a.addEventListener("click", function () {
  2104. a.parentElement.removeChild(a);
  2105. });
  2106. a.click();
  2107. } else {
  2108. var newWindow = window.open("");
  2109. var img = newWindow.document.createElement("img");
  2110. img.src = base64Image;
  2111. newWindow.document.body.appendChild(img);
  2112. }
  2113. };
  2114. texture.render(true);
  2115. texture.dispose();
  2116. if (previousCamera) {
  2117. scene.activeCamera = previousCamera;
  2118. }
  2119. };
  2120. Tools.ValidateXHRData = function (xhr, dataType) {
  2121. if (typeof dataType === "undefined") { dataType = 7; }
  2122. try {
  2123. if (dataType & 1) {
  2124. if (xhr.responseText && xhr.responseText.length > 0) {
  2125. return true;
  2126. } else if (dataType === 1) {
  2127. return false;
  2128. }
  2129. }
  2130. if (dataType & 2) {
  2131. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  2132. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  2133. return true;
  2134. } else if (dataType === 2) {
  2135. return false;
  2136. }
  2137. }
  2138. if (dataType & 4) {
  2139. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  2140. if (ddsHeader[0] == 68 && ddsHeader[1] == 68 && ddsHeader[2] == 83) {
  2141. return true;
  2142. } else {
  2143. return false;
  2144. }
  2145. }
  2146. } catch (e) {
  2147. }
  2148. return false;
  2149. };
  2150. Object.defineProperty(Tools, "NoneLogLevel", {
  2151. get: function () {
  2152. return Tools._NoneLogLevel;
  2153. },
  2154. enumerable: true,
  2155. configurable: true
  2156. });
  2157. Object.defineProperty(Tools, "MessageLogLevel", {
  2158. get: function () {
  2159. return Tools._MessageLogLevel;
  2160. },
  2161. enumerable: true,
  2162. configurable: true
  2163. });
  2164. Object.defineProperty(Tools, "WarningLogLevel", {
  2165. get: function () {
  2166. return Tools._WarningLogLevel;
  2167. },
  2168. enumerable: true,
  2169. configurable: true
  2170. });
  2171. Object.defineProperty(Tools, "ErrorLogLevel", {
  2172. get: function () {
  2173. return Tools._ErrorLogLevel;
  2174. },
  2175. enumerable: true,
  2176. configurable: true
  2177. });
  2178. Object.defineProperty(Tools, "AllLogLevel", {
  2179. get: function () {
  2180. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  2181. },
  2182. enumerable: true,
  2183. configurable: true
  2184. });
  2185. Tools._FormatMessage = function (message) {
  2186. var padStr = function (i) {
  2187. return (i < 10) ? "0" + i : "" + i;
  2188. };
  2189. var date = new Date();
  2190. return "BJS - [" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  2191. };
  2192. Tools._LogDisabled = function (message) {
  2193. };
  2194. Tools._LogEnabled = function (message) {
  2195. console.log(Tools._FormatMessage(message));
  2196. };
  2197. Tools._WarnDisabled = function (message) {
  2198. };
  2199. Tools._WarnEnabled = function (message) {
  2200. console.warn(Tools._FormatMessage(message));
  2201. };
  2202. Tools._ErrorDisabled = function (message) {
  2203. };
  2204. Tools._ErrorEnabled = function (message) {
  2205. console.error(Tools._FormatMessage(message));
  2206. };
  2207. Object.defineProperty(Tools, "LogLevels", {
  2208. set: function (level) {
  2209. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  2210. Tools.Log = Tools._LogEnabled;
  2211. } else {
  2212. Tools.Log = Tools._LogDisabled;
  2213. }
  2214. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  2215. Tools.Warn = Tools._WarnEnabled;
  2216. } else {
  2217. Tools.Warn = Tools._WarnDisabled;
  2218. }
  2219. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  2220. Tools.Error = Tools._ErrorEnabled;
  2221. } else {
  2222. Tools.Error = Tools._ErrorDisabled;
  2223. }
  2224. },
  2225. enumerable: true,
  2226. configurable: true
  2227. });
  2228. Tools.BaseUrl = "";
  2229. Tools.GetExponantOfTwo = function (value, max) {
  2230. var count = 1;
  2231. do {
  2232. count *= 2;
  2233. } while(count < value);
  2234. if (count > max)
  2235. count = max;
  2236. return count;
  2237. };
  2238. Tools._NoneLogLevel = 0;
  2239. Tools._MessageLogLevel = 1;
  2240. Tools._WarningLogLevel = 2;
  2241. Tools._ErrorLogLevel = 4;
  2242. Tools.Log = Tools._LogEnabled;
  2243. Tools.Warn = Tools._WarnEnabled;
  2244. Tools.Error = Tools._ErrorEnabled;
  2245. return Tools;
  2246. })();
  2247. BABYLON.Tools = Tools;
  2248. })(BABYLON || (BABYLON = {}));
  2249. var BABYLON;
  2250. (function (BABYLON) {
  2251. var _DepthCullingState = (function () {
  2252. function _DepthCullingState() {
  2253. this._isDepthTestDirty = false;
  2254. this._isDepthMaskDirty = false;
  2255. this._isDepthFuncDirty = false;
  2256. this._isCullFaceDirty = false;
  2257. this._isCullDirty = false;
  2258. }
  2259. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  2260. get: function () {
  2261. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty;
  2262. },
  2263. enumerable: true,
  2264. configurable: true
  2265. });
  2266. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  2267. get: function () {
  2268. return this._cullFace;
  2269. },
  2270. set: function (value) {
  2271. if (this._cullFace === value) {
  2272. return;
  2273. }
  2274. this._cullFace = value;
  2275. this._isCullFaceDirty = true;
  2276. },
  2277. enumerable: true,
  2278. configurable: true
  2279. });
  2280. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  2281. get: function () {
  2282. return this._cull;
  2283. },
  2284. set: function (value) {
  2285. if (this._cull === value) {
  2286. return;
  2287. }
  2288. this._cull = value;
  2289. this._isCullDirty = true;
  2290. },
  2291. enumerable: true,
  2292. configurable: true
  2293. });
  2294. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  2295. get: function () {
  2296. return this._depthFunc;
  2297. },
  2298. set: function (value) {
  2299. if (this._depthFunc === value) {
  2300. return;
  2301. }
  2302. this._depthFunc = value;
  2303. this._isDepthFuncDirty = true;
  2304. },
  2305. enumerable: true,
  2306. configurable: true
  2307. });
  2308. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  2309. get: function () {
  2310. return this._depthMask;
  2311. },
  2312. set: function (value) {
  2313. if (this._depthMask === value) {
  2314. return;
  2315. }
  2316. this._depthMask = value;
  2317. this._isDepthMaskDirty = true;
  2318. },
  2319. enumerable: true,
  2320. configurable: true
  2321. });
  2322. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  2323. get: function () {
  2324. return this._depthTest;
  2325. },
  2326. set: function (value) {
  2327. if (this._depthTest === value) {
  2328. return;
  2329. }
  2330. this._depthTest = value;
  2331. this._isDepthTestDirty = true;
  2332. },
  2333. enumerable: true,
  2334. configurable: true
  2335. });
  2336. _DepthCullingState.prototype.reset = function () {
  2337. this._depthMask = true;
  2338. this._depthTest = true;
  2339. this._depthFunc = null;
  2340. this._cull = null;
  2341. this._cullFace = null;
  2342. this._isDepthTestDirty = true;
  2343. this._isDepthMaskDirty = true;
  2344. this._isDepthFuncDirty = false;
  2345. this._isCullFaceDirty = false;
  2346. this._isCullDirty = false;
  2347. };
  2348. _DepthCullingState.prototype.apply = function (gl) {
  2349. if (!this.isDirty) {
  2350. return;
  2351. }
  2352. if (this._isCullDirty) {
  2353. if (this.cull === true) {
  2354. gl.enable(gl.CULL_FACE);
  2355. } else if (this.cull === false) {
  2356. gl.disable(gl.CULL_FACE);
  2357. }
  2358. this._isCullDirty = false;
  2359. }
  2360. if (this._isCullFaceDirty) {
  2361. gl.cullFace(this.cullFace);
  2362. this._isCullFaceDirty = false;
  2363. }
  2364. if (this._isDepthMaskDirty) {
  2365. gl.depthMask(this.depthMask);
  2366. this._isDepthMaskDirty = false;
  2367. }
  2368. if (this._isDepthTestDirty) {
  2369. if (this.depthTest === true) {
  2370. gl.enable(gl.DEPTH_TEST);
  2371. } else if (this.depthTest === false) {
  2372. gl.disable(gl.DEPTH_TEST);
  2373. }
  2374. this._isDepthTestDirty = false;
  2375. }
  2376. if (this._isDepthFuncDirty) {
  2377. gl.depthFunc(this.depthFunc);
  2378. this._isDepthFuncDirty = false;
  2379. }
  2380. };
  2381. return _DepthCullingState;
  2382. })();
  2383. BABYLON._DepthCullingState = _DepthCullingState;
  2384. var _AlphaState = (function () {
  2385. function _AlphaState() {
  2386. this._isAlphaBlendDirty = false;
  2387. this._isBlendFunctionParametersDirty = false;
  2388. this._alphaBlend = false;
  2389. this._blendFunctionParameters = new Array(4);
  2390. }
  2391. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  2392. get: function () {
  2393. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  2394. },
  2395. enumerable: true,
  2396. configurable: true
  2397. });
  2398. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  2399. get: function () {
  2400. return this._alphaBlend;
  2401. },
  2402. set: function (value) {
  2403. if (this._alphaBlend === value) {
  2404. return;
  2405. }
  2406. this._alphaBlend = value;
  2407. this._isAlphaBlendDirty = true;
  2408. },
  2409. enumerable: true,
  2410. configurable: true
  2411. });
  2412. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  2413. if (this._blendFunctionParameters[0] === value0 && this._blendFunctionParameters[1] === value1 && this._blendFunctionParameters[2] === value2 && this._blendFunctionParameters[3] === value3) {
  2414. return;
  2415. }
  2416. this._blendFunctionParameters[0] = value0;
  2417. this._blendFunctionParameters[1] = value1;
  2418. this._blendFunctionParameters[2] = value2;
  2419. this._blendFunctionParameters[3] = value3;
  2420. this._isBlendFunctionParametersDirty = true;
  2421. };
  2422. _AlphaState.prototype.reset = function () {
  2423. this._alphaBlend = false;
  2424. this._blendFunctionParameters[0] = null;
  2425. this._blendFunctionParameters[1] = null;
  2426. this._blendFunctionParameters[2] = null;
  2427. this._blendFunctionParameters[3] = null;
  2428. this._isAlphaBlendDirty = true;
  2429. this._isBlendFunctionParametersDirty = false;
  2430. };
  2431. _AlphaState.prototype.apply = function (gl) {
  2432. if (!this.isDirty) {
  2433. return;
  2434. }
  2435. if (this._isAlphaBlendDirty) {
  2436. if (this._alphaBlend === true) {
  2437. gl.enable(gl.BLEND);
  2438. } else if (this._alphaBlend === false) {
  2439. gl.disable(gl.BLEND);
  2440. }
  2441. this._isAlphaBlendDirty = false;
  2442. }
  2443. if (this._isBlendFunctionParametersDirty) {
  2444. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  2445. this._isBlendFunctionParametersDirty = false;
  2446. }
  2447. };
  2448. return _AlphaState;
  2449. })();
  2450. BABYLON._AlphaState = _AlphaState;
  2451. var compileShader = function (gl, source, type, defines) {
  2452. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  2453. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  2454. gl.compileShader(shader);
  2455. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  2456. throw new Error(gl.getShaderInfoLog(shader));
  2457. }
  2458. return shader;
  2459. };
  2460. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  2461. var magFilter = gl.NEAREST;
  2462. var minFilter = gl.NEAREST;
  2463. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  2464. magFilter = gl.LINEAR;
  2465. if (generateMipMaps) {
  2466. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  2467. } else {
  2468. minFilter = gl.LINEAR;
  2469. }
  2470. } else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  2471. magFilter = gl.LINEAR;
  2472. if (generateMipMaps) {
  2473. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  2474. } else {
  2475. minFilter = gl.LINEAR;
  2476. }
  2477. } else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  2478. magFilter = gl.NEAREST;
  2479. if (generateMipMaps) {
  2480. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  2481. } else {
  2482. minFilter = gl.NEAREST;
  2483. }
  2484. }
  2485. return {
  2486. min: minFilter,
  2487. mag: magFilter
  2488. };
  2489. };
  2490. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  2491. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  2492. var engine = scene.getEngine();
  2493. var potWidth = BABYLON.Tools.GetExponantOfTwo(width, engine.getCaps().maxTextureSize);
  2494. var potHeight = BABYLON.Tools.GetExponantOfTwo(height, engine.getCaps().maxTextureSize);
  2495. gl.bindTexture(gl.TEXTURE_2D, texture);
  2496. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  2497. processFunction(potWidth, potHeight);
  2498. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  2499. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  2500. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  2501. if (!noMipmap && !isCompressed) {
  2502. gl.generateMipmap(gl.TEXTURE_2D);
  2503. }
  2504. gl.bindTexture(gl.TEXTURE_2D, null);
  2505. engine._activeTexturesCache = [];
  2506. texture._baseWidth = width;
  2507. texture._baseHeight = height;
  2508. texture._width = potWidth;
  2509. texture._height = potHeight;
  2510. texture.isReady = true;
  2511. scene._removePendingData(texture);
  2512. };
  2513. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  2514. var img;
  2515. var onload = function () {
  2516. loadedImages[index] = img;
  2517. loadedImages._internalCount++;
  2518. scene._removePendingData(img);
  2519. if (loadedImages._internalCount == 6) {
  2520. onfinish(loadedImages);
  2521. }
  2522. };
  2523. var onerror = function () {
  2524. scene._removePendingData(img);
  2525. };
  2526. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  2527. scene._addPendingData(img);
  2528. };
  2529. var cascadeLoad = function (rootUrl, scene, onfinish, extensions) {
  2530. var loadedImages = [];
  2531. loadedImages._internalCount = 0;
  2532. for (var index = 0; index < 6; index++) {
  2533. partialLoad(rootUrl + extensions[index], index, loadedImages, scene, onfinish);
  2534. }
  2535. };
  2536. var EngineCapabilities = (function () {
  2537. function EngineCapabilities() {
  2538. }
  2539. return EngineCapabilities;
  2540. })();
  2541. BABYLON.EngineCapabilities = EngineCapabilities;
  2542. var Engine = (function () {
  2543. function Engine(canvas, antialias, options) {
  2544. var _this = this;
  2545. this.isFullscreen = false;
  2546. this.isPointerLock = false;
  2547. this.forceWireframe = false;
  2548. this.cullBackFaces = true;
  2549. this.renderEvenInBackground = true;
  2550. this.scenes = new Array();
  2551. this._windowIsBackground = false;
  2552. this._runningLoop = false;
  2553. this._loadingDivBackgroundColor = "black";
  2554. this._depthCullingState = new _DepthCullingState();
  2555. this._alphaState = new _AlphaState();
  2556. this._loadedTexturesCache = new Array();
  2557. this._activeTexturesCache = new Array();
  2558. this._compiledEffects = {};
  2559. this._renderingCanvas = canvas;
  2560. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  2561. options = options || {};
  2562. options.antialias = antialias;
  2563. try {
  2564. this._gl = canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options);
  2565. } catch (e) {
  2566. throw new Error("WebGL not supported");
  2567. }
  2568. if (!this._gl) {
  2569. throw new Error("WebGL not supported");
  2570. }
  2571. this._onBlur = function () {
  2572. _this._windowIsBackground = true;
  2573. };
  2574. this._onFocus = function () {
  2575. _this._windowIsBackground = false;
  2576. };
  2577. window.addEventListener("blur", this._onBlur);
  2578. window.addEventListener("focus", this._onFocus);
  2579. this._workingCanvas = document.createElement("canvas");
  2580. this._workingContext = this._workingCanvas.getContext("2d");
  2581. this._hardwareScalingLevel = 1.0 / (window.devicePixelRatio || 1.0);
  2582. this.resize();
  2583. this._caps = new EngineCapabilities();
  2584. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  2585. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  2586. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  2587. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  2588. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  2589. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  2590. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  2591. 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');
  2592. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  2593. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  2594. this.setDepthBuffer(true);
  2595. this.setDepthFunctionToLessOrEqual();
  2596. this.setDepthWrite(true);
  2597. this._onFullscreenChange = function () {
  2598. if (document.fullscreen !== undefined) {
  2599. _this.isFullscreen = document.fullscreen;
  2600. } else if (document.mozFullScreen !== undefined) {
  2601. _this.isFullscreen = document.mozFullScreen;
  2602. } else if (document.webkitIsFullScreen !== undefined) {
  2603. _this.isFullscreen = document.webkitIsFullScreen;
  2604. } else if (document.msIsFullScreen !== undefined) {
  2605. _this.isFullscreen = document.msIsFullScreen;
  2606. }
  2607. if (_this.isFullscreen && _this._pointerLockRequested) {
  2608. canvas.requestPointerLock = canvas.requestPointerLock || canvas.msRequestPointerLock || canvas.mozRequestPointerLock || canvas.webkitRequestPointerLock;
  2609. if (canvas.requestPointerLock) {
  2610. canvas.requestPointerLock();
  2611. }
  2612. }
  2613. };
  2614. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  2615. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  2616. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  2617. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  2618. this._onPointerLockChange = function () {
  2619. _this.isPointerLock = (document.mozPointerLockElement === canvas || document.webkitPointerLockElement === canvas || document.msPointerLockElement === canvas || document.pointerLockElement === canvas);
  2620. };
  2621. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  2622. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  2623. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  2624. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  2625. }
  2626. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  2627. get: function () {
  2628. return Engine._ALPHA_DISABLE;
  2629. },
  2630. enumerable: true,
  2631. configurable: true
  2632. });
  2633. Object.defineProperty(Engine, "ALPHA_ADD", {
  2634. get: function () {
  2635. return Engine._ALPHA_ADD;
  2636. },
  2637. enumerable: true,
  2638. configurable: true
  2639. });
  2640. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  2641. get: function () {
  2642. return Engine._ALPHA_COMBINE;
  2643. },
  2644. enumerable: true,
  2645. configurable: true
  2646. });
  2647. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  2648. get: function () {
  2649. return Engine._DELAYLOADSTATE_NONE;
  2650. },
  2651. enumerable: true,
  2652. configurable: true
  2653. });
  2654. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  2655. get: function () {
  2656. return Engine._DELAYLOADSTATE_LOADED;
  2657. },
  2658. enumerable: true,
  2659. configurable: true
  2660. });
  2661. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  2662. get: function () {
  2663. return Engine._DELAYLOADSTATE_LOADING;
  2664. },
  2665. enumerable: true,
  2666. configurable: true
  2667. });
  2668. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  2669. get: function () {
  2670. return Engine._DELAYLOADSTATE_NOTLOADED;
  2671. },
  2672. enumerable: true,
  2673. configurable: true
  2674. });
  2675. Object.defineProperty(Engine, "Version", {
  2676. get: function () {
  2677. return "1.14.0";
  2678. },
  2679. enumerable: true,
  2680. configurable: true
  2681. });
  2682. Engine.prototype.getAspectRatio = function (camera) {
  2683. var viewport = camera.viewport;
  2684. return (this.getRenderWidth() * viewport.width) / (this.getRenderHeight() * viewport.height);
  2685. };
  2686. Engine.prototype.getRenderWidth = function () {
  2687. if (this._currentRenderTarget) {
  2688. return this._currentRenderTarget._width;
  2689. }
  2690. return this._renderingCanvas.width;
  2691. };
  2692. Engine.prototype.getRenderHeight = function () {
  2693. if (this._currentRenderTarget) {
  2694. return this._currentRenderTarget._height;
  2695. }
  2696. return this._renderingCanvas.height;
  2697. };
  2698. Engine.prototype.getRenderingCanvas = function () {
  2699. return this._renderingCanvas;
  2700. };
  2701. Engine.prototype.getRenderingCanvasClientRect = function () {
  2702. return this._renderingCanvas.getBoundingClientRect();
  2703. };
  2704. Engine.prototype.setHardwareScalingLevel = function (level) {
  2705. this._hardwareScalingLevel = level;
  2706. this.resize();
  2707. };
  2708. Engine.prototype.getHardwareScalingLevel = function () {
  2709. return this._hardwareScalingLevel;
  2710. };
  2711. Engine.prototype.getLoadedTexturesCache = function () {
  2712. return this._loadedTexturesCache;
  2713. };
  2714. Engine.prototype.getCaps = function () {
  2715. return this._caps;
  2716. };
  2717. Engine.prototype.setDepthFunctionToGreater = function () {
  2718. this._depthCullingState.depthFunc = this._gl.GREATER;
  2719. };
  2720. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  2721. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  2722. };
  2723. Engine.prototype.setDepthFunctionToLess = function () {
  2724. this._depthCullingState.depthFunc = this._gl.LESS;
  2725. };
  2726. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  2727. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  2728. };
  2729. Engine.prototype.stopRenderLoop = function () {
  2730. this._renderFunction = null;
  2731. this._runningLoop = false;
  2732. };
  2733. Engine.prototype._renderLoop = function () {
  2734. var _this = this;
  2735. var shouldRender = true;
  2736. if (!this.renderEvenInBackground && this._windowIsBackground) {
  2737. shouldRender = false;
  2738. }
  2739. if (shouldRender) {
  2740. this.beginFrame();
  2741. if (this._renderFunction) {
  2742. this._renderFunction();
  2743. }
  2744. this.endFrame();
  2745. }
  2746. if (this._runningLoop) {
  2747. BABYLON.Tools.QueueNewFrame(function () {
  2748. _this._renderLoop();
  2749. });
  2750. }
  2751. };
  2752. Engine.prototype.runRenderLoop = function (renderFunction) {
  2753. var _this = this;
  2754. this._runningLoop = true;
  2755. this._renderFunction = renderFunction;
  2756. BABYLON.Tools.QueueNewFrame(function () {
  2757. _this._renderLoop();
  2758. });
  2759. };
  2760. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  2761. if (this.isFullscreen) {
  2762. BABYLON.Tools.ExitFullscreen();
  2763. } else {
  2764. this._pointerLockRequested = requestPointerLock;
  2765. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  2766. }
  2767. };
  2768. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  2769. this.applyStates();
  2770. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  2771. if (this._depthCullingState.depthMask) {
  2772. this._gl.clearDepth(1.0);
  2773. }
  2774. var mode = 0;
  2775. if (backBuffer)
  2776. mode |= this._gl.COLOR_BUFFER_BIT;
  2777. if (depthStencil && this._depthCullingState.depthMask)
  2778. mode |= this._gl.DEPTH_BUFFER_BIT;
  2779. this._gl.clear(mode);
  2780. };
  2781. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  2782. var width = requiredWidth || this._renderingCanvas.width;
  2783. var height = requiredHeight || this._renderingCanvas.height;
  2784. var x = viewport.x || 0;
  2785. var y = viewport.y || 0;
  2786. this._cachedViewport = viewport;
  2787. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  2788. };
  2789. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  2790. this._cachedViewport = null;
  2791. this._gl.viewport(x, y, width, height);
  2792. };
  2793. Engine.prototype.beginFrame = function () {
  2794. BABYLON.Tools._MeasureFps();
  2795. };
  2796. Engine.prototype.endFrame = function () {
  2797. this.flushFramebuffer();
  2798. };
  2799. Engine.prototype.resize = function () {
  2800. this._renderingCanvas.width = this._renderingCanvas.clientWidth / this._hardwareScalingLevel;
  2801. this._renderingCanvas.height = this._renderingCanvas.clientHeight / this._hardwareScalingLevel;
  2802. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  2803. };
  2804. Engine.prototype.bindFramebuffer = function (texture) {
  2805. this._currentRenderTarget = texture;
  2806. var gl = this._gl;
  2807. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  2808. this._gl.viewport(0, 0, texture._width, texture._height);
  2809. this.wipeCaches();
  2810. };
  2811. Engine.prototype.unBindFramebuffer = function (texture) {
  2812. this._currentRenderTarget = null;
  2813. if (texture.generateMipMaps) {
  2814. var gl = this._gl;
  2815. gl.bindTexture(gl.TEXTURE_2D, texture);
  2816. gl.generateMipmap(gl.TEXTURE_2D);
  2817. gl.bindTexture(gl.TEXTURE_2D, null);
  2818. }
  2819. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  2820. };
  2821. Engine.prototype.flushFramebuffer = function () {
  2822. this._gl.flush();
  2823. };
  2824. Engine.prototype.restoreDefaultFramebuffer = function () {
  2825. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  2826. this.setViewport(this._cachedViewport);
  2827. this.wipeCaches();
  2828. };
  2829. Engine.prototype._resetVertexBufferBinding = function () {
  2830. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  2831. this._cachedVertexBuffers = null;
  2832. };
  2833. Engine.prototype.createVertexBuffer = function (vertices) {
  2834. var vbo = this._gl.createBuffer();
  2835. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  2836. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  2837. this._resetVertexBufferBinding();
  2838. vbo.references = 1;
  2839. return vbo;
  2840. };
  2841. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  2842. var vbo = this._gl.createBuffer();
  2843. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  2844. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  2845. this._resetVertexBufferBinding();
  2846. vbo.references = 1;
  2847. return vbo;
  2848. };
  2849. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, length) {
  2850. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  2851. if (vertices instanceof Float32Array) {
  2852. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices);
  2853. } else {
  2854. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices));
  2855. }
  2856. this._resetVertexBufferBinding();
  2857. };
  2858. Engine.prototype._resetIndexBufferBinding = function () {
  2859. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  2860. this._cachedIndexBuffer = null;
  2861. };
  2862. Engine.prototype.createIndexBuffer = function (indices) {
  2863. var vbo = this._gl.createBuffer();
  2864. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  2865. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(indices), this._gl.STATIC_DRAW);
  2866. this._resetIndexBufferBinding();
  2867. vbo.references = 1;
  2868. return vbo;
  2869. };
  2870. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  2871. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  2872. this._cachedVertexBuffers = vertexBuffer;
  2873. this._cachedEffectForVertexBuffers = effect;
  2874. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  2875. var offset = 0;
  2876. for (var index = 0; index < vertexDeclaration.length; index++) {
  2877. var order = effect.getAttributeLocation(index);
  2878. if (order >= 0) {
  2879. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  2880. }
  2881. offset += vertexDeclaration[index] * 4;
  2882. }
  2883. }
  2884. if (this._cachedIndexBuffer !== indexBuffer) {
  2885. this._cachedIndexBuffer = indexBuffer;
  2886. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  2887. }
  2888. };
  2889. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  2890. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  2891. this._cachedVertexBuffers = vertexBuffers;
  2892. this._cachedEffectForVertexBuffers = effect;
  2893. var attributes = effect.getAttributesNames();
  2894. for (var index = 0; index < attributes.length; index++) {
  2895. var order = effect.getAttributeLocation(index);
  2896. if (order >= 0) {
  2897. var vertexBuffer = vertexBuffers[attributes[index]];
  2898. if (!vertexBuffer) {
  2899. continue;
  2900. }
  2901. var stride = vertexBuffer.getStrideSize();
  2902. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  2903. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  2904. }
  2905. }
  2906. }
  2907. if (this._cachedIndexBuffer !== indexBuffer) {
  2908. this._cachedIndexBuffer = indexBuffer;
  2909. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  2910. }
  2911. };
  2912. Engine.prototype._releaseBuffer = function (buffer) {
  2913. buffer.references--;
  2914. if (buffer.references === 0) {
  2915. this._gl.deleteBuffer(buffer);
  2916. return true;
  2917. }
  2918. return false;
  2919. };
  2920. Engine.prototype.createInstancesBuffer = function (capacity) {
  2921. var buffer = this._gl.createBuffer();
  2922. buffer.capacity = capacity;
  2923. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  2924. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  2925. return buffer;
  2926. };
  2927. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  2928. this._gl.deleteBuffer(buffer);
  2929. };
  2930. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  2931. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  2932. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  2933. for (var index = 0; index < 4; index++) {
  2934. var offsetLocation = offsetLocations[index];
  2935. this._gl.enableVertexAttribArray(offsetLocation);
  2936. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  2937. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  2938. }
  2939. };
  2940. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  2941. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  2942. for (var index = 0; index < 4; index++) {
  2943. var offsetLocation = offsetLocations[index];
  2944. this._gl.disableVertexAttribArray(offsetLocation);
  2945. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  2946. }
  2947. };
  2948. Engine.prototype.applyStates = function () {
  2949. this._depthCullingState.apply(this._gl);
  2950. this._alphaState.apply(this._gl);
  2951. };
  2952. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  2953. this.applyStates();
  2954. if (instancesCount) {
  2955. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, this._gl.UNSIGNED_SHORT, indexStart * 2, instancesCount);
  2956. return;
  2957. }
  2958. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, this._gl.UNSIGNED_SHORT, indexStart * 2);
  2959. };
  2960. Engine.prototype._releaseEffect = function (effect) {
  2961. if (this._compiledEffects[effect._key]) {
  2962. delete this._compiledEffects[effect._key];
  2963. if (effect.getProgram()) {
  2964. this._gl.deleteProgram(effect.getProgram());
  2965. }
  2966. }
  2967. };
  2968. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  2969. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  2970. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  2971. var name = vertex + "+" + fragment + "@" + defines;
  2972. if (this._compiledEffects[name]) {
  2973. return this._compiledEffects[name];
  2974. }
  2975. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  2976. effect._key = name;
  2977. this._compiledEffects[name] = effect;
  2978. return effect;
  2979. };
  2980. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  2981. if (typeof uniformsNames === "undefined") { uniformsNames = []; }
  2982. if (typeof samplers === "undefined") { samplers = []; }
  2983. if (typeof defines === "undefined") { defines = ""; }
  2984. return this.createEffect({
  2985. vertex: "particles",
  2986. fragmentElement: fragmentName
  2987. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  2988. };
  2989. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  2990. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  2991. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  2992. var shaderProgram = this._gl.createProgram();
  2993. this._gl.attachShader(shaderProgram, vertexShader);
  2994. this._gl.attachShader(shaderProgram, fragmentShader);
  2995. this._gl.linkProgram(shaderProgram);
  2996. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  2997. if (!linked) {
  2998. var error = this._gl.getProgramInfoLog(shaderProgram);
  2999. if (error) {
  3000. throw new Error(error);
  3001. }
  3002. }
  3003. this._gl.deleteShader(vertexShader);
  3004. this._gl.deleteShader(fragmentShader);
  3005. return shaderProgram;
  3006. };
  3007. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  3008. var results = [];
  3009. for (var index = 0; index < uniformsNames.length; index++) {
  3010. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  3011. }
  3012. return results;
  3013. };
  3014. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  3015. var results = [];
  3016. for (var index = 0; index < attributesNames.length; index++) {
  3017. try {
  3018. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  3019. } catch (e) {
  3020. results.push(-1);
  3021. }
  3022. }
  3023. return results;
  3024. };
  3025. Engine.prototype.enableEffect = function (effect) {
  3026. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  3027. return;
  3028. }
  3029. this._vertexAttribArrays = this._vertexAttribArrays || [];
  3030. this._gl.useProgram(effect.getProgram());
  3031. for (var i in this._vertexAttribArrays) {
  3032. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  3033. continue;
  3034. }
  3035. this._vertexAttribArrays[i] = false;
  3036. this._gl.disableVertexAttribArray(i);
  3037. }
  3038. var attributesCount = effect.getAttributesCount();
  3039. for (var index = 0; index < attributesCount; index++) {
  3040. var order = effect.getAttributeLocation(index);
  3041. if (order >= 0) {
  3042. this._vertexAttribArrays[order] = true;
  3043. this._gl.enableVertexAttribArray(order);
  3044. }
  3045. }
  3046. this._currentEffect = effect;
  3047. };
  3048. Engine.prototype.setArray = function (uniform, array) {
  3049. if (!uniform)
  3050. return;
  3051. this._gl.uniform1fv(uniform, array);
  3052. };
  3053. Engine.prototype.setMatrices = function (uniform, matrices) {
  3054. if (!uniform)
  3055. return;
  3056. this._gl.uniformMatrix4fv(uniform, false, matrices);
  3057. };
  3058. Engine.prototype.setMatrix = function (uniform, matrix) {
  3059. if (!uniform)
  3060. return;
  3061. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  3062. };
  3063. Engine.prototype.setFloat = function (uniform, value) {
  3064. if (!uniform)
  3065. return;
  3066. this._gl.uniform1f(uniform, value);
  3067. };
  3068. Engine.prototype.setFloat2 = function (uniform, x, y) {
  3069. if (!uniform)
  3070. return;
  3071. this._gl.uniform2f(uniform, x, y);
  3072. };
  3073. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  3074. if (!uniform)
  3075. return;
  3076. this._gl.uniform3f(uniform, x, y, z);
  3077. };
  3078. Engine.prototype.setBool = function (uniform, bool) {
  3079. if (!uniform)
  3080. return;
  3081. this._gl.uniform1i(uniform, bool);
  3082. };
  3083. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  3084. if (!uniform)
  3085. return;
  3086. this._gl.uniform4f(uniform, x, y, z, w);
  3087. };
  3088. Engine.prototype.setColor3 = function (uniform, color3) {
  3089. if (!uniform)
  3090. return;
  3091. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  3092. };
  3093. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  3094. if (!uniform)
  3095. return;
  3096. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  3097. };
  3098. Engine.prototype.setState = function (culling, force) {
  3099. if (this._depthCullingState.cull !== culling || force) {
  3100. if (culling) {
  3101. this._depthCullingState.cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  3102. this._depthCullingState.cull = true;
  3103. } else {
  3104. this._depthCullingState.cull = false;
  3105. }
  3106. }
  3107. };
  3108. Engine.prototype.setDepthBuffer = function (enable) {
  3109. this._depthCullingState.depthTest = enable;
  3110. };
  3111. Engine.prototype.getDepthWrite = function () {
  3112. return this._depthCullingState.depthMask;
  3113. };
  3114. Engine.prototype.setDepthWrite = function (enable) {
  3115. this._depthCullingState.depthMask = enable;
  3116. };
  3117. Engine.prototype.setColorWrite = function (enable) {
  3118. this._gl.colorMask(enable, enable, enable, enable);
  3119. };
  3120. Engine.prototype.setAlphaMode = function (mode) {
  3121. switch (mode) {
  3122. case BABYLON.Engine.ALPHA_DISABLE:
  3123. this.setDepthWrite(true);
  3124. this._alphaState.alphaBlend = false;
  3125. break;
  3126. case BABYLON.Engine.ALPHA_COMBINE:
  3127. this.setDepthWrite(false);
  3128. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  3129. this._alphaState.alphaBlend = true;
  3130. break;
  3131. case BABYLON.Engine.ALPHA_ADD:
  3132. this.setDepthWrite(false);
  3133. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  3134. this._alphaState.alphaBlend = true;
  3135. break;
  3136. }
  3137. };
  3138. Engine.prototype.setAlphaTesting = function (enable) {
  3139. this._alphaTest = enable;
  3140. };
  3141. Engine.prototype.getAlphaTesting = function () {
  3142. return this._alphaTest;
  3143. };
  3144. Engine.prototype.wipeCaches = function () {
  3145. this._activeTexturesCache = [];
  3146. this._currentEffect = null;
  3147. this._depthCullingState.reset();
  3148. this._alphaState.reset();
  3149. this._cachedVertexBuffers = null;
  3150. this._cachedIndexBuffer = null;
  3151. this._cachedEffectForVertexBuffers = null;
  3152. };
  3153. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  3154. var gl = this._gl;
  3155. gl.bindTexture(gl.TEXTURE_2D, texture);
  3156. var magFilter = gl.NEAREST;
  3157. var minFilter = gl.NEAREST;
  3158. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  3159. magFilter = gl.LINEAR;
  3160. minFilter = gl.LINEAR;
  3161. } else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  3162. magFilter = gl.LINEAR;
  3163. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  3164. }
  3165. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  3166. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  3167. gl.bindTexture(gl.TEXTURE_2D, null);
  3168. };
  3169. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  3170. var _this = this;
  3171. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  3172. if (typeof onLoad === "undefined") { onLoad = null; }
  3173. if (typeof onError === "undefined") { onError = null; }
  3174. if (typeof buffer === "undefined") { buffer = null; }
  3175. var texture = this._gl.createTexture();
  3176. var extension;
  3177. var fromData = false;
  3178. if (url.substr(0, 5) === "data:") {
  3179. fromData = true;
  3180. }
  3181. if (!fromData)
  3182. extension = url.substr(url.length - 4, 4).toLowerCase();
  3183. else {
  3184. var oldUrl = url;
  3185. fromData = oldUrl.split(':');
  3186. url = oldUrl;
  3187. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  3188. }
  3189. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  3190. var isTGA = (extension === ".tga");
  3191. scene._addPendingData(texture);
  3192. texture.url = url;
  3193. texture.noMipmap = noMipmap;
  3194. texture.references = 1;
  3195. this._loadedTexturesCache.push(texture);
  3196. var onerror = function () {
  3197. scene._removePendingData(texture);
  3198. if (onError) {
  3199. onError();
  3200. }
  3201. };
  3202. if (isTGA) {
  3203. var callback = function (arrayBuffer) {
  3204. var data = new Uint8Array(arrayBuffer);
  3205. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  3206. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  3207. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  3208. if (onLoad) {
  3209. onLoad();
  3210. }
  3211. }, samplingMode);
  3212. };
  3213. if (!(fromData instanceof Array))
  3214. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  3215. callback(arrayBuffer);
  3216. }, onerror, scene.database, true);
  3217. else
  3218. callback(buffer);
  3219. } else if (isDDS) {
  3220. var callback = function (data) {
  3221. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  3222. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) == 1);
  3223. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  3224. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  3225. if (onLoad) {
  3226. onLoad();
  3227. }
  3228. }, samplingMode);
  3229. };
  3230. if (!(fromData instanceof Array))
  3231. BABYLON.Tools.LoadFile(url, function (data) {
  3232. callback(data);
  3233. }, onerror, scene.database, true);
  3234. else
  3235. callback(buffer);
  3236. } else {
  3237. var onload = function (img) {
  3238. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  3239. var isPot = (img.width == potWidth && img.height == potHeight);
  3240. if (!isPot) {
  3241. _this._workingCanvas.width = potWidth;
  3242. _this._workingCanvas.height = potHeight;
  3243. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  3244. }
  3245. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  3246. if (onLoad) {
  3247. onLoad();
  3248. }
  3249. }, samplingMode);
  3250. };
  3251. if (!(fromData instanceof Array))
  3252. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  3253. else
  3254. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  3255. }
  3256. return texture;
  3257. };
  3258. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  3259. var texture = this._gl.createTexture();
  3260. width = BABYLON.Tools.GetExponantOfTwo(width, this._caps.maxTextureSize);
  3261. height = BABYLON.Tools.GetExponantOfTwo(height, this._caps.maxTextureSize);
  3262. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  3263. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  3264. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  3265. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  3266. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  3267. this._activeTexturesCache = [];
  3268. texture._baseWidth = width;
  3269. texture._baseHeight = height;
  3270. texture._width = width;
  3271. texture._height = height;
  3272. texture.isReady = false;
  3273. texture.generateMipMaps = generateMipMaps;
  3274. texture.references = 1;
  3275. this._loadedTexturesCache.push(texture);
  3276. return texture;
  3277. };
  3278. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  3279. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  3280. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  3281. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  3282. if (texture.generateMipMaps) {
  3283. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  3284. }
  3285. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  3286. this._activeTexturesCache = [];
  3287. texture.isReady = true;
  3288. };
  3289. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  3290. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  3291. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1);
  3292. if (video.videoWidth !== texture._width || video.videoHeight !== texture._height) {
  3293. if (!texture._workingCanvas) {
  3294. texture._workingCanvas = document.createElement("canvas");
  3295. texture._workingContext = texture._workingCanvas.getContext("2d");
  3296. texture._workingCanvas.width = texture._width;
  3297. texture._workingCanvas.height = texture._height;
  3298. }
  3299. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  3300. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  3301. } else {
  3302. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  3303. }
  3304. if (texture.generateMipMaps) {
  3305. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  3306. }
  3307. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  3308. this._activeTexturesCache = [];
  3309. texture.isReady = true;
  3310. };
  3311. Engine.prototype.createRenderTargetTexture = function (size, options) {
  3312. var generateMipMaps = false;
  3313. var generateDepthBuffer = true;
  3314. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  3315. if (options !== undefined) {
  3316. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipmaps;
  3317. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  3318. if (options.samplingMode !== undefined) {
  3319. samplingMode = options.samplingMode;
  3320. }
  3321. }
  3322. var gl = this._gl;
  3323. var texture = gl.createTexture();
  3324. gl.bindTexture(gl.TEXTURE_2D, texture);
  3325. var width = size.width || size;
  3326. var height = size.height || size;
  3327. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  3328. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  3329. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  3330. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  3331. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  3332. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  3333. var depthBuffer;
  3334. if (generateDepthBuffer) {
  3335. depthBuffer = gl.createRenderbuffer();
  3336. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  3337. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  3338. }
  3339. var framebuffer = gl.createFramebuffer();
  3340. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  3341. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  3342. if (generateDepthBuffer) {
  3343. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  3344. }
  3345. gl.bindTexture(gl.TEXTURE_2D, null);
  3346. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  3347. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  3348. texture._framebuffer = framebuffer;
  3349. if (generateDepthBuffer) {
  3350. texture._depthBuffer = depthBuffer;
  3351. }
  3352. texture._width = width;
  3353. texture._height = height;
  3354. texture.isReady = true;
  3355. texture.generateMipMaps = generateMipMaps;
  3356. texture.references = 1;
  3357. this._activeTexturesCache = [];
  3358. this._loadedTexturesCache.push(texture);
  3359. return texture;
  3360. };
  3361. Engine.prototype.createCubeTexture = function (rootUrl, scene, extensions, noMipmap) {
  3362. var _this = this;
  3363. var gl = this._gl;
  3364. var texture = gl.createTexture();
  3365. texture.isCube = true;
  3366. texture.url = rootUrl;
  3367. texture.references = 1;
  3368. this._loadedTexturesCache.push(texture);
  3369. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  3370. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  3371. if (isDDS) {
  3372. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  3373. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  3374. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  3375. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  3376. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  3377. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  3378. if (!noMipmap && !info.isFourCC && info.mipmapCount == 1) {
  3379. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  3380. }
  3381. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  3382. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  3383. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  3384. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  3385. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  3386. _this._activeTexturesCache = [];
  3387. texture._width = info.width;
  3388. texture._height = info.height;
  3389. texture.isReady = true;
  3390. }, null, null, true);
  3391. } else {
  3392. cascadeLoad(rootUrl, scene, function (imgs) {
  3393. var width = BABYLON.Tools.GetExponantOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  3394. var height = width;
  3395. _this._workingCanvas.width = width;
  3396. _this._workingCanvas.height = height;
  3397. var faces = [
  3398. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  3399. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  3400. ];
  3401. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  3402. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  3403. for (var index = 0; index < faces.length; index++) {
  3404. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  3405. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  3406. }
  3407. if (!noMipmap) {
  3408. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  3409. }
  3410. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  3411. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  3412. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  3413. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  3414. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  3415. _this._activeTexturesCache = [];
  3416. texture._width = width;
  3417. texture._height = height;
  3418. texture.isReady = true;
  3419. }, extensions);
  3420. }
  3421. return texture;
  3422. };
  3423. Engine.prototype._releaseTexture = function (texture) {
  3424. var gl = this._gl;
  3425. if (texture._framebuffer) {
  3426. gl.deleteFramebuffer(texture._framebuffer);
  3427. }
  3428. if (texture._depthBuffer) {
  3429. gl.deleteRenderbuffer(texture._depthBuffer);
  3430. }
  3431. gl.deleteTexture(texture);
  3432. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  3433. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  3434. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  3435. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  3436. this._activeTexturesCache[channel] = null;
  3437. }
  3438. var index = this._loadedTexturesCache.indexOf(texture);
  3439. if (index !== -1) {
  3440. this._loadedTexturesCache.splice(index, 1);
  3441. }
  3442. };
  3443. Engine.prototype.bindSamplers = function (effect) {
  3444. this._gl.useProgram(effect.getProgram());
  3445. var samplers = effect.getSamplers();
  3446. for (var index = 0; index < samplers.length; index++) {
  3447. var uniform = effect.getUniform(samplers[index]);
  3448. this._gl.uniform1i(uniform, index);
  3449. }
  3450. this._currentEffect = null;
  3451. };
  3452. Engine.prototype._bindTexture = function (channel, texture) {
  3453. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  3454. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  3455. this._activeTexturesCache[channel] = null;
  3456. };
  3457. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  3458. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  3459. };
  3460. Engine.prototype.setTexture = function (channel, texture) {
  3461. if (channel < 0) {
  3462. return;
  3463. }
  3464. if (!texture || !texture.isReady()) {
  3465. if (this._activeTexturesCache[channel] != null) {
  3466. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  3467. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  3468. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  3469. this._activeTexturesCache[channel] = null;
  3470. }
  3471. return;
  3472. }
  3473. if (texture instanceof BABYLON.VideoTexture) {
  3474. if (texture.update()) {
  3475. this._activeTexturesCache[channel] = null;
  3476. }
  3477. } else if (texture.delayLoadState == BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  3478. texture.delayLoad();
  3479. return;
  3480. }
  3481. if (this._activeTexturesCache[channel] == texture) {
  3482. return;
  3483. }
  3484. this._activeTexturesCache[channel] = texture;
  3485. var internalTexture = texture.getInternalTexture();
  3486. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  3487. if (internalTexture.isCube) {
  3488. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  3489. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  3490. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  3491. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  3492. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  3493. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  3494. }
  3495. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  3496. } else {
  3497. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  3498. if (internalTexture._cachedWrapU !== texture.wrapU) {
  3499. internalTexture._cachedWrapU = texture.wrapU;
  3500. switch (texture.wrapU) {
  3501. case BABYLON.Texture.WRAP_ADDRESSMODE:
  3502. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  3503. break;
  3504. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  3505. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  3506. break;
  3507. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  3508. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  3509. break;
  3510. }
  3511. }
  3512. if (internalTexture._cachedWrapV !== texture.wrapV) {
  3513. internalTexture._cachedWrapV = texture.wrapV;
  3514. switch (texture.wrapV) {
  3515. case BABYLON.Texture.WRAP_ADDRESSMODE:
  3516. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  3517. break;
  3518. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  3519. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  3520. break;
  3521. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  3522. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  3523. break;
  3524. }
  3525. }
  3526. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  3527. }
  3528. };
  3529. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  3530. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  3531. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== texture.anisotropicFilteringLevel) {
  3532. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(texture.anisotropicFilteringLevel, this._caps.maxAnisotropy));
  3533. texture._cachedAnisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  3534. }
  3535. };
  3536. Engine.prototype.readPixels = function (x, y, width, height) {
  3537. var data = new Uint8Array(height * width * 4);
  3538. this._gl.readPixels(0, 0, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  3539. return data;
  3540. };
  3541. Engine.prototype.dispose = function () {
  3542. this.hideLoadingUI();
  3543. this.stopRenderLoop();
  3544. while (this.scenes.length) {
  3545. this.scenes[0].dispose();
  3546. }
  3547. for (var name in this._compiledEffects) {
  3548. this._gl.deleteProgram(this._compiledEffects[name]._program);
  3549. }
  3550. for (var i in this._vertexAttribArrays) {
  3551. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  3552. continue;
  3553. }
  3554. this._gl.disableVertexAttribArray(i);
  3555. }
  3556. window.removeEventListener("blur", this._onBlur);
  3557. window.removeEventListener("focus", this._onFocus);
  3558. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  3559. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  3560. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  3561. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  3562. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  3563. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  3564. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  3565. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  3566. };
  3567. Engine.prototype.displayLoadingUI = function () {
  3568. var _this = this;
  3569. this._loadingDiv = document.createElement("div");
  3570. this._loadingDiv.style.opacity = "0";
  3571. this._loadingDiv.style.transition = "opacity 1.5s ease";
  3572. this._loadingTextDiv = document.createElement("div");
  3573. this._loadingTextDiv.style.position = "absolute";
  3574. this._loadingTextDiv.style.left = "0";
  3575. this._loadingTextDiv.style.top = "50%";
  3576. this._loadingTextDiv.style.marginTop = "80px";
  3577. this._loadingTextDiv.style.width = "100%";
  3578. this._loadingTextDiv.style.height = "20px";
  3579. this._loadingTextDiv.style.fontFamily = "Arial";
  3580. this._loadingTextDiv.style.fontSize = "14px";
  3581. this._loadingTextDiv.style.color = "white";
  3582. this._loadingTextDiv.style.textAlign = "center";
  3583. this._loadingTextDiv.innerHTML = "Loading";
  3584. this._loadingDiv.appendChild(this._loadingTextDiv);
  3585. var imgBack = new Image();
  3586. 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==";
  3587. imgBack.style.position = "absolute";
  3588. imgBack.style.left = "50%";
  3589. imgBack.style.top = "50%";
  3590. imgBack.style.marginLeft = "-50px";
  3591. imgBack.style.marginTop = "-50px";
  3592. imgBack.style.transition = "transform 1.0s ease";
  3593. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  3594. var deg = 360;
  3595. var onTransitionEnd = function () {
  3596. deg += 360;
  3597. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  3598. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  3599. };
  3600. imgBack.addEventListener("transitionend", onTransitionEnd);
  3601. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  3602. this._loadingDiv.appendChild(imgBack);
  3603. var imgFront = new Image();
  3604. 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=";
  3605. imgFront.style.position = "absolute";
  3606. imgFront.style.left = "50%";
  3607. imgFront.style.top = "50%";
  3608. imgFront.style.marginLeft = "-50px";
  3609. imgFront.style.marginTop = "-50px";
  3610. this._loadingDiv.appendChild(imgFront);
  3611. this._resizeLoadingUI = function () {
  3612. var canvasRect = _this.getRenderingCanvasClientRect();
  3613. _this._loadingDiv.style.position = "absolute";
  3614. _this._loadingDiv.style.left = canvasRect.left + "px";
  3615. _this._loadingDiv.style.top = canvasRect.top + "px";
  3616. _this._loadingDiv.style.width = canvasRect.width + "px";
  3617. _this._loadingDiv.style.height = canvasRect.height + "px";
  3618. };
  3619. this._resizeLoadingUI();
  3620. window.addEventListener("resize", this._resizeLoadingUI);
  3621. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  3622. document.body.appendChild(this._loadingDiv);
  3623. setTimeout(function () {
  3624. _this._loadingDiv.style.opacity = "1";
  3625. imgBack.style.transform = "rotateZ(360deg)";
  3626. imgBack.style.webkitTransform = "rotateZ(360deg)";
  3627. }, 0);
  3628. };
  3629. Object.defineProperty(Engine.prototype, "loadingUIText", {
  3630. set: function (text) {
  3631. if (!this._loadingDiv) {
  3632. return;
  3633. }
  3634. this._loadingTextDiv.innerHTML = text;
  3635. },
  3636. enumerable: true,
  3637. configurable: true
  3638. });
  3639. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  3640. get: function () {
  3641. return this._loadingDivBackgroundColor;
  3642. },
  3643. set: function (color) {
  3644. this._loadingDivBackgroundColor = color;
  3645. if (!this._loadingDiv) {
  3646. return;
  3647. }
  3648. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  3649. },
  3650. enumerable: true,
  3651. configurable: true
  3652. });
  3653. Engine.prototype.hideLoadingUI = function () {
  3654. var _this = this;
  3655. if (!this._loadingDiv) {
  3656. return;
  3657. }
  3658. var onTransitionEnd = function () {
  3659. if (!_this._loadingDiv) {
  3660. return;
  3661. }
  3662. document.body.removeChild(_this._loadingDiv);
  3663. window.removeEventListener("resize", _this._resizeLoadingUI);
  3664. _this._loadingDiv = null;
  3665. };
  3666. this._loadingDiv.style.opacity = "0";
  3667. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  3668. };
  3669. Engine.isSupported = function () {
  3670. try {
  3671. var tempcanvas = document.createElement("canvas");
  3672. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  3673. return gl != null && !!window.WebGLRenderingContext;
  3674. } catch (e) {
  3675. return false;
  3676. }
  3677. };
  3678. Engine._ALPHA_DISABLE = 0;
  3679. Engine._ALPHA_ADD = 1;
  3680. Engine._ALPHA_COMBINE = 2;
  3681. Engine._DELAYLOADSTATE_NONE = 0;
  3682. Engine._DELAYLOADSTATE_LOADED = 1;
  3683. Engine._DELAYLOADSTATE_LOADING = 2;
  3684. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  3685. Engine.Epsilon = 0.001;
  3686. Engine.CollisionsEpsilon = 0.001;
  3687. Engine.ShadersRepository = "Babylon/Shaders/";
  3688. return Engine;
  3689. })();
  3690. BABYLON.Engine = Engine;
  3691. })(BABYLON || (BABYLON = {}));
  3692. var BABYLON;
  3693. (function (BABYLON) {
  3694. var Node = (function () {
  3695. function Node(name, scene) {
  3696. this.state = "";
  3697. this.animations = new Array();
  3698. this._childrenFlag = -1;
  3699. this._isEnabled = true;
  3700. this._isReady = true;
  3701. this._currentRenderId = -1;
  3702. this.name = name;
  3703. this.id = name;
  3704. this._scene = scene;
  3705. this._initCache();
  3706. }
  3707. Node.prototype.getScene = function () {
  3708. return this._scene;
  3709. };
  3710. Node.prototype.getEngine = function () {
  3711. return this._scene.getEngine();
  3712. };
  3713. Node.prototype.getWorldMatrix = function () {
  3714. return BABYLON.Matrix.Identity();
  3715. };
  3716. Node.prototype._initCache = function () {
  3717. this._cache = {};
  3718. this._cache.parent = undefined;
  3719. };
  3720. Node.prototype.updateCache = function (force) {
  3721. if (!force && this.isSynchronized())
  3722. return;
  3723. this._cache.parent = this.parent;
  3724. this._updateCache();
  3725. };
  3726. Node.prototype._updateCache = function (ignoreParentClass) {
  3727. };
  3728. Node.prototype._isSynchronized = function () {
  3729. return true;
  3730. };
  3731. Node.prototype.isSynchronizedWithParent = function () {
  3732. return this.parent ? this.parent._currentRenderId <= this._currentRenderId : true;
  3733. };
  3734. Node.prototype.isSynchronized = function (updateCache) {
  3735. var check = this.hasNewParent();
  3736. check = check || !this.isSynchronizedWithParent();
  3737. check = check || !this._isSynchronized();
  3738. if (updateCache)
  3739. this.updateCache(true);
  3740. return !check;
  3741. };
  3742. Node.prototype.hasNewParent = function (update) {
  3743. if (this._cache.parent === this.parent)
  3744. return false;
  3745. if (update)
  3746. this._cache.parent = this.parent;
  3747. return true;
  3748. };
  3749. Node.prototype.isReady = function () {
  3750. return this._isReady;
  3751. };
  3752. Node.prototype.isEnabled = function () {
  3753. if (!this._isEnabled) {
  3754. return false;
  3755. }
  3756. if (this.parent) {
  3757. return this.parent.isEnabled();
  3758. }
  3759. return true;
  3760. };
  3761. Node.prototype.setEnabled = function (value) {
  3762. this._isEnabled = value;
  3763. };
  3764. Node.prototype.isDescendantOf = function (ancestor) {
  3765. if (this.parent) {
  3766. if (this.parent === ancestor) {
  3767. return true;
  3768. }
  3769. return this.parent.isDescendantOf(ancestor);
  3770. }
  3771. return false;
  3772. };
  3773. Node.prototype._getDescendants = function (list, results) {
  3774. for (var index = 0; index < list.length; index++) {
  3775. var item = list[index];
  3776. if (item.isDescendantOf(this)) {
  3777. results.push(item);
  3778. }
  3779. }
  3780. };
  3781. Node.prototype.getDescendants = function () {
  3782. var results = [];
  3783. this._getDescendants(this._scene.meshes, results);
  3784. this._getDescendants(this._scene.lights, results);
  3785. this._getDescendants(this._scene.cameras, results);
  3786. return results;
  3787. };
  3788. Node.prototype._setReady = function (state) {
  3789. if (state == this._isReady) {
  3790. return;
  3791. }
  3792. if (!state) {
  3793. this._isReady = false;
  3794. return;
  3795. }
  3796. this._isReady = true;
  3797. if (this.onReady) {
  3798. this.onReady(this);
  3799. }
  3800. };
  3801. return Node;
  3802. })();
  3803. BABYLON.Node = Node;
  3804. })(BABYLON || (BABYLON = {}));
  3805. var BABYLON;
  3806. (function (BABYLON) {
  3807. var BoundingSphere = (function () {
  3808. function BoundingSphere(minimum, maximum) {
  3809. this.minimum = minimum;
  3810. this.maximum = maximum;
  3811. this._tempRadiusVector = BABYLON.Vector3.Zero();
  3812. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  3813. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  3814. this.radius = distance * 0.5;
  3815. this.centerWorld = BABYLON.Vector3.Zero();
  3816. this._update(BABYLON.Matrix.Identity());
  3817. }
  3818. BoundingSphere.prototype._update = function (world) {
  3819. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  3820. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  3821. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  3822. };
  3823. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  3824. for (var i = 0; i < 6; i++) {
  3825. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  3826. return false;
  3827. }
  3828. return true;
  3829. };
  3830. BoundingSphere.prototype.intersectsPoint = function (point) {
  3831. var x = this.centerWorld.x - point.x;
  3832. var y = this.centerWorld.y - point.y;
  3833. var z = this.centerWorld.z - point.z;
  3834. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  3835. if (Math.abs(this.radiusWorld - distance) < BABYLON.Engine.Epsilon)
  3836. return false;
  3837. return true;
  3838. };
  3839. BoundingSphere.Intersects = function (sphere0, sphere1) {
  3840. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  3841. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  3842. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  3843. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  3844. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  3845. return false;
  3846. return true;
  3847. };
  3848. return BoundingSphere;
  3849. })();
  3850. BABYLON.BoundingSphere = BoundingSphere;
  3851. })(BABYLON || (BABYLON = {}));
  3852. var BABYLON;
  3853. (function (BABYLON) {
  3854. var BoundingBox = (function () {
  3855. function BoundingBox(minimum, maximum) {
  3856. this.minimum = minimum;
  3857. this.maximum = maximum;
  3858. this.vectors = new Array();
  3859. this.vectorsWorld = new Array();
  3860. this.vectors.push(this.minimum.clone());
  3861. this.vectors.push(this.maximum.clone());
  3862. this.vectors.push(this.minimum.clone());
  3863. this.vectors[2].x = this.maximum.x;
  3864. this.vectors.push(this.minimum.clone());
  3865. this.vectors[3].y = this.maximum.y;
  3866. this.vectors.push(this.minimum.clone());
  3867. this.vectors[4].z = this.maximum.z;
  3868. this.vectors.push(this.maximum.clone());
  3869. this.vectors[5].z = this.minimum.z;
  3870. this.vectors.push(this.maximum.clone());
  3871. this.vectors[6].x = this.minimum.x;
  3872. this.vectors.push(this.maximum.clone());
  3873. this.vectors[7].y = this.minimum.y;
  3874. this.center = this.maximum.add(this.minimum).scale(0.5);
  3875. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  3876. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  3877. for (var index = 0; index < this.vectors.length; index++) {
  3878. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  3879. }
  3880. this.minimumWorld = BABYLON.Vector3.Zero();
  3881. this.maximumWorld = BABYLON.Vector3.Zero();
  3882. this._update(BABYLON.Matrix.Identity());
  3883. }
  3884. BoundingBox.prototype.getWorldMatrix = function () {
  3885. return this._worldMatrix;
  3886. };
  3887. BoundingBox.prototype._update = function (world) {
  3888. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  3889. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  3890. for (var index = 0; index < this.vectors.length; index++) {
  3891. var v = this.vectorsWorld[index];
  3892. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  3893. if (v.x < this.minimumWorld.x)
  3894. this.minimumWorld.x = v.x;
  3895. if (v.y < this.minimumWorld.y)
  3896. this.minimumWorld.y = v.y;
  3897. if (v.z < this.minimumWorld.z)
  3898. this.minimumWorld.z = v.z;
  3899. if (v.x > this.maximumWorld.x)
  3900. this.maximumWorld.x = v.x;
  3901. if (v.y > this.maximumWorld.y)
  3902. this.maximumWorld.y = v.y;
  3903. if (v.z > this.maximumWorld.z)
  3904. this.maximumWorld.z = v.z;
  3905. }
  3906. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  3907. this.center.scaleInPlace(0.5);
  3908. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  3909. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  3910. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  3911. this._worldMatrix = world;
  3912. };
  3913. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  3914. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  3915. };
  3916. BoundingBox.prototype.intersectsPoint = function (point) {
  3917. var delta = BABYLON.Engine.Epsilon;
  3918. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  3919. return false;
  3920. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  3921. return false;
  3922. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  3923. return false;
  3924. return true;
  3925. };
  3926. BoundingBox.prototype.intersectsSphere = function (sphere) {
  3927. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  3928. };
  3929. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  3930. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  3931. return false;
  3932. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  3933. return false;
  3934. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  3935. return false;
  3936. return true;
  3937. };
  3938. BoundingBox.Intersects = function (box0, box1) {
  3939. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  3940. return false;
  3941. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  3942. return false;
  3943. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  3944. return false;
  3945. return true;
  3946. };
  3947. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  3948. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  3949. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  3950. return (num <= (sphereRadius * sphereRadius));
  3951. };
  3952. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  3953. for (var p = 0; p < 6; p++) {
  3954. var inCount = 8;
  3955. for (var i = 0; i < 8; i++) {
  3956. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  3957. --inCount;
  3958. } else {
  3959. break;
  3960. }
  3961. }
  3962. if (inCount == 0)
  3963. return false;
  3964. }
  3965. return true;
  3966. };
  3967. return BoundingBox;
  3968. })();
  3969. BABYLON.BoundingBox = BoundingBox;
  3970. })(BABYLON || (BABYLON = {}));
  3971. var BABYLON;
  3972. (function (BABYLON) {
  3973. var computeBoxExtents = function (axis, box) {
  3974. var p = BABYLON.Vector3.Dot(box.center, axis);
  3975. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  3976. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  3977. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  3978. var r = r0 + r1 + r2;
  3979. return {
  3980. min: p - r,
  3981. max: p + r
  3982. };
  3983. };
  3984. var extentsOverlap = function (min0, max0, min1, max1) {
  3985. return !(min0 > max1 || min1 > max0);
  3986. };
  3987. var axisOverlap = function (axis, box0, box1) {
  3988. var result0 = computeBoxExtents(axis, box0);
  3989. var result1 = computeBoxExtents(axis, box1);
  3990. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  3991. };
  3992. var BoundingInfo = (function () {
  3993. function BoundingInfo(minimum, maximum) {
  3994. this.minimum = minimum;
  3995. this.maximum = maximum;
  3996. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  3997. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  3998. }
  3999. BoundingInfo.prototype._update = function (world) {
  4000. this.boundingBox._update(world);
  4001. this.boundingSphere._update(world);
  4002. };
  4003. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  4004. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  4005. return false;
  4006. return this.boundingBox.isInFrustum(frustumPlanes);
  4007. };
  4008. BoundingInfo.prototype._checkCollision = function (collider) {
  4009. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  4010. };
  4011. BoundingInfo.prototype.intersectsPoint = function (point) {
  4012. if (!this.boundingSphere.centerWorld) {
  4013. return false;
  4014. }
  4015. if (!this.boundingSphere.intersectsPoint(point)) {
  4016. return false;
  4017. }
  4018. if (!this.boundingBox.intersectsPoint(point)) {
  4019. return false;
  4020. }
  4021. return true;
  4022. };
  4023. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  4024. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  4025. return false;
  4026. }
  4027. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  4028. return false;
  4029. }
  4030. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  4031. return false;
  4032. }
  4033. if (!precise) {
  4034. return true;
  4035. }
  4036. var box0 = this.boundingBox;
  4037. var box1 = boundingInfo.boundingBox;
  4038. if (!axisOverlap(box0.directions[0], box0, box1))
  4039. return false;
  4040. if (!axisOverlap(box0.directions[1], box0, box1))
  4041. return false;
  4042. if (!axisOverlap(box0.directions[2], box0, box1))
  4043. return false;
  4044. if (!axisOverlap(box1.directions[0], box0, box1))
  4045. return false;
  4046. if (!axisOverlap(box1.directions[1], box0, box1))
  4047. return false;
  4048. if (!axisOverlap(box1.directions[2], box0, box1))
  4049. return false;
  4050. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  4051. return false;
  4052. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  4053. return false;
  4054. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  4055. return false;
  4056. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  4057. return false;
  4058. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  4059. return false;
  4060. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  4061. return false;
  4062. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  4063. return false;
  4064. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  4065. return false;
  4066. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  4067. return false;
  4068. return true;
  4069. };
  4070. return BoundingInfo;
  4071. })();
  4072. BABYLON.BoundingInfo = BoundingInfo;
  4073. })(BABYLON || (BABYLON = {}));
  4074. var __extends = this.__extends || function (d, b) {
  4075. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  4076. function __() { this.constructor = d; }
  4077. __.prototype = b.prototype;
  4078. d.prototype = new __();
  4079. };
  4080. var BABYLON;
  4081. (function (BABYLON) {
  4082. var Light = (function (_super) {
  4083. __extends(Light, _super);
  4084. function Light(name, scene) {
  4085. _super.call(this, name, scene);
  4086. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  4087. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  4088. this.intensity = 1.0;
  4089. this.range = Number.MAX_VALUE;
  4090. this.includedOnlyMeshes = new Array();
  4091. this.excludedMeshes = new Array();
  4092. this._excludedMeshesIds = new Array();
  4093. this._includedOnlyMeshesIds = new Array();
  4094. scene.lights.push(this);
  4095. }
  4096. Light.prototype.getShadowGenerator = function () {
  4097. return this._shadowGenerator;
  4098. };
  4099. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  4100. };
  4101. Light.prototype._getWorldMatrix = function () {
  4102. return BABYLON.Matrix.Identity();
  4103. };
  4104. Light.prototype.canAffectMesh = function (mesh) {
  4105. if (!mesh) {
  4106. return true;
  4107. }
  4108. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  4109. return false;
  4110. }
  4111. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  4112. return false;
  4113. }
  4114. return true;
  4115. };
  4116. Light.prototype.getWorldMatrix = function () {
  4117. this._currentRenderId = this.getScene().getRenderId();
  4118. var worldMatrix = this._getWorldMatrix();
  4119. if (this.parent && this.parent.getWorldMatrix) {
  4120. if (!this._parentedWorldMatrix) {
  4121. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  4122. }
  4123. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  4124. return this._parentedWorldMatrix;
  4125. }
  4126. return worldMatrix;
  4127. };
  4128. Light.prototype.dispose = function () {
  4129. if (this._shadowGenerator) {
  4130. this._shadowGenerator.dispose();
  4131. this._shadowGenerator = null;
  4132. }
  4133. var index = this.getScene().lights.indexOf(this);
  4134. this.getScene().lights.splice(index, 1);
  4135. };
  4136. return Light;
  4137. })(BABYLON.Node);
  4138. BABYLON.Light = Light;
  4139. })(BABYLON || (BABYLON = {}));
  4140. var __extends = this.__extends || function (d, b) {
  4141. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  4142. function __() { this.constructor = d; }
  4143. __.prototype = b.prototype;
  4144. d.prototype = new __();
  4145. };
  4146. var BABYLON;
  4147. (function (BABYLON) {
  4148. var PointLight = (function (_super) {
  4149. __extends(PointLight, _super);
  4150. function PointLight(name, position, scene) {
  4151. _super.call(this, name, scene);
  4152. this.position = position;
  4153. }
  4154. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  4155. if (this.parent && this.parent.getWorldMatrix) {
  4156. if (!this._transformedPosition) {
  4157. this._transformedPosition = BABYLON.Vector3.Zero();
  4158. }
  4159. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this._transformedPosition);
  4160. effect.setFloat4(positionUniformName, this._transformedPosition.x, this._transformedPosition.y, this._transformedPosition.z, 0);
  4161. return;
  4162. }
  4163. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  4164. };
  4165. PointLight.prototype.getShadowGenerator = function () {
  4166. return null;
  4167. };
  4168. PointLight.prototype._getWorldMatrix = function () {
  4169. if (!this._worldMatrix) {
  4170. this._worldMatrix = BABYLON.Matrix.Identity();
  4171. }
  4172. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  4173. return this._worldMatrix;
  4174. };
  4175. return PointLight;
  4176. })(BABYLON.Light);
  4177. BABYLON.PointLight = PointLight;
  4178. })(BABYLON || (BABYLON = {}));
  4179. var __extends = this.__extends || function (d, b) {
  4180. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  4181. function __() { this.constructor = d; }
  4182. __.prototype = b.prototype;
  4183. d.prototype = new __();
  4184. };
  4185. var BABYLON;
  4186. (function (BABYLON) {
  4187. var SpotLight = (function (_super) {
  4188. __extends(SpotLight, _super);
  4189. function SpotLight(name, position, direction, angle, exponent, scene) {
  4190. _super.call(this, name, scene);
  4191. this.position = position;
  4192. this.direction = direction;
  4193. this.angle = angle;
  4194. this.exponent = exponent;
  4195. }
  4196. SpotLight.prototype.setDirectionToTarget = function (target) {
  4197. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  4198. return this.direction;
  4199. };
  4200. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  4201. var normalizeDirection;
  4202. if (this.parent && this.parent.getWorldMatrix) {
  4203. if (!this._transformedDirection) {
  4204. this._transformedDirection = BABYLON.Vector3.Zero();
  4205. }
  4206. if (!this._transformedPosition) {
  4207. this._transformedPosition = BABYLON.Vector3.Zero();
  4208. }
  4209. var parentWorldMatrix = this.parent.getWorldMatrix();
  4210. BABYLON.Vector3.TransformCoordinatesToRef(this.position, parentWorldMatrix, this._transformedPosition);
  4211. BABYLON.Vector3.TransformNormalToRef(this.direction, parentWorldMatrix, this._transformedDirection);
  4212. effect.setFloat4(positionUniformName, this._transformedPosition.x, this._transformedPosition.y, this._transformedPosition.z, this.exponent);
  4213. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  4214. } else {
  4215. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  4216. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  4217. }
  4218. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  4219. };
  4220. SpotLight.prototype._getWorldMatrix = function () {
  4221. if (!this._worldMatrix) {
  4222. this._worldMatrix = BABYLON.Matrix.Identity();
  4223. }
  4224. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  4225. return this._worldMatrix;
  4226. };
  4227. return SpotLight;
  4228. })(BABYLON.Light);
  4229. BABYLON.SpotLight = SpotLight;
  4230. })(BABYLON || (BABYLON = {}));
  4231. var __extends = this.__extends || function (d, b) {
  4232. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  4233. function __() { this.constructor = d; }
  4234. __.prototype = b.prototype;
  4235. d.prototype = new __();
  4236. };
  4237. var BABYLON;
  4238. (function (BABYLON) {
  4239. var DirectionalLight = (function (_super) {
  4240. __extends(DirectionalLight, _super);
  4241. function DirectionalLight(name, direction, scene) {
  4242. _super.call(this, name, scene);
  4243. this.direction = direction;
  4244. this.position = direction.scale(-1);
  4245. }
  4246. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  4247. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  4248. return this.direction;
  4249. };
  4250. DirectionalLight.prototype._computeTransformedPosition = function () {
  4251. if (this.parent && this.parent.getWorldMatrix) {
  4252. if (!this._transformedPosition) {
  4253. this._transformedPosition = BABYLON.Vector3.Zero();
  4254. }
  4255. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this._transformedPosition);
  4256. return true;
  4257. }
  4258. return false;
  4259. };
  4260. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  4261. if (this.parent && this.parent.getWorldMatrix) {
  4262. if (!this._transformedDirection) {
  4263. this._transformedDirection = BABYLON.Vector3.Zero();
  4264. }
  4265. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  4266. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  4267. return;
  4268. }
  4269. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  4270. };
  4271. DirectionalLight.prototype._getWorldMatrix = function () {
  4272. if (!this._worldMatrix) {
  4273. this._worldMatrix = BABYLON.Matrix.Identity();
  4274. }
  4275. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  4276. return this._worldMatrix;
  4277. };
  4278. return DirectionalLight;
  4279. })(BABYLON.Light);
  4280. BABYLON.DirectionalLight = DirectionalLight;
  4281. })(BABYLON || (BABYLON = {}));
  4282. var BABYLON;
  4283. (function (BABYLON) {
  4284. var ShadowGenerator = (function () {
  4285. function ShadowGenerator(mapSize, light) {
  4286. var _this = this;
  4287. this.filter = ShadowGenerator.FILTER_VARIANCESHADOWMAP;
  4288. this._darkness = 0;
  4289. this._transparencyShadow = false;
  4290. this._viewMatrix = BABYLON.Matrix.Zero();
  4291. this._projectionMatrix = BABYLON.Matrix.Zero();
  4292. this._transformMatrix = BABYLON.Matrix.Zero();
  4293. this._worldViewProjection = BABYLON.Matrix.Zero();
  4294. this._light = light;
  4295. this._scene = light.getScene();
  4296. light._shadowGenerator = this;
  4297. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false);
  4298. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  4299. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  4300. this._shadowMap.renderParticles = false;
  4301. var renderSubMesh = function (subMesh) {
  4302. var mesh = subMesh.getRenderingMesh();
  4303. var scene = _this._scene;
  4304. var engine = scene.getEngine();
  4305. engine.setState(subMesh.getMaterial().backFaceCulling);
  4306. var batch = mesh._getInstancesRenderList(subMesh._id);
  4307. if (batch.mustReturn) {
  4308. return;
  4309. }
  4310. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  4311. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  4312. engine.enableEffect(_this._effect);
  4313. mesh._bind(subMesh, _this._effect, false);
  4314. var material = subMesh.getMaterial();
  4315. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  4316. if (material && material.needAlphaTesting()) {
  4317. var alphaTexture = material.getAlphaTestTexture();
  4318. _this._effect.setTexture("diffuseSampler", alphaTexture);
  4319. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  4320. }
  4321. var useBones = mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  4322. if (useBones) {
  4323. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  4324. }
  4325. if (hardwareInstancedRendering) {
  4326. mesh._renderWithInstances(subMesh, false, batch, _this._effect, engine);
  4327. } else {
  4328. if (batch.renderSelf[subMesh._id]) {
  4329. _this._effect.setMatrix("world", mesh.getWorldMatrix());
  4330. mesh._draw(subMesh, true);
  4331. }
  4332. if (batch.visibleInstances[subMesh._id]) {
  4333. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  4334. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  4335. _this._effect.setMatrix("world", instance.getWorldMatrix());
  4336. mesh._draw(subMesh, true);
  4337. }
  4338. }
  4339. }
  4340. } else {
  4341. _this._shadowMap.resetRefreshCounter();
  4342. }
  4343. };
  4344. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  4345. var index;
  4346. for (index = 0; index < opaqueSubMeshes.length; index++) {
  4347. renderSubMesh(opaqueSubMeshes.data[index]);
  4348. }
  4349. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  4350. renderSubMesh(alphaTestSubMeshes.data[index]);
  4351. }
  4352. if (_this._transparencyShadow) {
  4353. for (index = 0; index < transparentSubMeshes.length; index++) {
  4354. renderSubMesh(transparentSubMeshes.data[index]);
  4355. }
  4356. }
  4357. };
  4358. }
  4359. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  4360. get: function () {
  4361. return ShadowGenerator._FILTER_NONE;
  4362. },
  4363. enumerable: true,
  4364. configurable: true
  4365. });
  4366. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  4367. get: function () {
  4368. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  4369. },
  4370. enumerable: true,
  4371. configurable: true
  4372. });
  4373. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  4374. get: function () {
  4375. return ShadowGenerator._FILTER_POISSONSAMPLING;
  4376. },
  4377. enumerable: true,
  4378. configurable: true
  4379. });
  4380. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  4381. get: function () {
  4382. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP;
  4383. },
  4384. set: function (value) {
  4385. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  4386. },
  4387. enumerable: true,
  4388. configurable: true
  4389. });
  4390. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  4391. get: function () {
  4392. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  4393. },
  4394. set: function (value) {
  4395. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  4396. },
  4397. enumerable: true,
  4398. configurable: true
  4399. });
  4400. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  4401. var defines = [];
  4402. if (this.useVarianceShadowMap) {
  4403. defines.push("#define VSM");
  4404. }
  4405. var attribs = [BABYLON.VertexBuffer.PositionKind];
  4406. var mesh = subMesh.getMesh();
  4407. var material = subMesh.getMaterial();
  4408. if (material && material.needAlphaTesting()) {
  4409. defines.push("#define ALPHATEST");
  4410. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  4411. attribs.push(BABYLON.VertexBuffer.UVKind);
  4412. defines.push("#define UV1");
  4413. }
  4414. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  4415. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  4416. defines.push("#define UV2");
  4417. }
  4418. }
  4419. if (mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  4420. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  4421. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  4422. defines.push("#define BONES");
  4423. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  4424. }
  4425. if (useInstances) {
  4426. defines.push("#define INSTANCES");
  4427. attribs.push("world0");
  4428. attribs.push("world1");
  4429. attribs.push("world2");
  4430. attribs.push("world3");
  4431. }
  4432. var join = defines.join("\n");
  4433. if (this._cachedDefines != join) {
  4434. this._cachedDefines = join;
  4435. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  4436. }
  4437. return this._effect.isReady();
  4438. };
  4439. ShadowGenerator.prototype.getShadowMap = function () {
  4440. return this._shadowMap;
  4441. };
  4442. ShadowGenerator.prototype.getLight = function () {
  4443. return this._light;
  4444. };
  4445. ShadowGenerator.prototype.getTransformMatrix = function () {
  4446. var lightPosition = this._light.position;
  4447. var lightDirection = this._light.direction;
  4448. if (this._light._computeTransformedPosition()) {
  4449. lightPosition = this._light._transformedPosition;
  4450. }
  4451. if (!this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !lightDirection.equals(this._cachedDirection)) {
  4452. this._cachedPosition = lightPosition.clone();
  4453. this._cachedDirection = lightDirection.clone();
  4454. var activeCamera = this._scene.activeCamera;
  4455. BABYLON.Matrix.LookAtLHToRef(lightPosition, this._light.position.add(lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  4456. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2.0, 1.0, activeCamera.minZ, activeCamera.maxZ, this._projectionMatrix);
  4457. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  4458. }
  4459. return this._transformMatrix;
  4460. };
  4461. ShadowGenerator.prototype.getDarkness = function () {
  4462. return this._darkness;
  4463. };
  4464. ShadowGenerator.prototype.setDarkness = function (darkness) {
  4465. if (darkness >= 1.0)
  4466. this._darkness = 1.0;
  4467. else if (darkness <= 0.0)
  4468. this._darkness = 0.0;
  4469. else
  4470. this._darkness = darkness;
  4471. };
  4472. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  4473. this._transparencyShadow = hasShadow;
  4474. };
  4475. ShadowGenerator.prototype.dispose = function () {
  4476. this._shadowMap.dispose();
  4477. };
  4478. ShadowGenerator._FILTER_NONE = 0;
  4479. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  4480. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  4481. return ShadowGenerator;
  4482. })();
  4483. BABYLON.ShadowGenerator = ShadowGenerator;
  4484. })(BABYLON || (BABYLON = {}));
  4485. var __extends = this.__extends || function (d, b) {
  4486. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  4487. function __() { this.constructor = d; }
  4488. __.prototype = b.prototype;
  4489. d.prototype = new __();
  4490. };
  4491. var BABYLON;
  4492. (function (BABYLON) {
  4493. var HemisphericLight = (function (_super) {
  4494. __extends(HemisphericLight, _super);
  4495. function HemisphericLight(name, direction, scene) {
  4496. _super.call(this, name, scene);
  4497. this.direction = direction;
  4498. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  4499. }
  4500. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  4501. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  4502. return this.direction;
  4503. };
  4504. HemisphericLight.prototype.getShadowGenerator = function () {
  4505. return null;
  4506. };
  4507. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  4508. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  4509. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  4510. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  4511. };
  4512. HemisphericLight.prototype._getWorldMatrix = function () {
  4513. if (!this._worldMatrix) {
  4514. this._worldMatrix = BABYLON.Matrix.Identity();
  4515. }
  4516. return this._worldMatrix;
  4517. };
  4518. return HemisphericLight;
  4519. })(BABYLON.Light);
  4520. BABYLON.HemisphericLight = HemisphericLight;
  4521. })(BABYLON || (BABYLON = {}));
  4522. var BABYLON;
  4523. (function (BABYLON) {
  4524. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  4525. if (boxMin.x > sphereCenter.x + sphereRadius)
  4526. return false;
  4527. if (sphereCenter.x - sphereRadius > boxMax.x)
  4528. return false;
  4529. if (boxMin.y > sphereCenter.y + sphereRadius)
  4530. return false;
  4531. if (sphereCenter.y - sphereRadius > boxMax.y)
  4532. return false;
  4533. if (boxMin.z > sphereCenter.z + sphereRadius)
  4534. return false;
  4535. if (sphereCenter.z - sphereRadius > boxMax.z)
  4536. return false;
  4537. return true;
  4538. };
  4539. var getLowestRoot = function (a, b, c, maxR) {
  4540. var determinant = b * b - 4.0 * a * c;
  4541. var result = { root: 0, found: false };
  4542. if (determinant < 0)
  4543. return result;
  4544. var sqrtD = Math.sqrt(determinant);
  4545. var r1 = (-b - sqrtD) / (2.0 * a);
  4546. var r2 = (-b + sqrtD) / (2.0 * a);
  4547. if (r1 > r2) {
  4548. var temp = r2;
  4549. r2 = r1;
  4550. r1 = temp;
  4551. }
  4552. if (r1 > 0 && r1 < maxR) {
  4553. result.root = r1;
  4554. result.found = true;
  4555. return result;
  4556. }
  4557. if (r2 > 0 && r2 < maxR) {
  4558. result.root = r2;
  4559. result.found = true;
  4560. return result;
  4561. }
  4562. return result;
  4563. };
  4564. var Collider = (function () {
  4565. function Collider() {
  4566. this.radius = new BABYLON.Vector3(1, 1, 1);
  4567. this.retry = 0;
  4568. this.basePointWorld = BABYLON.Vector3.Zero();
  4569. this.velocityWorld = BABYLON.Vector3.Zero();
  4570. this.normalizedVelocity = BABYLON.Vector3.Zero();
  4571. this._collisionPoint = BABYLON.Vector3.Zero();
  4572. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  4573. this._tempVector = BABYLON.Vector3.Zero();
  4574. this._tempVector2 = BABYLON.Vector3.Zero();
  4575. this._tempVector3 = BABYLON.Vector3.Zero();
  4576. this._tempVector4 = BABYLON.Vector3.Zero();
  4577. this._edge = BABYLON.Vector3.Zero();
  4578. this._baseToVertex = BABYLON.Vector3.Zero();
  4579. this._destinationPoint = BABYLON.Vector3.Zero();
  4580. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  4581. this._displacementVector = BABYLON.Vector3.Zero();
  4582. }
  4583. Collider.prototype._initialize = function (source, dir, e) {
  4584. this.velocity = dir;
  4585. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  4586. this.basePoint = source;
  4587. source.multiplyToRef(this.radius, this.basePointWorld);
  4588. dir.multiplyToRef(this.radius, this.velocityWorld);
  4589. this.velocityWorldLength = this.velocityWorld.length();
  4590. this.epsilon = e;
  4591. this.collisionFound = false;
  4592. };
  4593. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  4594. pa.subtractToRef(point, this._tempVector);
  4595. pb.subtractToRef(point, this._tempVector2);
  4596. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  4597. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  4598. if (d < 0)
  4599. return false;
  4600. pc.subtractToRef(point, this._tempVector3);
  4601. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  4602. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  4603. if (d < 0)
  4604. return false;
  4605. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  4606. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  4607. return d >= 0;
  4608. };
  4609. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  4610. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  4611. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  4612. if (distance > this.velocityWorldLength + max + sphereRadius) {
  4613. return false;
  4614. }
  4615. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  4616. return false;
  4617. return true;
  4618. };
  4619. Collider.prototype._testTriangle = function (faceIndex, subMesh, p1, p2, p3) {
  4620. var t0;
  4621. var embeddedInPlane = false;
  4622. if (!subMesh._trianglePlanes) {
  4623. subMesh._trianglePlanes = [];
  4624. }
  4625. if (!subMesh._trianglePlanes[faceIndex]) {
  4626. subMesh._trianglePlanes[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  4627. subMesh._trianglePlanes[faceIndex].copyFromPoints(p1, p2, p3);
  4628. }
  4629. var trianglePlane = subMesh._trianglePlanes[faceIndex];
  4630. if ((!subMesh.getMaterial()) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  4631. return;
  4632. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  4633. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  4634. if (normalDotVelocity == 0) {
  4635. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  4636. return;
  4637. embeddedInPlane = true;
  4638. t0 = 0;
  4639. } else {
  4640. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  4641. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  4642. if (t0 > t1) {
  4643. var temp = t1;
  4644. t1 = t0;
  4645. t0 = temp;
  4646. }
  4647. if (t0 > 1.0 || t1 < 0.0)
  4648. return;
  4649. if (t0 < 0)
  4650. t0 = 0;
  4651. if (t0 > 1.0)
  4652. t0 = 1.0;
  4653. }
  4654. this._collisionPoint.copyFromFloats(0, 0, 0);
  4655. var found = false;
  4656. var t = 1.0;
  4657. if (!embeddedInPlane) {
  4658. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  4659. this.velocity.scaleToRef(t0, this._tempVector);
  4660. this._planeIntersectionPoint.addInPlace(this._tempVector);
  4661. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  4662. found = true;
  4663. t = t0;
  4664. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  4665. }
  4666. }
  4667. if (!found) {
  4668. var velocitySquaredLength = this.velocity.lengthSquared();
  4669. var a = velocitySquaredLength;
  4670. this.basePoint.subtractToRef(p1, this._tempVector);
  4671. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  4672. var c = this._tempVector.lengthSquared() - 1.0;
  4673. var lowestRoot = getLowestRoot(a, b, c, t);
  4674. if (lowestRoot.found) {
  4675. t = lowestRoot.root;
  4676. found = true;
  4677. this._collisionPoint.copyFrom(p1);
  4678. }
  4679. this.basePoint.subtractToRef(p2, this._tempVector);
  4680. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  4681. c = this._tempVector.lengthSquared() - 1.0;
  4682. lowestRoot = getLowestRoot(a, b, c, t);
  4683. if (lowestRoot.found) {
  4684. t = lowestRoot.root;
  4685. found = true;
  4686. this._collisionPoint.copyFrom(p2);
  4687. }
  4688. this.basePoint.subtractToRef(p3, this._tempVector);
  4689. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  4690. c = this._tempVector.lengthSquared() - 1.0;
  4691. lowestRoot = getLowestRoot(a, b, c, t);
  4692. if (lowestRoot.found) {
  4693. t = lowestRoot.root;
  4694. found = true;
  4695. this._collisionPoint.copyFrom(p3);
  4696. }
  4697. p2.subtractToRef(p1, this._edge);
  4698. p1.subtractToRef(this.basePoint, this._baseToVertex);
  4699. var edgeSquaredLength = this._edge.lengthSquared();
  4700. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  4701. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  4702. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  4703. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  4704. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  4705. lowestRoot = getLowestRoot(a, b, c, t);
  4706. if (lowestRoot.found) {
  4707. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  4708. if (f >= 0.0 && f <= 1.0) {
  4709. t = lowestRoot.root;
  4710. found = true;
  4711. this._edge.scaleInPlace(f);
  4712. p1.addToRef(this._edge, this._collisionPoint);
  4713. }
  4714. }
  4715. p3.subtractToRef(p2, this._edge);
  4716. p2.subtractToRef(this.basePoint, this._baseToVertex);
  4717. edgeSquaredLength = this._edge.lengthSquared();
  4718. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  4719. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  4720. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  4721. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  4722. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  4723. lowestRoot = getLowestRoot(a, b, c, t);
  4724. if (lowestRoot.found) {
  4725. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  4726. if (f >= 0.0 && f <= 1.0) {
  4727. t = lowestRoot.root;
  4728. found = true;
  4729. this._edge.scaleInPlace(f);
  4730. p2.addToRef(this._edge, this._collisionPoint);
  4731. }
  4732. }
  4733. p1.subtractToRef(p3, this._edge);
  4734. p3.subtractToRef(this.basePoint, this._baseToVertex);
  4735. edgeSquaredLength = this._edge.lengthSquared();
  4736. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  4737. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  4738. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  4739. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  4740. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  4741. lowestRoot = getLowestRoot(a, b, c, t);
  4742. if (lowestRoot.found) {
  4743. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  4744. if (f >= 0.0 && f <= 1.0) {
  4745. t = lowestRoot.root;
  4746. found = true;
  4747. this._edge.scaleInPlace(f);
  4748. p3.addToRef(this._edge, this._collisionPoint);
  4749. }
  4750. }
  4751. }
  4752. if (found) {
  4753. var distToCollision = t * this.velocity.length();
  4754. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  4755. if (!this.intersectionPoint) {
  4756. this.intersectionPoint = this._collisionPoint.clone();
  4757. } else {
  4758. this.intersectionPoint.copyFrom(this._collisionPoint);
  4759. }
  4760. this.nearestDistance = distToCollision;
  4761. this.collisionFound = true;
  4762. this.collidedMesh = subMesh.getMesh();
  4763. }
  4764. }
  4765. };
  4766. Collider.prototype._collide = function (subMesh, pts, indices, indexStart, indexEnd, decal) {
  4767. for (var i = indexStart; i < indexEnd; i += 3) {
  4768. var p1 = pts[indices[i] - decal];
  4769. var p2 = pts[indices[i + 1] - decal];
  4770. var p3 = pts[indices[i + 2] - decal];
  4771. this._testTriangle(i, subMesh, p3, p2, p1);
  4772. }
  4773. };
  4774. Collider.prototype._getResponse = function (pos, vel) {
  4775. pos.addToRef(vel, this._destinationPoint);
  4776. vel.scaleInPlace((this.nearestDistance / vel.length()));
  4777. this.basePoint.addToRef(vel, pos);
  4778. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  4779. this._slidePlaneNormal.normalize();
  4780. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  4781. pos.addInPlace(this._displacementVector);
  4782. this.intersectionPoint.addInPlace(this._displacementVector);
  4783. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  4784. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  4785. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  4786. };
  4787. return Collider;
  4788. })();
  4789. BABYLON.Collider = Collider;
  4790. })(BABYLON || (BABYLON = {}));
  4791. var __extends = this.__extends || function (d, b) {
  4792. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  4793. function __() { this.constructor = d; }
  4794. __.prototype = b.prototype;
  4795. d.prototype = new __();
  4796. };
  4797. var BABYLON;
  4798. (function (BABYLON) {
  4799. var Camera = (function (_super) {
  4800. __extends(Camera, _super);
  4801. function Camera(name, position, scene) {
  4802. _super.call(this, name, scene);
  4803. this.position = position;
  4804. this.upVector = BABYLON.Vector3.Up();
  4805. this.orthoLeft = null;
  4806. this.orthoRight = null;
  4807. this.orthoBottom = null;
  4808. this.orthoTop = null;
  4809. this.fov = 0.8;
  4810. this.minZ = 1.0;
  4811. this.maxZ = 10000.0;
  4812. this.inertia = 0.9;
  4813. this.mode = Camera.PERSPECTIVE_CAMERA;
  4814. this.isIntermediate = false;
  4815. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  4816. this.subCameras = [];
  4817. this.layerMask = 0xFFFFFFFF;
  4818. this._computedViewMatrix = BABYLON.Matrix.Identity();
  4819. this._projectionMatrix = new BABYLON.Matrix();
  4820. this._postProcesses = new Array();
  4821. this._postProcessesTakenIndices = [];
  4822. scene.cameras.push(this);
  4823. if (!scene.activeCamera) {
  4824. scene.activeCamera = this;
  4825. }
  4826. }
  4827. Camera.prototype._initCache = function () {
  4828. _super.prototype._initCache.call(this);
  4829. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4830. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4831. this._cache.mode = undefined;
  4832. this._cache.minZ = undefined;
  4833. this._cache.maxZ = undefined;
  4834. this._cache.fov = undefined;
  4835. this._cache.aspectRatio = undefined;
  4836. this._cache.orthoLeft = undefined;
  4837. this._cache.orthoRight = undefined;
  4838. this._cache.orthoBottom = undefined;
  4839. this._cache.orthoTop = undefined;
  4840. this._cache.renderWidth = undefined;
  4841. this._cache.renderHeight = undefined;
  4842. };
  4843. Camera.prototype._updateCache = function (ignoreParentClass) {
  4844. if (!ignoreParentClass) {
  4845. _super.prototype._updateCache.call(this);
  4846. }
  4847. var engine = this.getEngine();
  4848. this._cache.position.copyFrom(this.position);
  4849. this._cache.upVector.copyFrom(this.upVector);
  4850. this._cache.mode = this.mode;
  4851. this._cache.minZ = this.minZ;
  4852. this._cache.maxZ = this.maxZ;
  4853. this._cache.fov = this.fov;
  4854. this._cache.aspectRatio = engine.getAspectRatio(this);
  4855. this._cache.orthoLeft = this.orthoLeft;
  4856. this._cache.orthoRight = this.orthoRight;
  4857. this._cache.orthoBottom = this.orthoBottom;
  4858. this._cache.orthoTop = this.orthoTop;
  4859. this._cache.renderWidth = engine.getRenderWidth();
  4860. this._cache.renderHeight = engine.getRenderHeight();
  4861. };
  4862. Camera.prototype._updateFromScene = function () {
  4863. this.updateCache();
  4864. this._update();
  4865. };
  4866. Camera.prototype._isSynchronized = function () {
  4867. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  4868. };
  4869. Camera.prototype._isSynchronizedViewMatrix = function () {
  4870. if (!_super.prototype._isSynchronized.call(this))
  4871. return false;
  4872. return this._cache.position.equals(this.position) && this._cache.upVector.equals(this.upVector) && this.isSynchronizedWithParent();
  4873. };
  4874. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  4875. var check = this._cache.mode === this.mode && this._cache.minZ === this.minZ && this._cache.maxZ === this.maxZ;
  4876. if (!check) {
  4877. return false;
  4878. }
  4879. var engine = this.getEngine();
  4880. if (this.mode === BABYLON.Camera.PERSPECTIVE_CAMERA) {
  4881. check = this._cache.fov === this.fov && this._cache.aspectRatio === engine.getAspectRatio(this);
  4882. } else {
  4883. 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();
  4884. }
  4885. return check;
  4886. };
  4887. Camera.prototype.attachControl = function (element) {
  4888. };
  4889. Camera.prototype.detachControl = function (element) {
  4890. };
  4891. Camera.prototype._update = function () {
  4892. };
  4893. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  4894. if (typeof insertAt === "undefined") { insertAt = null; }
  4895. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  4896. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  4897. return 0;
  4898. }
  4899. if (insertAt == null || insertAt < 0) {
  4900. this._postProcesses.push(postProcess);
  4901. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  4902. return this._postProcesses.length - 1;
  4903. }
  4904. var add = 0;
  4905. if (this._postProcesses[insertAt]) {
  4906. var start = this._postProcesses.length - 1;
  4907. for (var i = start; i >= insertAt + 1; --i) {
  4908. this._postProcesses[i + 1] = this._postProcesses[i];
  4909. }
  4910. add = 1;
  4911. }
  4912. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  4913. if (this._postProcessesTakenIndices[i] < insertAt) {
  4914. continue;
  4915. }
  4916. start = this._postProcessesTakenIndices.length - 1;
  4917. for (var j = start; j >= i; --j) {
  4918. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  4919. }
  4920. this._postProcessesTakenIndices[i] = insertAt;
  4921. break;
  4922. }
  4923. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) == -1) {
  4924. this._postProcessesTakenIndices.push(insertAt);
  4925. }
  4926. var result = insertAt + add;
  4927. this._postProcesses[result] = postProcess;
  4928. return result;
  4929. };
  4930. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  4931. if (typeof atIndices === "undefined") { atIndices = null; }
  4932. var result = [];
  4933. if (!atIndices) {
  4934. var length = this._postProcesses.length;
  4935. for (var i = 0; i < length; i++) {
  4936. if (this._postProcesses[i] !== postProcess) {
  4937. continue;
  4938. }
  4939. delete this._postProcesses[i];
  4940. var index = this._postProcessesTakenIndices.indexOf(i);
  4941. this._postProcessesTakenIndices.splice(index, 1);
  4942. }
  4943. } else {
  4944. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  4945. for (i = 0; i < atIndices.length; i++) {
  4946. var foundPostProcess = this._postProcesses[atIndices[i]];
  4947. if (foundPostProcess !== postProcess) {
  4948. result.push(i);
  4949. continue;
  4950. }
  4951. delete this._postProcesses[atIndices[i]];
  4952. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  4953. this._postProcessesTakenIndices.splice(index, 1);
  4954. }
  4955. }
  4956. return result;
  4957. };
  4958. Camera.prototype.getWorldMatrix = function () {
  4959. if (!this._worldMatrix) {
  4960. this._worldMatrix = BABYLON.Matrix.Identity();
  4961. }
  4962. var viewMatrix = this.getViewMatrix();
  4963. viewMatrix.invertToRef(this._worldMatrix);
  4964. return this._worldMatrix;
  4965. };
  4966. Camera.prototype._getViewMatrix = function () {
  4967. return BABYLON.Matrix.Identity();
  4968. };
  4969. Camera.prototype.getViewMatrix = function () {
  4970. this._computedViewMatrix = this._computeViewMatrix();
  4971. if (!this.parent || !this.parent.getWorldMatrix || this.isSynchronized()) {
  4972. return this._computedViewMatrix;
  4973. }
  4974. if (!this._worldMatrix) {
  4975. this._worldMatrix = BABYLON.Matrix.Identity();
  4976. }
  4977. this._computedViewMatrix.invertToRef(this._worldMatrix);
  4978. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  4979. this._computedViewMatrix.invert();
  4980. this._currentRenderId = this.getScene().getRenderId();
  4981. return this._computedViewMatrix;
  4982. };
  4983. Camera.prototype._computeViewMatrix = function (force) {
  4984. if (!force && this._isSynchronizedViewMatrix()) {
  4985. return this._computedViewMatrix;
  4986. }
  4987. this._computedViewMatrix = this._getViewMatrix();
  4988. if (!this.parent || !this.parent.getWorldMatrix) {
  4989. this._currentRenderId = this.getScene().getRenderId();
  4990. }
  4991. return this._computedViewMatrix;
  4992. };
  4993. Camera.prototype.getProjectionMatrix = function (force) {
  4994. if (!force && this._isSynchronizedProjectionMatrix()) {
  4995. return this._projectionMatrix;
  4996. }
  4997. var engine = this.getEngine();
  4998. if (this.mode === BABYLON.Camera.PERSPECTIVE_CAMERA) {
  4999. if (this.minZ <= 0) {
  5000. this.minZ = 0.1;
  5001. }
  5002. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix);
  5003. return this._projectionMatrix;
  5004. }
  5005. var halfWidth = engine.getRenderWidth() / 2.0;
  5006. var halfHeight = engine.getRenderHeight() / 2.0;
  5007. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  5008. return this._projectionMatrix;
  5009. };
  5010. Camera.prototype.dispose = function () {
  5011. var index = this.getScene().cameras.indexOf(this);
  5012. this.getScene().cameras.splice(index, 1);
  5013. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  5014. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  5015. }
  5016. };
  5017. Camera.PERSPECTIVE_CAMERA = 0;
  5018. Camera.ORTHOGRAPHIC_CAMERA = 1;
  5019. return Camera;
  5020. })(BABYLON.Node);
  5021. BABYLON.Camera = Camera;
  5022. })(BABYLON || (BABYLON = {}));
  5023. var __extends = this.__extends || function (d, b) {
  5024. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  5025. function __() { this.constructor = d; }
  5026. __.prototype = b.prototype;
  5027. d.prototype = new __();
  5028. };
  5029. var BABYLON;
  5030. (function (BABYLON) {
  5031. var TargetCamera = (function (_super) {
  5032. __extends(TargetCamera, _super);
  5033. function TargetCamera(name, position, scene) {
  5034. _super.call(this, name, position, scene);
  5035. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  5036. this.cameraRotation = new BABYLON.Vector2(0, 0);
  5037. this.rotation = new BABYLON.Vector3(0, 0, 0);
  5038. this.speed = 2.0;
  5039. this.noRotationConstraint = false;
  5040. this.lockedTarget = null;
  5041. this._currentTarget = BABYLON.Vector3.Zero();
  5042. this._viewMatrix = BABYLON.Matrix.Zero();
  5043. this._camMatrix = BABYLON.Matrix.Zero();
  5044. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  5045. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  5046. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  5047. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  5048. this._lookAtTemp = BABYLON.Matrix.Zero();
  5049. this._tempMatrix = BABYLON.Matrix.Zero();
  5050. }
  5051. TargetCamera.prototype._getLockedTargetPosition = function () {
  5052. if (!this.lockedTarget) {
  5053. return null;
  5054. }
  5055. return this.lockedTarget.position || this.lockedTarget;
  5056. };
  5057. TargetCamera.prototype._initCache = function () {
  5058. _super.prototype._initCache.call(this);
  5059. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5060. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5061. };
  5062. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  5063. if (!ignoreParentClass) {
  5064. _super.prototype._updateCache.call(this);
  5065. }
  5066. var lockedTargetPosition = this._getLockedTargetPosition();
  5067. if (!lockedTargetPosition) {
  5068. this._cache.lockedTarget = null;
  5069. } else {
  5070. if (!this._cache.lockedTarget) {
  5071. this._cache.lockedTarget = lockedTargetPosition.clone();
  5072. } else {
  5073. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  5074. }
  5075. }
  5076. this._cache.rotation.copyFrom(this.rotation);
  5077. };
  5078. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  5079. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  5080. return false;
  5081. }
  5082. var lockedTargetPosition = this._getLockedTargetPosition();
  5083. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition) && this._cache.rotation.equals(this.rotation);
  5084. };
  5085. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  5086. return this.speed * ((BABYLON.Tools.GetDeltaTime() / (BABYLON.Tools.GetFps() * 10.0)));
  5087. };
  5088. TargetCamera.prototype.setTarget = function (target) {
  5089. this.upVector.normalize();
  5090. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  5091. this._camMatrix.invert();
  5092. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  5093. var vDir = target.subtract(this.position);
  5094. if (vDir.x >= 0.0) {
  5095. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  5096. } else {
  5097. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  5098. }
  5099. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  5100. if (isNaN(this.rotation.x)) {
  5101. this.rotation.x = 0;
  5102. }
  5103. if (isNaN(this.rotation.y)) {
  5104. this.rotation.y = 0;
  5105. }
  5106. if (isNaN(this.rotation.z)) {
  5107. this.rotation.z = 0;
  5108. }
  5109. };
  5110. TargetCamera.prototype.getTarget = function () {
  5111. return this._currentTarget;
  5112. };
  5113. TargetCamera.prototype._decideIfNeedsToMove = function () {
  5114. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  5115. };
  5116. TargetCamera.prototype._updatePosition = function () {
  5117. this.position.addInPlace(this.cameraDirection);
  5118. };
  5119. TargetCamera.prototype._update = function () {
  5120. var needToMove = this._decideIfNeedsToMove();
  5121. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  5122. if (needToMove) {
  5123. this._updatePosition();
  5124. }
  5125. if (needToRotate) {
  5126. this.rotation.x += this.cameraRotation.x;
  5127. this.rotation.y += this.cameraRotation.y;
  5128. if (!this.noRotationConstraint) {
  5129. var limit = (Math.PI / 2) * 0.95;
  5130. if (this.rotation.x > limit)
  5131. this.rotation.x = limit;
  5132. if (this.rotation.x < -limit)
  5133. this.rotation.x = -limit;
  5134. }
  5135. }
  5136. if (needToMove) {
  5137. if (Math.abs(this.cameraDirection.x) < BABYLON.Engine.Epsilon) {
  5138. this.cameraDirection.x = 0;
  5139. }
  5140. if (Math.abs(this.cameraDirection.y) < BABYLON.Engine.Epsilon) {
  5141. this.cameraDirection.y = 0;
  5142. }
  5143. if (Math.abs(this.cameraDirection.z) < BABYLON.Engine.Epsilon) {
  5144. this.cameraDirection.z = 0;
  5145. }
  5146. this.cameraDirection.scaleInPlace(this.inertia);
  5147. }
  5148. if (needToRotate) {
  5149. if (Math.abs(this.cameraRotation.x) < BABYLON.Engine.Epsilon) {
  5150. this.cameraRotation.x = 0;
  5151. }
  5152. if (Math.abs(this.cameraRotation.y) < BABYLON.Engine.Epsilon) {
  5153. this.cameraRotation.y = 0;
  5154. }
  5155. this.cameraRotation.scaleInPlace(this.inertia);
  5156. }
  5157. };
  5158. TargetCamera.prototype._getViewMatrix = function () {
  5159. if (!this.lockedTarget) {
  5160. if (this.upVector.x != 0 || this.upVector.y != 1.0 || this.upVector.z != 0) {
  5161. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  5162. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  5163. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  5164. this._lookAtTemp.invert();
  5165. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  5166. } else {
  5167. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  5168. }
  5169. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  5170. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  5171. } else {
  5172. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  5173. }
  5174. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  5175. return this._viewMatrix;
  5176. };
  5177. return TargetCamera;
  5178. })(BABYLON.Camera);
  5179. BABYLON.TargetCamera = TargetCamera;
  5180. })(BABYLON || (BABYLON = {}));
  5181. var __extends = this.__extends || function (d, b) {
  5182. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  5183. function __() { this.constructor = d; }
  5184. __.prototype = b.prototype;
  5185. d.prototype = new __();
  5186. };
  5187. var BABYLON;
  5188. (function (BABYLON) {
  5189. var FollowCamera = (function (_super) {
  5190. __extends(FollowCamera, _super);
  5191. function FollowCamera(name, position, scene) {
  5192. _super.call(this, name, position, scene);
  5193. this.radius = 12;
  5194. this.rotationOffset = 0;
  5195. this.heightOffset = 4;
  5196. this.cameraAcceleration = 0.05;
  5197. this.maxCameraSpeed = 20;
  5198. }
  5199. FollowCamera.prototype.getRadians = function (degrees) {
  5200. return degrees * Math.PI / 180;
  5201. };
  5202. FollowCamera.prototype.follow = function (cameraTarget) {
  5203. if (!cameraTarget)
  5204. return;
  5205. var radians = this.getRadians(this.rotationOffset) + cameraTarget.rotation.y;
  5206. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  5207. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  5208. var dx = targetX - this.position.x;
  5209. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  5210. var dz = (targetZ) - this.position.z;
  5211. var vx = dx * this.cameraAcceleration * 2;
  5212. var vy = dy * this.cameraAcceleration;
  5213. var vz = dz * this.cameraAcceleration * 2;
  5214. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  5215. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  5216. }
  5217. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  5218. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  5219. }
  5220. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  5221. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  5222. }
  5223. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  5224. this.setTarget(cameraTarget.position);
  5225. };
  5226. FollowCamera.prototype._update = function () {
  5227. _super.prototype._update.call(this);
  5228. this.follow(this.target);
  5229. };
  5230. return FollowCamera;
  5231. })(BABYLON.TargetCamera);
  5232. BABYLON.FollowCamera = FollowCamera;
  5233. })(BABYLON || (BABYLON = {}));
  5234. var __extends = this.__extends || function (d, b) {
  5235. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  5236. function __() { this.constructor = d; }
  5237. __.prototype = b.prototype;
  5238. d.prototype = new __();
  5239. };
  5240. var BABYLON;
  5241. (function (BABYLON) {
  5242. var FreeCamera = (function (_super) {
  5243. __extends(FreeCamera, _super);
  5244. function FreeCamera(name, position, scene) {
  5245. _super.call(this, name, position, scene);
  5246. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  5247. this.keysUp = [38];
  5248. this.keysDown = [40];
  5249. this.keysLeft = [37];
  5250. this.keysRight = [39];
  5251. this.checkCollisions = false;
  5252. this.applyGravity = false;
  5253. this.angularSensibility = 2000.0;
  5254. this._keys = [];
  5255. this._collider = new BABYLON.Collider();
  5256. this._needMoveForGravity = true;
  5257. this._oldPosition = BABYLON.Vector3.Zero();
  5258. this._diffPosition = BABYLON.Vector3.Zero();
  5259. this._newPosition = BABYLON.Vector3.Zero();
  5260. }
  5261. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  5262. var _this = this;
  5263. var previousPosition;
  5264. var engine = this.getEngine();
  5265. if (this._attachedElement) {
  5266. return;
  5267. }
  5268. this._attachedElement = element;
  5269. if (this._onMouseDown === undefined) {
  5270. this._onMouseDown = function (evt) {
  5271. previousPosition = {
  5272. x: evt.clientX,
  5273. y: evt.clientY
  5274. };
  5275. if (!noPreventDefault) {
  5276. evt.preventDefault();
  5277. }
  5278. };
  5279. this._onMouseUp = function (evt) {
  5280. previousPosition = null;
  5281. if (!noPreventDefault) {
  5282. evt.preventDefault();
  5283. }
  5284. };
  5285. this._onMouseOut = function (evt) {
  5286. previousPosition = null;
  5287. _this._keys = [];
  5288. if (!noPreventDefault) {
  5289. evt.preventDefault();
  5290. }
  5291. };
  5292. this._onMouseMove = function (evt) {
  5293. if (!previousPosition && !engine.isPointerLock) {
  5294. return;
  5295. }
  5296. var offsetX;
  5297. var offsetY;
  5298. if (!engine.isPointerLock) {
  5299. offsetX = evt.clientX - previousPosition.x;
  5300. offsetY = evt.clientY - previousPosition.y;
  5301. } else {
  5302. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  5303. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  5304. }
  5305. _this.cameraRotation.y += offsetX / _this.angularSensibility;
  5306. _this.cameraRotation.x += offsetY / _this.angularSensibility;
  5307. previousPosition = {
  5308. x: evt.clientX,
  5309. y: evt.clientY
  5310. };
  5311. if (!noPreventDefault) {
  5312. evt.preventDefault();
  5313. }
  5314. };
  5315. this._onKeyDown = function (evt) {
  5316. 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) {
  5317. var index = _this._keys.indexOf(evt.keyCode);
  5318. if (index === -1) {
  5319. _this._keys.push(evt.keyCode);
  5320. }
  5321. if (!noPreventDefault) {
  5322. evt.preventDefault();
  5323. }
  5324. }
  5325. };
  5326. this._onKeyUp = function (evt) {
  5327. 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) {
  5328. var index = _this._keys.indexOf(evt.keyCode);
  5329. if (index >= 0) {
  5330. _this._keys.splice(index, 1);
  5331. }
  5332. if (!noPreventDefault) {
  5333. evt.preventDefault();
  5334. }
  5335. }
  5336. };
  5337. this._onLostFocus = function () {
  5338. _this._keys = [];
  5339. };
  5340. this._reset = function () {
  5341. _this._keys = [];
  5342. previousPosition = null;
  5343. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  5344. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  5345. };
  5346. }
  5347. element.addEventListener("mousedown", this._onMouseDown, false);
  5348. element.addEventListener("mouseup", this._onMouseUp, false);
  5349. element.addEventListener("mouseout", this._onMouseOut, false);
  5350. element.addEventListener("mousemove", this._onMouseMove, false);
  5351. BABYLON.Tools.RegisterTopRootEvents([
  5352. { name: "keydown", handler: this._onKeyDown },
  5353. { name: "keyup", handler: this._onKeyUp },
  5354. { name: "blur", handler: this._onLostFocus }
  5355. ]);
  5356. };
  5357. FreeCamera.prototype.detachControl = function (element) {
  5358. if (this._attachedElement != element) {
  5359. return;
  5360. }
  5361. element.removeEventListener("mousedown", this._onMouseDown);
  5362. element.removeEventListener("mouseup", this._onMouseUp);
  5363. element.removeEventListener("mouseout", this._onMouseOut);
  5364. element.removeEventListener("mousemove", this._onMouseMove);
  5365. BABYLON.Tools.UnregisterTopRootEvents([
  5366. { name: "keydown", handler: this._onKeyDown },
  5367. { name: "keyup", handler: this._onKeyUp },
  5368. { name: "blur", handler: this._onLostFocus }
  5369. ]);
  5370. this._attachedElement = null;
  5371. if (this._reset) {
  5372. this._reset();
  5373. }
  5374. };
  5375. FreeCamera.prototype._collideWithWorld = function (velocity) {
  5376. var globalPosition;
  5377. if (this.parent) {
  5378. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  5379. } else {
  5380. globalPosition = this.position;
  5381. }
  5382. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  5383. this._collider.radius = this.ellipsoid;
  5384. this.getScene()._getNewPosition(this._oldPosition, velocity, this._collider, 3, this._newPosition);
  5385. this._newPosition.subtractToRef(this._oldPosition, this._diffPosition);
  5386. if (this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  5387. this.position.addInPlace(this._diffPosition);
  5388. if (this.onCollide) {
  5389. this.onCollide(this._collider.collidedMesh);
  5390. }
  5391. }
  5392. };
  5393. FreeCamera.prototype._checkInputs = function () {
  5394. if (!this._localDirection) {
  5395. this._localDirection = BABYLON.Vector3.Zero();
  5396. this._transformedDirection = BABYLON.Vector3.Zero();
  5397. }
  5398. for (var index = 0; index < this._keys.length; index++) {
  5399. var keyCode = this._keys[index];
  5400. var speed = this._computeLocalCameraSpeed();
  5401. if (this.keysLeft.indexOf(keyCode) !== -1) {
  5402. this._localDirection.copyFromFloats(-speed, 0, 0);
  5403. } else if (this.keysUp.indexOf(keyCode) !== -1) {
  5404. this._localDirection.copyFromFloats(0, 0, speed);
  5405. } else if (this.keysRight.indexOf(keyCode) !== -1) {
  5406. this._localDirection.copyFromFloats(speed, 0, 0);
  5407. } else if (this.keysDown.indexOf(keyCode) !== -1) {
  5408. this._localDirection.copyFromFloats(0, 0, -speed);
  5409. }
  5410. this.getViewMatrix().invertToRef(this._cameraTransformMatrix);
  5411. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  5412. this.cameraDirection.addInPlace(this._transformedDirection);
  5413. }
  5414. };
  5415. FreeCamera.prototype._decideIfNeedsToMove = function () {
  5416. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  5417. };
  5418. FreeCamera.prototype._updatePosition = function () {
  5419. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  5420. this._collideWithWorld(this.cameraDirection);
  5421. if (this.applyGravity) {
  5422. var oldPosition = this.position;
  5423. this._collideWithWorld(this.getScene().gravity);
  5424. this._needMoveForGravity = (BABYLON.Vector3.DistanceSquared(oldPosition, this.position) != 0);
  5425. }
  5426. } else {
  5427. this.position.addInPlace(this.cameraDirection);
  5428. }
  5429. };
  5430. FreeCamera.prototype._update = function () {
  5431. this._checkInputs();
  5432. _super.prototype._update.call(this);
  5433. };
  5434. return FreeCamera;
  5435. })(BABYLON.TargetCamera);
  5436. BABYLON.FreeCamera = FreeCamera;
  5437. })(BABYLON || (BABYLON = {}));
  5438. var __extends = this.__extends || function (d, b) {
  5439. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  5440. function __() { this.constructor = d; }
  5441. __.prototype = b.prototype;
  5442. d.prototype = new __();
  5443. };
  5444. var BABYLON;
  5445. (function (BABYLON) {
  5446. var TouchCamera = (function (_super) {
  5447. __extends(TouchCamera, _super);
  5448. function TouchCamera(name, position, scene) {
  5449. _super.call(this, name, position, scene);
  5450. this._offsetX = null;
  5451. this._offsetY = null;
  5452. this._pointerCount = 0;
  5453. this._pointerPressed = [];
  5454. this.angularSensibility = 200000.0;
  5455. this.moveSensibility = 500.0;
  5456. }
  5457. TouchCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  5458. var _this = this;
  5459. var previousPosition;
  5460. if (this._attachedCanvas) {
  5461. return;
  5462. }
  5463. this._attachedCanvas = canvas;
  5464. if (this._onPointerDown === undefined) {
  5465. this._onPointerDown = function (evt) {
  5466. if (!noPreventDefault) {
  5467. evt.preventDefault();
  5468. }
  5469. _this._pointerPressed.push(evt.pointerId);
  5470. if (_this._pointerPressed.length !== 1) {
  5471. return;
  5472. }
  5473. previousPosition = {
  5474. x: evt.clientX,
  5475. y: evt.clientY
  5476. };
  5477. };
  5478. this._onPointerUp = function (evt) {
  5479. if (!noPreventDefault) {
  5480. evt.preventDefault();
  5481. }
  5482. var index = _this._pointerPressed.indexOf(evt.pointerId);
  5483. if (index === -1) {
  5484. return;
  5485. }
  5486. _this._pointerPressed.splice(index, 1);
  5487. if (index != 0) {
  5488. return;
  5489. }
  5490. previousPosition = null;
  5491. _this._offsetX = null;
  5492. _this._offsetY = null;
  5493. };
  5494. this._onPointerMove = function (evt) {
  5495. if (!noPreventDefault) {
  5496. evt.preventDefault();
  5497. }
  5498. if (!previousPosition) {
  5499. return;
  5500. }
  5501. var index = _this._pointerPressed.indexOf(evt.pointerId);
  5502. if (index != 0) {
  5503. return;
  5504. }
  5505. _this._offsetX = evt.clientX - previousPosition.x;
  5506. _this._offsetY = -(evt.clientY - previousPosition.y);
  5507. };
  5508. this._onLostFocus = function () {
  5509. _this._offsetX = null;
  5510. _this._offsetY = null;
  5511. };
  5512. }
  5513. canvas.addEventListener("pointerdown", this._onPointerDown);
  5514. canvas.addEventListener("pointerup", this._onPointerUp);
  5515. canvas.addEventListener("pointerout", this._onPointerUp);
  5516. canvas.addEventListener("pointermove", this._onPointerMove);
  5517. BABYLON.Tools.RegisterTopRootEvents([
  5518. { name: "blur", handler: this._onLostFocus }
  5519. ]);
  5520. };
  5521. TouchCamera.prototype.detachControl = function (canvas) {
  5522. if (this._attachedCanvas != canvas) {
  5523. return;
  5524. }
  5525. canvas.removeEventListener("pointerdown", this._onPointerDown);
  5526. canvas.removeEventListener("pointerup", this._onPointerUp);
  5527. canvas.removeEventListener("pointerout", this._onPointerUp);
  5528. canvas.removeEventListener("pointermove", this._onPointerMove);
  5529. BABYLON.Tools.UnregisterTopRootEvents([
  5530. { name: "blur", handler: this._onLostFocus }
  5531. ]);
  5532. this._attachedCanvas = null;
  5533. };
  5534. TouchCamera.prototype._checkInputs = function () {
  5535. if (!this._offsetX) {
  5536. return;
  5537. }
  5538. this.cameraRotation.y += this._offsetX / this.angularSensibility;
  5539. if (this._pointerPressed.length > 1) {
  5540. this.cameraRotation.x += -this._offsetY / this.angularSensibility;
  5541. } else {
  5542. var speed = this._computeLocalCameraSpeed();
  5543. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  5544. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  5545. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  5546. }
  5547. };
  5548. return TouchCamera;
  5549. })(BABYLON.FreeCamera);
  5550. BABYLON.TouchCamera = TouchCamera;
  5551. })(BABYLON || (BABYLON = {}));
  5552. var __extends = this.__extends || function (d, b) {
  5553. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  5554. function __() { this.constructor = d; }
  5555. __.prototype = b.prototype;
  5556. d.prototype = new __();
  5557. };
  5558. var BABYLON;
  5559. (function (BABYLON) {
  5560. var DeviceOrientationCamera = (function (_super) {
  5561. __extends(DeviceOrientationCamera, _super);
  5562. function DeviceOrientationCamera(name, position, scene) {
  5563. var _this = this;
  5564. _super.call(this, name, position, scene);
  5565. this._offsetX = null;
  5566. this._offsetY = null;
  5567. this._orientationGamma = 0;
  5568. this._orientationBeta = 0;
  5569. this._initialOrientationGamma = 0;
  5570. this._initialOrientationBeta = 0;
  5571. this.angularSensibility = 10000.0;
  5572. this.moveSensibility = 50.0;
  5573. window.addEventListener("resize", function () {
  5574. _this._initialOrientationGamma = null;
  5575. }, false);
  5576. }
  5577. DeviceOrientationCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  5578. var _this = this;
  5579. if (this._attachedCanvas) {
  5580. return;
  5581. }
  5582. this._attachedCanvas = canvas;
  5583. if (!this._orientationChanged) {
  5584. this._orientationChanged = function (evt) {
  5585. if (!_this._initialOrientationGamma) {
  5586. _this._initialOrientationGamma = evt.gamma;
  5587. _this._initialOrientationBeta = evt.beta;
  5588. }
  5589. _this._orientationGamma = evt.gamma;
  5590. _this._orientationBeta = evt.beta;
  5591. _this._offsetY = (_this._initialOrientationBeta - _this._orientationBeta);
  5592. _this._offsetX = (_this._initialOrientationGamma - _this._orientationGamma);
  5593. };
  5594. }
  5595. window.addEventListener("deviceorientation", this._orientationChanged);
  5596. };
  5597. DeviceOrientationCamera.prototype.detachControl = function (canvas) {
  5598. if (this._attachedCanvas != canvas) {
  5599. return;
  5600. }
  5601. window.removeEventListener("deviceorientation", this._orientationChanged);
  5602. this._attachedCanvas = null;
  5603. this._orientationGamma = 0;
  5604. this._orientationBeta = 0;
  5605. this._initialOrientationGamma = 0;
  5606. this._initialOrientationBeta = 0;
  5607. };
  5608. DeviceOrientationCamera.prototype._checkInputs = function () {
  5609. if (!this._offsetX) {
  5610. return;
  5611. }
  5612. this.cameraRotation.y -= this._offsetX / this.angularSensibility;
  5613. var speed = this._computeLocalCameraSpeed();
  5614. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  5615. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  5616. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  5617. };
  5618. return DeviceOrientationCamera;
  5619. })(BABYLON.FreeCamera);
  5620. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  5621. })(BABYLON || (BABYLON = {}));
  5622. var __extends = this.__extends || function (d, b) {
  5623. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  5624. function __() { this.constructor = d; }
  5625. __.prototype = b.prototype;
  5626. d.prototype = new __();
  5627. };
  5628. var BABYLON;
  5629. (function (BABYLON) {
  5630. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  5631. var ArcRotateCamera = (function (_super) {
  5632. __extends(ArcRotateCamera, _super);
  5633. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  5634. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  5635. this.alpha = alpha;
  5636. this.beta = beta;
  5637. this.radius = radius;
  5638. this.target = target;
  5639. this.inertialAlphaOffset = 0;
  5640. this.inertialBetaOffset = 0;
  5641. this.inertialRadiusOffset = 0;
  5642. this.lowerAlphaLimit = null;
  5643. this.upperAlphaLimit = null;
  5644. this.lowerBetaLimit = 0.01;
  5645. this.upperBetaLimit = Math.PI;
  5646. this.lowerRadiusLimit = null;
  5647. this.upperRadiusLimit = null;
  5648. this.angularSensibility = 1000.0;
  5649. this.wheelPrecision = 3.0;
  5650. this.keysUp = [38];
  5651. this.keysDown = [40];
  5652. this.keysLeft = [37];
  5653. this.keysRight = [39];
  5654. this.zoomOnFactor = 1;
  5655. this._keys = [];
  5656. this._viewMatrix = new BABYLON.Matrix();
  5657. this.checkCollisions = false;
  5658. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  5659. this._collider = new BABYLON.Collider();
  5660. this._previousPosition = BABYLON.Vector3.Zero();
  5661. this._collisionVelocity = BABYLON.Vector3.Zero();
  5662. this._newPosition = BABYLON.Vector3.Zero();
  5663. this.pinchPrecision = 20;
  5664. this.getViewMatrix();
  5665. }
  5666. ArcRotateCamera.prototype._getTargetPosition = function () {
  5667. return this.target.position || this.target;
  5668. };
  5669. ArcRotateCamera.prototype._initCache = function () {
  5670. _super.prototype._initCache.call(this);
  5671. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5672. this._cache.alpha = undefined;
  5673. this._cache.beta = undefined;
  5674. this._cache.radius = undefined;
  5675. };
  5676. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  5677. if (!ignoreParentClass) {
  5678. _super.prototype._updateCache.call(this);
  5679. }
  5680. this._cache.target.copyFrom(this._getTargetPosition());
  5681. this._cache.alpha = this.alpha;
  5682. this._cache.beta = this.beta;
  5683. this._cache.radius = this.radius;
  5684. };
  5685. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  5686. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  5687. return false;
  5688. return this._cache.target.equals(this._getTargetPosition()) && this._cache.alpha === this.alpha && this._cache.beta === this.beta && this._cache.radius === this.radius;
  5689. };
  5690. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault) {
  5691. var _this = this;
  5692. var previousPosition;
  5693. var pointerId;
  5694. var pinchStarted = false;
  5695. var pinchPointX1, pinchPointX2;
  5696. if (this._attachedElement) {
  5697. return;
  5698. }
  5699. this._attachedElement = element;
  5700. var engine = this.getEngine();
  5701. if (this._onPointerDown === undefined) {
  5702. this._onPointerDown = function (evt) {
  5703. if (pointerId) {
  5704. return;
  5705. }
  5706. pointerId = evt.pointerId;
  5707. previousPosition = {
  5708. x: evt.clientX,
  5709. y: evt.clientY
  5710. };
  5711. if (!noPreventDefault) {
  5712. evt.preventDefault();
  5713. }
  5714. };
  5715. this._onPointerUp = function (evt) {
  5716. previousPosition = null;
  5717. pointerId = null;
  5718. if (!noPreventDefault) {
  5719. evt.preventDefault();
  5720. }
  5721. };
  5722. this._onPointerMove = function (evt) {
  5723. if (!previousPosition) {
  5724. return;
  5725. }
  5726. if (pointerId !== evt.pointerId) {
  5727. return;
  5728. }
  5729. if (pinchStarted) {
  5730. return;
  5731. }
  5732. var offsetX = evt.clientX - previousPosition.x;
  5733. var offsetY = evt.clientY - previousPosition.y;
  5734. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  5735. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  5736. previousPosition = {
  5737. x: evt.clientX,
  5738. y: evt.clientY
  5739. };
  5740. if (!noPreventDefault) {
  5741. evt.preventDefault();
  5742. }
  5743. };
  5744. this._onMouseMove = function (evt) {
  5745. if (!engine.isPointerLock) {
  5746. return;
  5747. }
  5748. if (pinchStarted) {
  5749. return;
  5750. }
  5751. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  5752. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  5753. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  5754. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  5755. if (!noPreventDefault) {
  5756. evt.preventDefault();
  5757. }
  5758. };
  5759. this._wheel = function (event) {
  5760. var delta = 0;
  5761. if (event.wheelDelta) {
  5762. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  5763. } else if (event.detail) {
  5764. delta = -event.detail / _this.wheelPrecision;
  5765. }
  5766. if (delta)
  5767. _this.inertialRadiusOffset += delta;
  5768. if (event.preventDefault) {
  5769. if (!noPreventDefault) {
  5770. event.preventDefault();
  5771. }
  5772. }
  5773. };
  5774. this._onKeyDown = function (evt) {
  5775. 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) {
  5776. var index = _this._keys.indexOf(evt.keyCode);
  5777. if (index === -1) {
  5778. _this._keys.push(evt.keyCode);
  5779. }
  5780. if (evt.preventDefault) {
  5781. if (!noPreventDefault) {
  5782. evt.preventDefault();
  5783. }
  5784. }
  5785. }
  5786. };
  5787. this._onKeyUp = function (evt) {
  5788. 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) {
  5789. var index = _this._keys.indexOf(evt.keyCode);
  5790. if (index >= 0) {
  5791. _this._keys.splice(index, 1);
  5792. }
  5793. if (evt.preventDefault) {
  5794. if (!noPreventDefault) {
  5795. evt.preventDefault();
  5796. }
  5797. }
  5798. }
  5799. };
  5800. this._onLostFocus = function () {
  5801. _this._keys = [];
  5802. pointerId = null;
  5803. };
  5804. this._onGestureStart = function (e) {
  5805. if (window.MSGesture === undefined) {
  5806. return;
  5807. }
  5808. if (!_this._MSGestureHandler) {
  5809. _this._MSGestureHandler = new MSGesture();
  5810. _this._MSGestureHandler.target = element;
  5811. }
  5812. _this._MSGestureHandler.addPointer(e.pointerId);
  5813. };
  5814. this._onGesture = function (e) {
  5815. _this.radius *= e.scale;
  5816. if (e.preventDefault) {
  5817. if (!noPreventDefault) {
  5818. e.stopPropagation();
  5819. e.preventDefault();
  5820. }
  5821. }
  5822. };
  5823. this._reset = function () {
  5824. _this._keys = [];
  5825. _this.inertialAlphaOffset = 0;
  5826. _this.inertialBetaOffset = 0;
  5827. _this.inertialRadiusOffset = 0;
  5828. previousPosition = null;
  5829. pointerId = null;
  5830. };
  5831. this._touchStart = function (event) {
  5832. if (event.touches.length == 2) {
  5833. pinchStarted = true;
  5834. _this._pinchStart(event);
  5835. }
  5836. };
  5837. this._touchMove = function (event) {
  5838. if (pinchStarted) {
  5839. _this._pinchMove(event);
  5840. }
  5841. };
  5842. this._touchEnd = function (event) {
  5843. if (pinchStarted) {
  5844. _this._pinchEnd(event);
  5845. }
  5846. };
  5847. this._pinchStart = function (event) {
  5848. pinchPointX1 = event.touches[0].clientX;
  5849. pinchPointX2 = event.touches[1].clientX;
  5850. pinchStarted = true;
  5851. };
  5852. this._pinchMove = function (event) {
  5853. var delta = 0;
  5854. var direction = 1;
  5855. var distanceXOrigine, distanceXNow;
  5856. if (event.touches.length != 2)
  5857. return;
  5858. distanceXOrigine = Math.abs(pinchPointX1 - pinchPointX2);
  5859. distanceXNow = Math.abs(event.touches[0].clientX - event.touches[1].clientX);
  5860. if (distanceXNow < distanceXOrigine) {
  5861. direction = -1;
  5862. }
  5863. delta = (_this.pinchPrecision / (_this.wheelPrecision * 40)) * direction;
  5864. _this.inertialRadiusOffset += delta;
  5865. pinchPointX1 = event.touches[0].clientX;
  5866. pinchPointX2 = event.touches[1].clientX;
  5867. };
  5868. this._pinchEnd = function (event) {
  5869. pinchStarted = false;
  5870. };
  5871. }
  5872. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  5873. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  5874. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  5875. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  5876. element.addEventListener("mousemove", this._onMouseMove, false);
  5877. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  5878. element.addEventListener("MSGestureChange", this._onGesture, false);
  5879. element.addEventListener('mousewheel', this._wheel, false);
  5880. element.addEventListener('DOMMouseScroll', this._wheel, false);
  5881. element.addEventListener('touchstart', this._touchStart, false);
  5882. element.addEventListener('touchmove', this._touchMove, false);
  5883. element.addEventListener('touchend', this._touchEnd, false);
  5884. BABYLON.Tools.RegisterTopRootEvents([
  5885. { name: "keydown", handler: this._onKeyDown },
  5886. { name: "keyup", handler: this._onKeyUp },
  5887. { name: "blur", handler: this._onLostFocus }
  5888. ]);
  5889. };
  5890. ArcRotateCamera.prototype.detachControl = function (element) {
  5891. if (this._attachedElement != element) {
  5892. return;
  5893. }
  5894. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  5895. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  5896. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  5897. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  5898. element.removeEventListener("mousemove", this._onMouseMove);
  5899. element.removeEventListener("MSPointerDown", this._onGestureStart);
  5900. element.removeEventListener("MSGestureChange", this._onGesture);
  5901. element.removeEventListener('mousewheel', this._wheel);
  5902. element.removeEventListener('DOMMouseScroll', this._wheel);
  5903. element.removeEventListener('touchstart', this._touchStart);
  5904. element.removeEventListener('touchmove', this._touchMove);
  5905. element.removeEventListener('touchend', this._touchEnd);
  5906. BABYLON.Tools.UnregisterTopRootEvents([
  5907. { name: "keydown", handler: this._onKeyDown },
  5908. { name: "keyup", handler: this._onKeyUp },
  5909. { name: "blur", handler: this._onLostFocus }
  5910. ]);
  5911. this._MSGestureHandler = null;
  5912. this._attachedElement = null;
  5913. if (this._reset) {
  5914. this._reset();
  5915. }
  5916. };
  5917. ArcRotateCamera.prototype._update = function () {
  5918. for (var index = 0; index < this._keys.length; index++) {
  5919. var keyCode = this._keys[index];
  5920. if (this.keysLeft.indexOf(keyCode) !== -1) {
  5921. this.inertialAlphaOffset -= 0.01;
  5922. } else if (this.keysUp.indexOf(keyCode) !== -1) {
  5923. this.inertialBetaOffset -= 0.01;
  5924. } else if (this.keysRight.indexOf(keyCode) !== -1) {
  5925. this.inertialAlphaOffset += 0.01;
  5926. } else if (this.keysDown.indexOf(keyCode) !== -1) {
  5927. this.inertialBetaOffset += 0.01;
  5928. }
  5929. }
  5930. if (this.inertialAlphaOffset != 0 || this.inertialBetaOffset != 0 || this.inertialRadiusOffset != 0) {
  5931. this.alpha += this.inertialAlphaOffset;
  5932. this.beta += this.inertialBetaOffset;
  5933. this.radius -= this.inertialRadiusOffset;
  5934. this.inertialAlphaOffset *= this.inertia;
  5935. this.inertialBetaOffset *= this.inertia;
  5936. this.inertialRadiusOffset *= this.inertia;
  5937. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Engine.Epsilon)
  5938. this.inertialAlphaOffset = 0;
  5939. if (Math.abs(this.inertialBetaOffset) < BABYLON.Engine.Epsilon)
  5940. this.inertialBetaOffset = 0;
  5941. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Engine.Epsilon)
  5942. this.inertialRadiusOffset = 0;
  5943. }
  5944. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  5945. this.alpha = this.lowerAlphaLimit;
  5946. }
  5947. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  5948. this.alpha = this.upperAlphaLimit;
  5949. }
  5950. if (this.lowerBetaLimit && this.beta < this.lowerBetaLimit) {
  5951. this.beta = this.lowerBetaLimit;
  5952. }
  5953. if (this.upperBetaLimit && this.beta > this.upperBetaLimit) {
  5954. this.beta = this.upperBetaLimit;
  5955. }
  5956. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  5957. this.radius = this.lowerRadiusLimit;
  5958. }
  5959. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  5960. this.radius = this.upperRadiusLimit;
  5961. }
  5962. };
  5963. ArcRotateCamera.prototype.setPosition = function (position) {
  5964. var radiusv3 = position.subtract(this._getTargetPosition());
  5965. this.radius = radiusv3.length();
  5966. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  5967. if (radiusv3.z < 0) {
  5968. this.alpha = 2 * Math.PI - this.alpha;
  5969. }
  5970. this.beta = Math.acos(radiusv3.y / this.radius);
  5971. };
  5972. ArcRotateCamera.prototype._getViewMatrix = function () {
  5973. var cosa = Math.cos(this.alpha);
  5974. var sina = Math.sin(this.alpha);
  5975. var cosb = Math.cos(this.beta);
  5976. var sinb = Math.sin(this.beta);
  5977. var target = this._getTargetPosition();
  5978. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this.position);
  5979. if (this.checkCollisions) {
  5980. this._collider.radius = this.collisionRadius;
  5981. this.position.subtractToRef(this._previousPosition, this._collisionVelocity);
  5982. this.getScene()._getNewPosition(this._previousPosition, this._collisionVelocity, this._collider, 3, this._newPosition);
  5983. if (!this._newPosition.equalsWithEpsilon(this.position)) {
  5984. this.position.copyFrom(this._previousPosition);
  5985. this.alpha = this._previousAlpha;
  5986. this.beta = this._previousBeta;
  5987. this.radius = this._previousRadius;
  5988. if (this.onCollide) {
  5989. this.onCollide(this._collider.collidedMesh);
  5990. }
  5991. }
  5992. }
  5993. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._viewMatrix);
  5994. this._previousAlpha = this.alpha;
  5995. this._previousBeta = this.beta;
  5996. this._previousRadius = this.radius;
  5997. this._previousPosition.copyFrom(this.position);
  5998. return this._viewMatrix;
  5999. };
  6000. ArcRotateCamera.prototype.zoomOn = function (meshes) {
  6001. meshes = meshes || this.getScene().meshes;
  6002. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  6003. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  6004. this.radius = distance * this.zoomOnFactor;
  6005. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance });
  6006. };
  6007. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance) {
  6008. var meshesOrMinMaxVector;
  6009. var distance;
  6010. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  6011. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  6012. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  6013. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  6014. } else {
  6015. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  6016. distance = meshesOrMinMaxVectorAndDistance.distance;
  6017. }
  6018. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  6019. this.maxZ = distance * 2;
  6020. };
  6021. return ArcRotateCamera;
  6022. })(BABYLON.Camera);
  6023. BABYLON.ArcRotateCamera = ArcRotateCamera;
  6024. })(BABYLON || (BABYLON = {}));
  6025. var BABYLON;
  6026. (function (BABYLON) {
  6027. var Scene = (function () {
  6028. function Scene(engine) {
  6029. this.autoClear = true;
  6030. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  6031. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  6032. this.forceWireframe = false;
  6033. this.cameraToUseForPointers = null;
  6034. this.fogMode = BABYLON.Scene.FOGMODE_NONE;
  6035. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  6036. this.fogDensity = 0.1;
  6037. this.fogStart = 0;
  6038. this.fogEnd = 1000.0;
  6039. this.lightsEnabled = true;
  6040. this.lights = new Array();
  6041. this.cameras = new Array();
  6042. this.activeCameras = new Array();
  6043. this.meshes = new Array();
  6044. this._geometries = new Array();
  6045. this.materials = new Array();
  6046. this.multiMaterials = new Array();
  6047. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  6048. this.texturesEnabled = true;
  6049. this.textures = new Array();
  6050. this.particlesEnabled = true;
  6051. this.particleSystems = new Array();
  6052. this.spriteManagers = new Array();
  6053. this.layers = new Array();
  6054. this.skeletons = new Array();
  6055. this.lensFlareSystems = new Array();
  6056. this.collisionsEnabled = true;
  6057. this.gravity = new BABYLON.Vector3(0, -9.0, 0);
  6058. this.postProcessesEnabled = true;
  6059. this.renderTargetsEnabled = true;
  6060. this.customRenderTargets = new Array();
  6061. this.importedMeshesFiles = new Array();
  6062. this._actionManagers = new Array();
  6063. this._meshesForIntersections = new BABYLON.SmartArray(256);
  6064. this.proceduralTexturesEnabled = true;
  6065. this._proceduralTextures = new Array();
  6066. this._totalVertices = 0;
  6067. this._activeVertices = 0;
  6068. this._activeParticles = 0;
  6069. this._lastFrameDuration = 0;
  6070. this._evaluateActiveMeshesDuration = 0;
  6071. this._renderTargetsDuration = 0;
  6072. this._particlesDuration = 0;
  6073. this._renderDuration = 0;
  6074. this._spritesDuration = 0;
  6075. this._animationRatio = 0;
  6076. this._renderId = 0;
  6077. this._executeWhenReadyTimeoutId = -1;
  6078. this._toBeDisposed = new BABYLON.SmartArray(256);
  6079. this._onReadyCallbacks = new Array();
  6080. this._pendingData = [];
  6081. this._onBeforeRenderCallbacks = new Array();
  6082. this._activeMeshes = new BABYLON.SmartArray(256);
  6083. this._processedMaterials = new BABYLON.SmartArray(256);
  6084. this._renderTargets = new BABYLON.SmartArray(256);
  6085. this._activeParticleSystems = new BABYLON.SmartArray(256);
  6086. this._activeSkeletons = new BABYLON.SmartArray(32);
  6087. this._activeAnimatables = new Array();
  6088. this._transformMatrix = BABYLON.Matrix.Zero();
  6089. this._scaledPosition = BABYLON.Vector3.Zero();
  6090. this._scaledVelocity = BABYLON.Vector3.Zero();
  6091. this._engine = engine;
  6092. engine.scenes.push(this);
  6093. this._renderingManager = new BABYLON.RenderingManager(this);
  6094. this.postProcessManager = new BABYLON.PostProcessManager(this);
  6095. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  6096. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  6097. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  6098. this.attachControl();
  6099. }
  6100. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  6101. get: function () {
  6102. return this._meshUnderPointer;
  6103. },
  6104. enumerable: true,
  6105. configurable: true
  6106. });
  6107. Object.defineProperty(Scene.prototype, "pointerX", {
  6108. get: function () {
  6109. return this._pointerX;
  6110. },
  6111. enumerable: true,
  6112. configurable: true
  6113. });
  6114. Object.defineProperty(Scene.prototype, "pointerY", {
  6115. get: function () {
  6116. return this._pointerY;
  6117. },
  6118. enumerable: true,
  6119. configurable: true
  6120. });
  6121. Scene.prototype.getBoundingBoxRenderer = function () {
  6122. return this._boundingBoxRenderer;
  6123. };
  6124. Scene.prototype.getOutlineRenderer = function () {
  6125. return this._outlineRenderer;
  6126. };
  6127. Scene.prototype.getEngine = function () {
  6128. return this._engine;
  6129. };
  6130. Scene.prototype.getTotalVertices = function () {
  6131. return this._totalVertices;
  6132. };
  6133. Scene.prototype.getActiveVertices = function () {
  6134. return this._activeVertices;
  6135. };
  6136. Scene.prototype.getActiveParticles = function () {
  6137. return this._activeParticles;
  6138. };
  6139. Scene.prototype.getLastFrameDuration = function () {
  6140. return this._lastFrameDuration;
  6141. };
  6142. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  6143. return this._evaluateActiveMeshesDuration;
  6144. };
  6145. Scene.prototype.getActiveMeshes = function () {
  6146. return this._activeMeshes;
  6147. };
  6148. Scene.prototype.getRenderTargetsDuration = function () {
  6149. return this._renderTargetsDuration;
  6150. };
  6151. Scene.prototype.getRenderDuration = function () {
  6152. return this._renderDuration;
  6153. };
  6154. Scene.prototype.getParticlesDuration = function () {
  6155. return this._particlesDuration;
  6156. };
  6157. Scene.prototype.getSpritesDuration = function () {
  6158. return this._spritesDuration;
  6159. };
  6160. Scene.prototype.getAnimationRatio = function () {
  6161. return this._animationRatio;
  6162. };
  6163. Scene.prototype.getRenderId = function () {
  6164. return this._renderId;
  6165. };
  6166. Scene.prototype._updatePointerPosition = function (evt) {
  6167. var canvasRect = this._engine.getRenderingCanvasClientRect();
  6168. this._pointerX = evt.clientX - canvasRect.left;
  6169. this._pointerY = evt.clientY - canvasRect.top;
  6170. if (this.cameraToUseForPointers) {
  6171. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  6172. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  6173. }
  6174. };
  6175. Scene.prototype.attachControl = function () {
  6176. var _this = this;
  6177. this._onPointerMove = function (evt) {
  6178. var canvas = _this._engine.getRenderingCanvas();
  6179. _this._updatePointerPosition(evt);
  6180. var pickResult = _this.pick(_this._pointerX, _this._pointerY, function (mesh) {
  6181. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPointerTriggers;
  6182. }, false, _this.cameraToUseForPointers);
  6183. if (pickResult.hit) {
  6184. _this._meshUnderPointer = pickResult.pickedMesh;
  6185. _this.setPointerOverMesh(pickResult.pickedMesh);
  6186. canvas.style.cursor = "pointer";
  6187. } else {
  6188. _this.setPointerOverMesh(null);
  6189. canvas.style.cursor = "";
  6190. _this._meshUnderPointer = null;
  6191. }
  6192. };
  6193. this._onPointerDown = function (evt) {
  6194. var predicate = null;
  6195. if (!_this.onPointerDown) {
  6196. predicate = function (mesh) {
  6197. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPickTriggers;
  6198. };
  6199. }
  6200. _this._updatePointerPosition(evt);
  6201. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  6202. if (pickResult.hit) {
  6203. if (pickResult.pickedMesh.actionManager) {
  6204. switch (evt.button) {
  6205. case 0:
  6206. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh));
  6207. break;
  6208. case 1:
  6209. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh));
  6210. break;
  6211. case 2:
  6212. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh));
  6213. break;
  6214. }
  6215. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh));
  6216. }
  6217. }
  6218. if (_this.onPointerDown) {
  6219. _this.onPointerDown(evt, pickResult);
  6220. }
  6221. };
  6222. this._onKeyDown = function (evt) {
  6223. if (_this.actionManager) {
  6224. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  6225. }
  6226. };
  6227. this._onKeyUp = function (evt) {
  6228. if (_this.actionManager) {
  6229. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  6230. }
  6231. };
  6232. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  6233. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  6234. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  6235. window.addEventListener("keydown", this._onKeyDown, false);
  6236. window.addEventListener("keyup", this._onKeyUp, false);
  6237. };
  6238. Scene.prototype.detachControl = function () {
  6239. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  6240. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  6241. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  6242. window.removeEventListener("keydown", this._onKeyDown);
  6243. window.removeEventListener("keyup", this._onKeyUp);
  6244. };
  6245. Scene.prototype.isReady = function () {
  6246. if (this._pendingData.length > 0) {
  6247. return false;
  6248. }
  6249. for (var index = 0; index < this._geometries.length; index++) {
  6250. var geometry = this._geometries[index];
  6251. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  6252. return false;
  6253. }
  6254. }
  6255. for (index = 0; index < this.meshes.length; index++) {
  6256. var mesh = this.meshes[index];
  6257. if (!mesh.isReady()) {
  6258. return false;
  6259. }
  6260. var mat = mesh.material;
  6261. if (mat) {
  6262. if (!mat.isReady(mesh)) {
  6263. return false;
  6264. }
  6265. }
  6266. }
  6267. return true;
  6268. };
  6269. Scene.prototype.registerBeforeRender = function (func) {
  6270. this._onBeforeRenderCallbacks.push(func);
  6271. };
  6272. Scene.prototype.unregisterBeforeRender = function (func) {
  6273. var index = this._onBeforeRenderCallbacks.indexOf(func);
  6274. if (index > -1) {
  6275. this._onBeforeRenderCallbacks.splice(index, 1);
  6276. }
  6277. };
  6278. Scene.prototype._addPendingData = function (data) {
  6279. this._pendingData.push(data);
  6280. };
  6281. Scene.prototype._removePendingData = function (data) {
  6282. var index = this._pendingData.indexOf(data);
  6283. if (index !== -1) {
  6284. this._pendingData.splice(index, 1);
  6285. }
  6286. };
  6287. Scene.prototype.getWaitingItemsCount = function () {
  6288. return this._pendingData.length;
  6289. };
  6290. Scene.prototype.executeWhenReady = function (func) {
  6291. var _this = this;
  6292. this._onReadyCallbacks.push(func);
  6293. if (this._executeWhenReadyTimeoutId !== -1) {
  6294. return;
  6295. }
  6296. this._executeWhenReadyTimeoutId = setTimeout(function () {
  6297. _this._checkIsReady();
  6298. }, 150);
  6299. };
  6300. Scene.prototype._checkIsReady = function () {
  6301. var _this = this;
  6302. if (this.isReady()) {
  6303. this._onReadyCallbacks.forEach(function (func) {
  6304. func();
  6305. });
  6306. this._onReadyCallbacks = [];
  6307. this._executeWhenReadyTimeoutId = -1;
  6308. return;
  6309. }
  6310. this._executeWhenReadyTimeoutId = setTimeout(function () {
  6311. _this._checkIsReady();
  6312. }, 150);
  6313. };
  6314. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  6315. if (speedRatio === undefined) {
  6316. speedRatio = 1.0;
  6317. }
  6318. this.stopAnimation(target);
  6319. if (!animatable) {
  6320. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  6321. }
  6322. if (target.animations) {
  6323. animatable.appendAnimations(target, target.animations);
  6324. }
  6325. if (target.getAnimatables) {
  6326. var animatables = target.getAnimatables();
  6327. for (var index = 0; index < animatables.length; index++) {
  6328. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  6329. }
  6330. }
  6331. return animatable;
  6332. };
  6333. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  6334. if (speedRatio === undefined) {
  6335. speedRatio = 1.0;
  6336. }
  6337. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  6338. return animatable;
  6339. };
  6340. Scene.prototype.getAnimatableByTarget = function (target) {
  6341. for (var index = 0; index < this._activeAnimatables.length; index++) {
  6342. if (this._activeAnimatables[index].target === target) {
  6343. return this._activeAnimatables[index];
  6344. }
  6345. }
  6346. return null;
  6347. };
  6348. Scene.prototype.stopAnimation = function (target) {
  6349. var animatable = this.getAnimatableByTarget(target);
  6350. if (animatable) {
  6351. animatable.stop();
  6352. }
  6353. };
  6354. Scene.prototype._animate = function () {
  6355. if (!this._animationStartDate) {
  6356. this._animationStartDate = new Date().getTime();
  6357. }
  6358. var now = new Date().getTime();
  6359. var delay = now - this._animationStartDate;
  6360. for (var index = 0; index < this._activeAnimatables.length; index++) {
  6361. if (!this._activeAnimatables[index]._animate(delay)) {
  6362. this._activeAnimatables.splice(index, 1);
  6363. index--;
  6364. }
  6365. }
  6366. };
  6367. Scene.prototype.getViewMatrix = function () {
  6368. return this._viewMatrix;
  6369. };
  6370. Scene.prototype.getProjectionMatrix = function () {
  6371. return this._projectionMatrix;
  6372. };
  6373. Scene.prototype.getTransformMatrix = function () {
  6374. return this._transformMatrix;
  6375. };
  6376. Scene.prototype.setTransformMatrix = function (view, projection) {
  6377. this._viewMatrix = view;
  6378. this._projectionMatrix = projection;
  6379. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  6380. };
  6381. Scene.prototype.setActiveCameraByID = function (id) {
  6382. var camera = this.getCameraByID(id);
  6383. if (camera) {
  6384. this.activeCamera = camera;
  6385. return camera;
  6386. }
  6387. return null;
  6388. };
  6389. Scene.prototype.setActiveCameraByName = function (name) {
  6390. var camera = this.getCameraByName(name);
  6391. if (camera) {
  6392. this.activeCamera = camera;
  6393. return camera;
  6394. }
  6395. return null;
  6396. };
  6397. Scene.prototype.getMaterialByID = function (id) {
  6398. for (var index = 0; index < this.materials.length; index++) {
  6399. if (this.materials[index].id === id) {
  6400. return this.materials[index];
  6401. }
  6402. }
  6403. return null;
  6404. };
  6405. Scene.prototype.getMaterialByName = function (name) {
  6406. for (var index = 0; index < this.materials.length; index++) {
  6407. if (this.materials[index].name === name) {
  6408. return this.materials[index];
  6409. }
  6410. }
  6411. return null;
  6412. };
  6413. Scene.prototype.getCameraByID = function (id) {
  6414. for (var index = 0; index < this.cameras.length; index++) {
  6415. if (this.cameras[index].id === id) {
  6416. return this.cameras[index];
  6417. }
  6418. }
  6419. return null;
  6420. };
  6421. Scene.prototype.getCameraByName = function (name) {
  6422. for (var index = 0; index < this.cameras.length; index++) {
  6423. if (this.cameras[index].name === name) {
  6424. return this.cameras[index];
  6425. }
  6426. }
  6427. return null;
  6428. };
  6429. Scene.prototype.getLightByName = function (name) {
  6430. for (var index = 0; index < this.lights.length; index++) {
  6431. if (this.lights[index].name === name) {
  6432. return this.lights[index];
  6433. }
  6434. }
  6435. return null;
  6436. };
  6437. Scene.prototype.getLightByID = function (id) {
  6438. for (var index = 0; index < this.lights.length; index++) {
  6439. if (this.lights[index].id === id) {
  6440. return this.lights[index];
  6441. }
  6442. }
  6443. return null;
  6444. };
  6445. Scene.prototype.getGeometryByID = function (id) {
  6446. for (var index = 0; index < this._geometries.length; index++) {
  6447. if (this._geometries[index].id === id) {
  6448. return this._geometries[index];
  6449. }
  6450. }
  6451. return null;
  6452. };
  6453. Scene.prototype.pushGeometry = function (geometry, force) {
  6454. if (!force && this.getGeometryByID(geometry.id)) {
  6455. return false;
  6456. }
  6457. this._geometries.push(geometry);
  6458. return true;
  6459. };
  6460. Scene.prototype.getGeometries = function () {
  6461. return this._geometries;
  6462. };
  6463. Scene.prototype.getMeshByID = function (id) {
  6464. for (var index = 0; index < this.meshes.length; index++) {
  6465. if (this.meshes[index].id === id) {
  6466. return this.meshes[index];
  6467. }
  6468. }
  6469. return null;
  6470. };
  6471. Scene.prototype.getLastMeshByID = function (id) {
  6472. for (var index = this.meshes.length - 1; index >= 0; index--) {
  6473. if (this.meshes[index].id === id) {
  6474. return this.meshes[index];
  6475. }
  6476. }
  6477. return null;
  6478. };
  6479. Scene.prototype.getLastEntryByID = function (id) {
  6480. for (var index = this.meshes.length - 1; index >= 0; index--) {
  6481. if (this.meshes[index].id === id) {
  6482. return this.meshes[index];
  6483. }
  6484. }
  6485. for (index = this.cameras.length - 1; index >= 0; index--) {
  6486. if (this.cameras[index].id === id) {
  6487. return this.cameras[index];
  6488. }
  6489. }
  6490. for (index = this.lights.length - 1; index >= 0; index--) {
  6491. if (this.lights[index].id === id) {
  6492. return this.lights[index];
  6493. }
  6494. }
  6495. return null;
  6496. };
  6497. Scene.prototype.getMeshByName = function (name) {
  6498. for (var index = 0; index < this.meshes.length; index++) {
  6499. if (this.meshes[index].name === name) {
  6500. return this.meshes[index];
  6501. }
  6502. }
  6503. return null;
  6504. };
  6505. Scene.prototype.getLastSkeletonByID = function (id) {
  6506. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  6507. if (this.skeletons[index].id === id) {
  6508. return this.skeletons[index];
  6509. }
  6510. }
  6511. return null;
  6512. };
  6513. Scene.prototype.getSkeletonById = function (id) {
  6514. for (var index = 0; index < this.skeletons.length; index++) {
  6515. if (this.skeletons[index].id === id) {
  6516. return this.skeletons[index];
  6517. }
  6518. }
  6519. return null;
  6520. };
  6521. Scene.prototype.getSkeletonByName = function (name) {
  6522. for (var index = 0; index < this.skeletons.length; index++) {
  6523. if (this.skeletons[index].name === name) {
  6524. return this.skeletons[index];
  6525. }
  6526. }
  6527. return null;
  6528. };
  6529. Scene.prototype.isActiveMesh = function (mesh) {
  6530. return (this._activeMeshes.indexOf(mesh) !== -1);
  6531. };
  6532. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  6533. if (mesh.subMeshes.length == 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  6534. var material = subMesh.getMaterial();
  6535. if (mesh.showSubMeshesBoundingBox) {
  6536. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  6537. }
  6538. if (material) {
  6539. if (material.getRenderTargetTextures) {
  6540. if (this._processedMaterials.indexOf(material) === -1) {
  6541. this._processedMaterials.push(material);
  6542. this._renderTargets.concat(material.getRenderTargetTextures());
  6543. }
  6544. }
  6545. this._activeVertices += subMesh.verticesCount;
  6546. this._renderingManager.dispatch(subMesh);
  6547. }
  6548. }
  6549. };
  6550. Scene.prototype._evaluateActiveMeshes = function () {
  6551. this._activeMeshes.reset();
  6552. this._renderingManager.reset();
  6553. this._processedMaterials.reset();
  6554. this._activeParticleSystems.reset();
  6555. this._activeSkeletons.reset();
  6556. this._boundingBoxRenderer.reset();
  6557. if (!this._frustumPlanes) {
  6558. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  6559. } else {
  6560. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  6561. }
  6562. var meshes;
  6563. var len;
  6564. if (this._selectionOctree) {
  6565. var selection = this._selectionOctree.select(this._frustumPlanes);
  6566. meshes = selection.data;
  6567. len = selection.length;
  6568. } else {
  6569. len = this.meshes.length;
  6570. meshes = this.meshes;
  6571. }
  6572. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  6573. var mesh = meshes[meshIndex];
  6574. this._totalVertices += mesh.getTotalVertices();
  6575. if (!mesh.isReady()) {
  6576. continue;
  6577. }
  6578. mesh.computeWorldMatrix();
  6579. mesh._preActivate();
  6580. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  6581. this._meshesForIntersections.pushNoDuplicate(mesh);
  6582. }
  6583. if (mesh.isEnabled() && mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) != 0) && mesh.isInFrustum(this._frustumPlanes)) {
  6584. this._activeMeshes.push(mesh);
  6585. mesh._activate(this._renderId);
  6586. this._activeMesh(mesh);
  6587. }
  6588. }
  6589. var beforeParticlesDate = new Date().getTime();
  6590. if (this.particlesEnabled) {
  6591. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  6592. var particleSystem = this.particleSystems[particleIndex];
  6593. if (!particleSystem.isStarted()) {
  6594. continue;
  6595. }
  6596. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  6597. this._activeParticleSystems.push(particleSystem);
  6598. particleSystem.animate();
  6599. }
  6600. }
  6601. }
  6602. this._particlesDuration += new Date().getTime() - beforeParticlesDate;
  6603. };
  6604. Scene.prototype._activeMesh = function (mesh) {
  6605. if (mesh.skeleton) {
  6606. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  6607. }
  6608. if (mesh.showBoundingBox) {
  6609. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  6610. }
  6611. if (mesh.subMeshes) {
  6612. var len;
  6613. var subMeshes;
  6614. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  6615. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  6616. len = intersections.length;
  6617. subMeshes = intersections.data;
  6618. } else {
  6619. subMeshes = mesh.subMeshes;
  6620. len = subMeshes.length;
  6621. }
  6622. for (var subIndex = 0; subIndex < len; subIndex++) {
  6623. var subMesh = subMeshes[subIndex];
  6624. this._evaluateSubMesh(subMesh, mesh);
  6625. }
  6626. }
  6627. };
  6628. Scene.prototype.updateTransformMatrix = function (force) {
  6629. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  6630. };
  6631. Scene.prototype._renderForCamera = function (camera) {
  6632. var engine = this._engine;
  6633. this.activeCamera = camera;
  6634. if (!this.activeCamera)
  6635. throw new Error("Active camera not set");
  6636. engine.setViewport(this.activeCamera.viewport);
  6637. this._renderId++;
  6638. this.updateTransformMatrix();
  6639. if (this.beforeCameraRender) {
  6640. this.beforeCameraRender(this.activeCamera);
  6641. }
  6642. var beforeEvaluateActiveMeshesDate = new Date().getTime();
  6643. this._evaluateActiveMeshes();
  6644. this._evaluateActiveMeshesDuration += new Date().getTime() - beforeEvaluateActiveMeshesDate;
  6645. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  6646. var skeleton = this._activeSkeletons.data[skeletonIndex];
  6647. skeleton.prepare();
  6648. }
  6649. var beforeRenderTargetDate = new Date().getTime();
  6650. if (this.renderTargetsEnabled) {
  6651. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  6652. var renderTarget = this._renderTargets.data[renderIndex];
  6653. if (renderTarget._shouldRender()) {
  6654. this._renderId++;
  6655. renderTarget.render();
  6656. }
  6657. }
  6658. this._renderId++;
  6659. }
  6660. if (this._renderTargets.length > 0) {
  6661. engine.restoreDefaultFramebuffer();
  6662. }
  6663. this._renderTargetsDuration += new Date().getTime() - beforeRenderTargetDate;
  6664. this.postProcessManager._prepareFrame();
  6665. var beforeRenderDate = new Date().getTime();
  6666. if (this.layers.length) {
  6667. engine.setDepthBuffer(false);
  6668. var layerIndex;
  6669. var layer;
  6670. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  6671. layer = this.layers[layerIndex];
  6672. if (layer.isBackground) {
  6673. layer.render();
  6674. }
  6675. }
  6676. engine.setDepthBuffer(true);
  6677. }
  6678. this._renderingManager.render(null, null, true, true);
  6679. this._boundingBoxRenderer.render();
  6680. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  6681. this.lensFlareSystems[lensFlareSystemIndex].render();
  6682. }
  6683. if (this.layers.length) {
  6684. engine.setDepthBuffer(false);
  6685. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  6686. layer = this.layers[layerIndex];
  6687. if (!layer.isBackground) {
  6688. layer.render();
  6689. }
  6690. }
  6691. engine.setDepthBuffer(true);
  6692. }
  6693. this._renderDuration += new Date().getTime() - beforeRenderDate;
  6694. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  6695. this.activeCamera._updateFromScene();
  6696. this._renderTargets.reset();
  6697. if (this.afterCameraRender) {
  6698. this.afterCameraRender(this.activeCamera);
  6699. }
  6700. };
  6701. Scene.prototype._processSubCameras = function (camera) {
  6702. if (camera.subCameras.length == 0) {
  6703. this._renderForCamera(camera);
  6704. return;
  6705. }
  6706. for (var index = 0; index < camera.subCameras.length; index++) {
  6707. this._renderForCamera(camera.subCameras[index]);
  6708. }
  6709. this.activeCamera = camera;
  6710. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  6711. this.activeCamera._updateFromScene();
  6712. };
  6713. Scene.prototype._checkIntersections = function () {
  6714. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  6715. var sourceMesh = this._meshesForIntersections.data[index];
  6716. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  6717. var action = sourceMesh.actionManager.actions[actionIndex];
  6718. if (action.trigger == BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger == BABYLON.ActionManager.OnIntersectionExitTrigger) {
  6719. var otherMesh = action.getTriggerParameter();
  6720. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, false);
  6721. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  6722. if (areIntersecting && currentIntersectionInProgress === -1 && action.trigger == BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  6723. sourceMesh.actionManager.processTrigger(BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionEvent.CreateNew(sourceMesh));
  6724. sourceMesh._intersectionsInProgress.push(otherMesh);
  6725. } else if (!areIntersecting && currentIntersectionInProgress > -1 && action.trigger == BABYLON.ActionManager.OnIntersectionExitTrigger) {
  6726. sourceMesh.actionManager.processTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, BABYLON.ActionEvent.CreateNew(sourceMesh));
  6727. var indexOfOther = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  6728. if (indexOfOther > -1) {
  6729. sourceMesh._intersectionsInProgress.splice(indexOfOther, 1);
  6730. }
  6731. }
  6732. }
  6733. }
  6734. }
  6735. };
  6736. Scene.prototype.render = function () {
  6737. var startDate = new Date().getTime();
  6738. this._particlesDuration = 0;
  6739. this._spritesDuration = 0;
  6740. this._activeParticles = 0;
  6741. this._renderDuration = 0;
  6742. this._evaluateActiveMeshesDuration = 0;
  6743. this._totalVertices = 0;
  6744. this._activeVertices = 0;
  6745. this._meshesForIntersections.reset();
  6746. if (this.actionManager) {
  6747. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  6748. }
  6749. if (this.beforeRender) {
  6750. this.beforeRender();
  6751. }
  6752. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  6753. this._onBeforeRenderCallbacks[callbackIndex]();
  6754. }
  6755. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(BABYLON.Tools.GetDeltaTime(), Scene.MaxDeltaTime));
  6756. this._animationRatio = deltaTime * (60.0 / 1000.0);
  6757. this._animate();
  6758. if (this._physicsEngine) {
  6759. this._physicsEngine._runOneStep(deltaTime / 1000.0);
  6760. }
  6761. var beforeRenderTargetDate = new Date().getTime();
  6762. var engine = this.getEngine();
  6763. if (this.renderTargetsEnabled) {
  6764. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  6765. var renderTarget = this.customRenderTargets[customIndex];
  6766. if (renderTarget._shouldRender()) {
  6767. this._renderId++;
  6768. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  6769. if (!this.activeCamera)
  6770. throw new Error("Active camera not set");
  6771. engine.setViewport(this.activeCamera.viewport);
  6772. this.updateTransformMatrix();
  6773. renderTarget.render();
  6774. }
  6775. }
  6776. this._renderId++;
  6777. }
  6778. if (this.customRenderTargets.length > 0) {
  6779. engine.restoreDefaultFramebuffer();
  6780. }
  6781. this._renderTargetsDuration += new Date().getTime() - beforeRenderTargetDate;
  6782. if (this.proceduralTexturesEnabled) {
  6783. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  6784. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  6785. if (proceduralTexture._shouldRender()) {
  6786. proceduralTexture.render();
  6787. }
  6788. }
  6789. }
  6790. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe, true);
  6791. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  6792. var light = this.lights[lightIndex];
  6793. var shadowGenerator = light.getShadowGenerator();
  6794. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  6795. this._renderTargets.push(shadowGenerator.getShadowMap());
  6796. }
  6797. }
  6798. this.postProcessRenderPipelineManager.update();
  6799. if (this.activeCameras.length > 0) {
  6800. var currentRenderId = this._renderId;
  6801. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  6802. this._renderId = currentRenderId;
  6803. this._processSubCameras(this.activeCameras[cameraIndex]);
  6804. }
  6805. } else {
  6806. if (!this.activeCamera) {
  6807. throw new Error("No camera defined");
  6808. }
  6809. this._processSubCameras(this.activeCamera);
  6810. }
  6811. this._checkIntersections();
  6812. if (this.afterRender) {
  6813. this.afterRender();
  6814. }
  6815. for (var index = 0; index < this._toBeDisposed.length; index++) {
  6816. this._toBeDisposed.data[index].dispose();
  6817. this._toBeDisposed[index] = null;
  6818. }
  6819. this._toBeDisposed.reset();
  6820. this._lastFrameDuration = new Date().getTime() - startDate;
  6821. };
  6822. Scene.prototype.dispose = function () {
  6823. this.beforeRender = null;
  6824. this.afterRender = null;
  6825. this.skeletons = [];
  6826. this._boundingBoxRenderer.dispose();
  6827. if (this.onDispose) {
  6828. this.onDispose();
  6829. }
  6830. this.detachControl();
  6831. var canvas = this._engine.getRenderingCanvas();
  6832. var index;
  6833. for (index = 0; index < this.cameras.length; index++) {
  6834. this.cameras[index].detachControl(canvas);
  6835. }
  6836. while (this.lights.length) {
  6837. this.lights[0].dispose();
  6838. }
  6839. while (this.meshes.length) {
  6840. this.meshes[0].dispose(true);
  6841. }
  6842. while (this.cameras.length) {
  6843. this.cameras[0].dispose();
  6844. }
  6845. while (this.materials.length) {
  6846. this.materials[0].dispose();
  6847. }
  6848. while (this.particleSystems.length) {
  6849. this.particleSystems[0].dispose();
  6850. }
  6851. while (this.spriteManagers.length) {
  6852. this.spriteManagers[0].dispose();
  6853. }
  6854. while (this.layers.length) {
  6855. this.layers[0].dispose();
  6856. }
  6857. while (this.textures.length) {
  6858. this.textures[0].dispose();
  6859. }
  6860. this.postProcessManager.dispose();
  6861. if (this._physicsEngine) {
  6862. this.disablePhysicsEngine();
  6863. }
  6864. index = this._engine.scenes.indexOf(this);
  6865. if (index > -1) {
  6866. this._engine.scenes.splice(index, 1);
  6867. }
  6868. this._engine.wipeCaches();
  6869. };
  6870. Scene.prototype._getNewPosition = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  6871. if (typeof excludedMesh === "undefined") { excludedMesh = null; }
  6872. position.divideToRef(collider.radius, this._scaledPosition);
  6873. velocity.divideToRef(collider.radius, this._scaledVelocity);
  6874. collider.retry = 0;
  6875. collider.initialVelocity = this._scaledVelocity;
  6876. collider.initialPosition = this._scaledPosition;
  6877. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, finalPosition, excludedMesh);
  6878. finalPosition.multiplyInPlace(collider.radius);
  6879. };
  6880. Scene.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  6881. if (typeof excludedMesh === "undefined") { excludedMesh = null; }
  6882. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  6883. if (collider.retry >= maximumRetry) {
  6884. finalPosition.copyFrom(position);
  6885. return;
  6886. }
  6887. collider._initialize(position, velocity, closeDistance);
  6888. for (var index = 0; index < this.meshes.length; index++) {
  6889. var mesh = this.meshes[index];
  6890. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  6891. mesh._checkCollision(collider);
  6892. }
  6893. }
  6894. if (!collider.collisionFound) {
  6895. position.addToRef(velocity, finalPosition);
  6896. return;
  6897. }
  6898. if (velocity.x != 0 || velocity.y != 0 || velocity.z != 0) {
  6899. collider._getResponse(position, velocity);
  6900. }
  6901. if (velocity.length() <= closeDistance) {
  6902. finalPosition.copyFrom(position);
  6903. return;
  6904. }
  6905. collider.retry++;
  6906. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  6907. };
  6908. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  6909. if (typeof maxCapacity === "undefined") { maxCapacity = 64; }
  6910. if (typeof maxDepth === "undefined") { maxDepth = 2; }
  6911. if (!this._selectionOctree) {
  6912. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  6913. }
  6914. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6915. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  6916. for (var index = 0; index < this.meshes.length; index++) {
  6917. var mesh = this.meshes[index];
  6918. mesh.computeWorldMatrix(true);
  6919. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  6920. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  6921. BABYLON.Tools.CheckExtends(minBox, min, max);
  6922. BABYLON.Tools.CheckExtends(maxBox, min, max);
  6923. }
  6924. this._selectionOctree.update(min, max, this.meshes);
  6925. return this._selectionOctree;
  6926. };
  6927. Scene.prototype.createPickingRay = function (x, y, world, camera) {
  6928. var engine = this._engine;
  6929. if (!camera) {
  6930. if (!this.activeCamera)
  6931. throw new Error("Active camera not set");
  6932. camera = this.activeCamera;
  6933. }
  6934. var cameraViewport = camera.viewport;
  6935. var viewport = cameraViewport.toGlobal(engine);
  6936. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  6937. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  6938. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  6939. };
  6940. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  6941. var pickingInfo = null;
  6942. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  6943. var mesh = this.meshes[meshIndex];
  6944. if (predicate) {
  6945. if (!predicate(mesh)) {
  6946. continue;
  6947. }
  6948. } else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  6949. continue;
  6950. }
  6951. var world = mesh.getWorldMatrix();
  6952. var ray = rayFunction(world);
  6953. var result = mesh.intersects(ray, fastCheck);
  6954. if (!result || !result.hit)
  6955. continue;
  6956. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  6957. continue;
  6958. pickingInfo = result;
  6959. if (fastCheck) {
  6960. break;
  6961. }
  6962. }
  6963. return pickingInfo || new BABYLON.PickingInfo();
  6964. };
  6965. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  6966. var _this = this;
  6967. return this._internalPick(function (world) {
  6968. return _this.createPickingRay(x, y, world, camera);
  6969. }, predicate, fastCheck);
  6970. };
  6971. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  6972. var _this = this;
  6973. return this._internalPick(function (world) {
  6974. if (!_this._pickWithRayInverseMatrix) {
  6975. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  6976. }
  6977. world.invertToRef(_this._pickWithRayInverseMatrix);
  6978. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  6979. }, predicate, fastCheck);
  6980. };
  6981. Scene.prototype.setPointerOverMesh = function (mesh) {
  6982. if (this._pointerOverMesh === mesh) {
  6983. return;
  6984. }
  6985. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  6986. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  6987. }
  6988. this._pointerOverMesh = mesh;
  6989. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  6990. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  6991. }
  6992. };
  6993. Scene.prototype.getPointerOverMesh = function () {
  6994. return this._pointerOverMesh;
  6995. };
  6996. Scene.prototype.getPhysicsEngine = function () {
  6997. return this._physicsEngine;
  6998. };
  6999. Scene.prototype.enablePhysics = function (gravity, plugin) {
  7000. if (this._physicsEngine) {
  7001. return true;
  7002. }
  7003. this._physicsEngine = new BABYLON.PhysicsEngine(plugin);
  7004. if (!this._physicsEngine.isSupported()) {
  7005. this._physicsEngine = null;
  7006. return false;
  7007. }
  7008. this._physicsEngine._initialize(gravity);
  7009. return true;
  7010. };
  7011. Scene.prototype.disablePhysicsEngine = function () {
  7012. if (!this._physicsEngine) {
  7013. return;
  7014. }
  7015. this._physicsEngine.dispose();
  7016. this._physicsEngine = undefined;
  7017. };
  7018. Scene.prototype.isPhysicsEnabled = function () {
  7019. return this._physicsEngine !== undefined;
  7020. };
  7021. Scene.prototype.setGravity = function (gravity) {
  7022. if (!this._physicsEngine) {
  7023. return;
  7024. }
  7025. this._physicsEngine._setGravity(gravity);
  7026. };
  7027. Scene.prototype.createCompoundImpostor = function (parts, options) {
  7028. if (parts.parts) {
  7029. options = parts;
  7030. parts = parts.parts;
  7031. }
  7032. if (!this._physicsEngine) {
  7033. return null;
  7034. }
  7035. for (var index = 0; index < parts.length; index++) {
  7036. var mesh = parts[index].mesh;
  7037. mesh._physicImpostor = parts[index].impostor;
  7038. mesh._physicsMass = options.mass / parts.length;
  7039. mesh._physicsFriction = options.friction;
  7040. mesh._physicRestitution = options.restitution;
  7041. }
  7042. return this._physicsEngine._registerMeshesAsCompound(parts, options);
  7043. };
  7044. Scene.prototype.deleteCompoundImpostor = function (compound) {
  7045. for (var index = 0; index < compound.parts.length; index++) {
  7046. var mesh = compound.parts[index].mesh;
  7047. mesh._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  7048. this._physicsEngine._unregisterMesh(mesh);
  7049. }
  7050. };
  7051. Scene.prototype._getByTags = function (list, tagsQuery) {
  7052. if (tagsQuery === undefined) {
  7053. return list;
  7054. }
  7055. var listByTags = [];
  7056. for (var i in list) {
  7057. var item = list[i];
  7058. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  7059. listByTags.push(item);
  7060. }
  7061. }
  7062. return listByTags;
  7063. };
  7064. Scene.prototype.getMeshesByTags = function (tagsQuery) {
  7065. return this._getByTags(this.meshes, tagsQuery);
  7066. };
  7067. Scene.prototype.getCamerasByTags = function (tagsQuery) {
  7068. return this._getByTags(this.cameras, tagsQuery);
  7069. };
  7070. Scene.prototype.getLightsByTags = function (tagsQuery) {
  7071. return this._getByTags(this.lights, tagsQuery);
  7072. };
  7073. Scene.prototype.getMaterialByTags = function (tagsQuery) {
  7074. return this._getByTags(this.materials, tagsQuery).concat(this._getByTags(this.multiMaterials, tagsQuery));
  7075. };
  7076. Scene.FOGMODE_NONE = 0;
  7077. Scene.FOGMODE_EXP = 1;
  7078. Scene.FOGMODE_EXP2 = 2;
  7079. Scene.FOGMODE_LINEAR = 3;
  7080. Scene.MinDeltaTime = 1.0;
  7081. Scene.MaxDeltaTime = 1000.0;
  7082. return Scene;
  7083. })();
  7084. BABYLON.Scene = Scene;
  7085. })(BABYLON || (BABYLON = {}));
  7086. var BABYLON;
  7087. (function (BABYLON) {
  7088. var VertexBuffer = (function () {
  7089. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation) {
  7090. if (engine instanceof BABYLON.Mesh) {
  7091. this._engine = engine.getScene().getEngine();
  7092. } else {
  7093. this._engine = engine;
  7094. }
  7095. this._updatable = updatable;
  7096. this._data = data;
  7097. if (!postponeInternalCreation) {
  7098. this.create();
  7099. }
  7100. this._kind = kind;
  7101. switch (kind) {
  7102. case VertexBuffer.PositionKind:
  7103. this._strideSize = 3;
  7104. break;
  7105. case VertexBuffer.NormalKind:
  7106. this._strideSize = 3;
  7107. break;
  7108. case VertexBuffer.UVKind:
  7109. this._strideSize = 2;
  7110. break;
  7111. case VertexBuffer.UV2Kind:
  7112. this._strideSize = 2;
  7113. break;
  7114. case VertexBuffer.ColorKind:
  7115. this._strideSize = 3;
  7116. break;
  7117. case VertexBuffer.MatricesIndicesKind:
  7118. this._strideSize = 4;
  7119. break;
  7120. case VertexBuffer.MatricesWeightsKind:
  7121. this._strideSize = 4;
  7122. break;
  7123. }
  7124. }
  7125. VertexBuffer.prototype.isUpdatable = function () {
  7126. return this._updatable;
  7127. };
  7128. VertexBuffer.prototype.getData = function () {
  7129. return this._data;
  7130. };
  7131. VertexBuffer.prototype.getBuffer = function () {
  7132. return this._buffer;
  7133. };
  7134. VertexBuffer.prototype.getStrideSize = function () {
  7135. return this._strideSize;
  7136. };
  7137. VertexBuffer.prototype.create = function (data) {
  7138. if (!data && this._buffer) {
  7139. return;
  7140. }
  7141. data = data || this._data;
  7142. if (!this._buffer) {
  7143. if (this._updatable) {
  7144. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  7145. } else {
  7146. this._buffer = this._engine.createVertexBuffer(data);
  7147. }
  7148. }
  7149. if (this._updatable) {
  7150. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  7151. this._data = data;
  7152. }
  7153. };
  7154. VertexBuffer.prototype.update = function (data) {
  7155. this.create(data);
  7156. };
  7157. VertexBuffer.prototype.updateDirectly = function (data) {
  7158. if (!this._buffer) {
  7159. return;
  7160. }
  7161. if (this._updatable) {
  7162. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  7163. this._data = null;
  7164. }
  7165. };
  7166. VertexBuffer.prototype.dispose = function () {
  7167. if (!this._buffer) {
  7168. return;
  7169. }
  7170. if (this._engine._releaseBuffer(this._buffer)) {
  7171. this._buffer = null;
  7172. }
  7173. };
  7174. Object.defineProperty(VertexBuffer, "PositionKind", {
  7175. get: function () {
  7176. return VertexBuffer._PositionKind;
  7177. },
  7178. enumerable: true,
  7179. configurable: true
  7180. });
  7181. Object.defineProperty(VertexBuffer, "NormalKind", {
  7182. get: function () {
  7183. return VertexBuffer._NormalKind;
  7184. },
  7185. enumerable: true,
  7186. configurable: true
  7187. });
  7188. Object.defineProperty(VertexBuffer, "UVKind", {
  7189. get: function () {
  7190. return VertexBuffer._UVKind;
  7191. },
  7192. enumerable: true,
  7193. configurable: true
  7194. });
  7195. Object.defineProperty(VertexBuffer, "UV2Kind", {
  7196. get: function () {
  7197. return VertexBuffer._UV2Kind;
  7198. },
  7199. enumerable: true,
  7200. configurable: true
  7201. });
  7202. Object.defineProperty(VertexBuffer, "ColorKind", {
  7203. get: function () {
  7204. return VertexBuffer._ColorKind;
  7205. },
  7206. enumerable: true,
  7207. configurable: true
  7208. });
  7209. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  7210. get: function () {
  7211. return VertexBuffer._MatricesIndicesKind;
  7212. },
  7213. enumerable: true,
  7214. configurable: true
  7215. });
  7216. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  7217. get: function () {
  7218. return VertexBuffer._MatricesWeightsKind;
  7219. },
  7220. enumerable: true,
  7221. configurable: true
  7222. });
  7223. VertexBuffer._PositionKind = "position";
  7224. VertexBuffer._NormalKind = "normal";
  7225. VertexBuffer._UVKind = "uv";
  7226. VertexBuffer._UV2Kind = "uv2";
  7227. VertexBuffer._ColorKind = "color";
  7228. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  7229. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  7230. return VertexBuffer;
  7231. })();
  7232. BABYLON.VertexBuffer = VertexBuffer;
  7233. })(BABYLON || (BABYLON = {}));
  7234. var __extends = this.__extends || function (d, b) {
  7235. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  7236. function __() { this.constructor = d; }
  7237. __.prototype = b.prototype;
  7238. d.prototype = new __();
  7239. };
  7240. var BABYLON;
  7241. (function (BABYLON) {
  7242. var AbstractMesh = (function (_super) {
  7243. __extends(AbstractMesh, _super);
  7244. function AbstractMesh(name, scene) {
  7245. _super.call(this, name, scene);
  7246. this.position = new BABYLON.Vector3(0, 0, 0);
  7247. this.rotation = new BABYLON.Vector3(0, 0, 0);
  7248. this.scaling = new BABYLON.Vector3(1, 1, 1);
  7249. this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_NONE;
  7250. this.visibility = 1.0;
  7251. this.infiniteDistance = false;
  7252. this.isVisible = true;
  7253. this.isPickable = true;
  7254. this.showBoundingBox = false;
  7255. this.showSubMeshesBoundingBox = false;
  7256. this.onDispose = null;
  7257. this.checkCollisions = false;
  7258. this.isBlocker = false;
  7259. this.renderingGroupId = 0;
  7260. this.receiveShadows = false;
  7261. this.renderOutline = false;
  7262. this.outlineColor = BABYLON.Color3.Red();
  7263. this.outlineWidth = 0.02;
  7264. this.useOctreeForRenderingSelection = true;
  7265. this.useOctreeForPicking = true;
  7266. this.useOctreeForCollisions = true;
  7267. this.layerMask = 0xFFFFFFFF;
  7268. this._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  7269. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  7270. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  7271. this._collider = new BABYLON.Collider();
  7272. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7273. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7274. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7275. this._localScaling = BABYLON.Matrix.Zero();
  7276. this._localRotation = BABYLON.Matrix.Zero();
  7277. this._localTranslation = BABYLON.Matrix.Zero();
  7278. this._localBillboard = BABYLON.Matrix.Zero();
  7279. this._localPivotScaling = BABYLON.Matrix.Zero();
  7280. this._localPivotScalingRotation = BABYLON.Matrix.Zero();
  7281. this._localWorld = BABYLON.Matrix.Zero();
  7282. this._worldMatrix = BABYLON.Matrix.Zero();
  7283. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  7284. this._absolutePosition = BABYLON.Vector3.Zero();
  7285. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  7286. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  7287. this._isDirty = false;
  7288. this._pivotMatrix = BABYLON.Matrix.Identity();
  7289. this._isDisposed = false;
  7290. this._renderId = 0;
  7291. this._intersectionsInProgress = new Array();
  7292. scene.meshes.push(this);
  7293. }
  7294. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  7295. get: function () {
  7296. return AbstractMesh._BILLBOARDMODE_NONE;
  7297. },
  7298. enumerable: true,
  7299. configurable: true
  7300. });
  7301. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  7302. get: function () {
  7303. return AbstractMesh._BILLBOARDMODE_X;
  7304. },
  7305. enumerable: true,
  7306. configurable: true
  7307. });
  7308. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  7309. get: function () {
  7310. return AbstractMesh._BILLBOARDMODE_Y;
  7311. },
  7312. enumerable: true,
  7313. configurable: true
  7314. });
  7315. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  7316. get: function () {
  7317. return AbstractMesh._BILLBOARDMODE_Z;
  7318. },
  7319. enumerable: true,
  7320. configurable: true
  7321. });
  7322. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  7323. get: function () {
  7324. return AbstractMesh._BILLBOARDMODE_ALL;
  7325. },
  7326. enumerable: true,
  7327. configurable: true
  7328. });
  7329. AbstractMesh.prototype.getTotalVertices = function () {
  7330. return 0;
  7331. };
  7332. AbstractMesh.prototype.getIndices = function () {
  7333. return null;
  7334. };
  7335. AbstractMesh.prototype.getVerticesData = function (kind) {
  7336. return null;
  7337. };
  7338. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  7339. return false;
  7340. };
  7341. AbstractMesh.prototype.getBoundingInfo = function () {
  7342. if (!this._boundingInfo) {
  7343. this._updateBoundingInfo();
  7344. }
  7345. return this._boundingInfo;
  7346. };
  7347. AbstractMesh.prototype._preActivate = function () {
  7348. };
  7349. AbstractMesh.prototype._activate = function (renderId) {
  7350. this._renderId = renderId;
  7351. };
  7352. AbstractMesh.prototype.getWorldMatrix = function () {
  7353. if (this._currentRenderId !== this.getScene().getRenderId()) {
  7354. this.computeWorldMatrix();
  7355. }
  7356. return this._worldMatrix;
  7357. };
  7358. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  7359. get: function () {
  7360. return this._worldMatrix;
  7361. },
  7362. enumerable: true,
  7363. configurable: true
  7364. });
  7365. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  7366. get: function () {
  7367. return this._absolutePosition;
  7368. },
  7369. enumerable: true,
  7370. configurable: true
  7371. });
  7372. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  7373. if (!this.rotationQuaternion) {
  7374. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  7375. this.rotation = BABYLON.Vector3.Zero();
  7376. }
  7377. if (!space || space == 0 /* LOCAL */) {
  7378. var rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  7379. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  7380. } else {
  7381. if (this.parent) {
  7382. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  7383. invertParentWorldMatrix.invert();
  7384. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  7385. }
  7386. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  7387. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  7388. }
  7389. };
  7390. AbstractMesh.prototype.translate = function (axis, distance, space) {
  7391. var displacementVector = axis.scale(distance);
  7392. if (!space || space == 0 /* LOCAL */) {
  7393. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  7394. this.setPositionWithLocalVector(tempV3);
  7395. } else {
  7396. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  7397. }
  7398. };
  7399. AbstractMesh.prototype.getAbsolutePosition = function () {
  7400. this.computeWorldMatrix();
  7401. return this._absolutePosition;
  7402. };
  7403. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  7404. if (!absolutePosition) {
  7405. return;
  7406. }
  7407. var absolutePositionX;
  7408. var absolutePositionY;
  7409. var absolutePositionZ;
  7410. if (absolutePosition.x === undefined) {
  7411. if (arguments.length < 3) {
  7412. return;
  7413. }
  7414. absolutePositionX = arguments[0];
  7415. absolutePositionY = arguments[1];
  7416. absolutePositionZ = arguments[2];
  7417. } else {
  7418. absolutePositionX = absolutePosition.x;
  7419. absolutePositionY = absolutePosition.y;
  7420. absolutePositionZ = absolutePosition.z;
  7421. }
  7422. if (this.parent) {
  7423. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  7424. invertParentWorldMatrix.invert();
  7425. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  7426. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  7427. } else {
  7428. this.position.x = absolutePositionX;
  7429. this.position.y = absolutePositionY;
  7430. this.position.z = absolutePositionZ;
  7431. }
  7432. };
  7433. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  7434. this._pivotMatrix = matrix;
  7435. this._cache.pivotMatrixUpdated = true;
  7436. };
  7437. AbstractMesh.prototype.getPivotMatrix = function () {
  7438. return this._pivotMatrix;
  7439. };
  7440. AbstractMesh.prototype._isSynchronized = function () {
  7441. if (this._isDirty) {
  7442. return false;
  7443. }
  7444. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  7445. return false;
  7446. if (this._cache.pivotMatrixUpdated) {
  7447. return false;
  7448. }
  7449. if (this.infiniteDistance) {
  7450. return false;
  7451. }
  7452. if (!this._cache.position.equals(this.position))
  7453. return false;
  7454. if (this.rotationQuaternion) {
  7455. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  7456. return false;
  7457. } else {
  7458. if (!this._cache.rotation.equals(this.rotation))
  7459. return false;
  7460. }
  7461. if (!this._cache.scaling.equals(this.scaling))
  7462. return false;
  7463. return true;
  7464. };
  7465. AbstractMesh.prototype._initCache = function () {
  7466. _super.prototype._initCache.call(this);
  7467. this._cache.localMatrixUpdated = false;
  7468. this._cache.position = BABYLON.Vector3.Zero();
  7469. this._cache.scaling = BABYLON.Vector3.Zero();
  7470. this._cache.rotation = BABYLON.Vector3.Zero();
  7471. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  7472. };
  7473. AbstractMesh.prototype.markAsDirty = function (property) {
  7474. if (property === "rotation") {
  7475. this.rotationQuaternion = null;
  7476. }
  7477. this._currentRenderId = Number.MAX_VALUE;
  7478. this._isDirty = true;
  7479. };
  7480. AbstractMesh.prototype._updateBoundingInfo = function () {
  7481. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  7482. this._boundingInfo._update(this.worldMatrixFromCache);
  7483. if (!this.subMeshes) {
  7484. return;
  7485. }
  7486. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  7487. var subMesh = this.subMeshes[subIndex];
  7488. subMesh.updateBoundingInfo(this.worldMatrixFromCache);
  7489. }
  7490. };
  7491. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  7492. if (!force && (this._currentRenderId == this.getScene().getRenderId() || this.isSynchronized(true))) {
  7493. return this._worldMatrix;
  7494. }
  7495. this._cache.position.copyFrom(this.position);
  7496. this._cache.scaling.copyFrom(this.scaling);
  7497. this._cache.pivotMatrixUpdated = false;
  7498. this._currentRenderId = this.getScene().getRenderId();
  7499. this._isDirty = false;
  7500. BABYLON.Matrix.ScalingToRef(this.scaling.x, this.scaling.y, this.scaling.z, this._localScaling);
  7501. if (this.rotationQuaternion) {
  7502. this.rotationQuaternion.toRotationMatrix(this._localRotation);
  7503. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  7504. } else {
  7505. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._localRotation);
  7506. this._cache.rotation.copyFrom(this.rotation);
  7507. }
  7508. if (this.infiniteDistance && !this.parent) {
  7509. var camera = this.getScene().activeCamera;
  7510. var cameraWorldMatrix = camera.getWorldMatrix();
  7511. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  7512. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, this._localTranslation);
  7513. } else {
  7514. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._localTranslation);
  7515. }
  7516. this._pivotMatrix.multiplyToRef(this._localScaling, this._localPivotScaling);
  7517. this._localPivotScaling.multiplyToRef(this._localRotation, this._localPivotScalingRotation);
  7518. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  7519. var localPosition = this.position.clone();
  7520. var zero = this.getScene().activeCamera.position.clone();
  7521. if (this.parent && this.parent.position) {
  7522. localPosition.addInPlace(this.parent.position);
  7523. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, this._localTranslation);
  7524. }
  7525. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) === AbstractMesh.BILLBOARDMODE_ALL) {
  7526. zero = this.getScene().activeCamera.position;
  7527. } else {
  7528. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X)
  7529. zero.x = localPosition.x + BABYLON.Engine.Epsilon;
  7530. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y)
  7531. zero.y = localPosition.y + 0.001;
  7532. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z)
  7533. zero.z = localPosition.z + 0.001;
  7534. }
  7535. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), this._localBillboard);
  7536. this._localBillboard.m[12] = this._localBillboard.m[13] = this._localBillboard.m[14] = 0;
  7537. this._localBillboard.invert();
  7538. this._localPivotScalingRotation.multiplyToRef(this._localBillboard, this._localWorld);
  7539. this._rotateYByPI.multiplyToRef(this._localWorld, this._localPivotScalingRotation);
  7540. }
  7541. this._localPivotScalingRotation.multiplyToRef(this._localTranslation, this._localWorld);
  7542. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  7543. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  7544. } else {
  7545. this._worldMatrix.copyFrom(this._localWorld);
  7546. }
  7547. this._updateBoundingInfo();
  7548. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  7549. return this._worldMatrix;
  7550. };
  7551. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  7552. this.computeWorldMatrix();
  7553. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  7554. };
  7555. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  7556. this.computeWorldMatrix();
  7557. var invLocalWorldMatrix = this._localWorld.clone();
  7558. invLocalWorldMatrix.invert();
  7559. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  7560. };
  7561. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  7562. this.computeWorldMatrix();
  7563. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  7564. };
  7565. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  7566. yawCor = yawCor || 0;
  7567. pitchCor = pitchCor || 0;
  7568. rollCor = rollCor || 0;
  7569. var dv = targetPoint.subtract(this.position);
  7570. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  7571. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  7572. var pitch = Math.atan2(dv.y, len);
  7573. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  7574. };
  7575. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  7576. if (!this._boundingInfo.isInFrustum(frustumPlanes)) {
  7577. return false;
  7578. }
  7579. return true;
  7580. };
  7581. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  7582. if (!this._boundingInfo || !mesh._boundingInfo) {
  7583. return false;
  7584. }
  7585. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  7586. };
  7587. AbstractMesh.prototype.intersectsPoint = function (point) {
  7588. if (!this._boundingInfo) {
  7589. return false;
  7590. }
  7591. return this._boundingInfo.intersectsPoint(point);
  7592. };
  7593. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  7594. var physicsEngine = this.getScene().getPhysicsEngine();
  7595. if (!physicsEngine) {
  7596. return;
  7597. }
  7598. if (impostor.impostor) {
  7599. options = impostor;
  7600. impostor = impostor.impostor;
  7601. }
  7602. impostor = impostor || BABYLON.PhysicsEngine.NoImpostor;
  7603. if (impostor === BABYLON.PhysicsEngine.NoImpostor) {
  7604. physicsEngine._unregisterMesh(this);
  7605. return;
  7606. }
  7607. options.mass = options.mass || 0;
  7608. options.friction = options.friction || 0.2;
  7609. options.restitution = options.restitution || 0.2;
  7610. this._physicImpostor = impostor;
  7611. this._physicsMass = options.mass;
  7612. this._physicsFriction = options.friction;
  7613. this._physicRestitution = options.restitution;
  7614. physicsEngine._registerMesh(this, impostor, options);
  7615. };
  7616. AbstractMesh.prototype.getPhysicsImpostor = function () {
  7617. if (!this._physicImpostor) {
  7618. return BABYLON.PhysicsEngine.NoImpostor;
  7619. }
  7620. return this._physicImpostor;
  7621. };
  7622. AbstractMesh.prototype.getPhysicsMass = function () {
  7623. if (!this._physicsMass) {
  7624. return 0;
  7625. }
  7626. return this._physicsMass;
  7627. };
  7628. AbstractMesh.prototype.getPhysicsFriction = function () {
  7629. if (!this._physicsFriction) {
  7630. return 0;
  7631. }
  7632. return this._physicsFriction;
  7633. };
  7634. AbstractMesh.prototype.getPhysicsRestitution = function () {
  7635. if (!this._physicRestitution) {
  7636. return 0;
  7637. }
  7638. return this._physicRestitution;
  7639. };
  7640. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  7641. if (!this._physicImpostor) {
  7642. return;
  7643. }
  7644. this.getScene().getPhysicsEngine()._applyImpulse(this, force, contactPoint);
  7645. };
  7646. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  7647. if (!this._physicImpostor) {
  7648. return;
  7649. }
  7650. this.getScene().getPhysicsEngine()._createLink(this, otherMesh, pivot1, pivot2, options);
  7651. };
  7652. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  7653. if (!this._physicImpostor) {
  7654. return;
  7655. }
  7656. this.getScene().getPhysicsEngine()._updateBodyPosition(this);
  7657. };
  7658. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  7659. var globalPosition = this.getAbsolutePosition();
  7660. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  7661. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  7662. this._collider.radius = this.ellipsoid;
  7663. this.getScene()._getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this._newPositionForCollisions, this);
  7664. this._newPositionForCollisions.subtractToRef(this._oldPositionForCollisions, this._diffPositionForCollisions);
  7665. if (this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  7666. this.position.addInPlace(this._diffPositionForCollisions);
  7667. }
  7668. };
  7669. /**
  7670. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  7671. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  7672. */
  7673. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  7674. if (typeof maxCapacity === "undefined") { maxCapacity = 64; }
  7675. if (typeof maxDepth === "undefined") { maxDepth = 2; }
  7676. if (!this._submeshesOctree) {
  7677. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  7678. }
  7679. this.computeWorldMatrix(true);
  7680. var bbox = this.getBoundingInfo().boundingBox;
  7681. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  7682. return this._submeshesOctree;
  7683. };
  7684. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  7685. this._generatePointsArray();
  7686. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  7687. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  7688. subMesh._lastColliderWorldVertices = [];
  7689. subMesh._trianglePlanes = [];
  7690. var start = subMesh.verticesStart;
  7691. var end = (subMesh.verticesStart + subMesh.verticesCount);
  7692. for (var i = start; i < end; i++) {
  7693. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  7694. }
  7695. }
  7696. collider._collide(subMesh, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart);
  7697. };
  7698. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  7699. var subMeshes;
  7700. var len;
  7701. if (this._submeshesOctree && this.useOctreeForCollisions) {
  7702. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  7703. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  7704. len = intersections.length;
  7705. subMeshes = intersections.data;
  7706. } else {
  7707. subMeshes = this.subMeshes;
  7708. len = subMeshes.length;
  7709. }
  7710. for (var index = 0; index < len; index++) {
  7711. var subMesh = subMeshes[index];
  7712. if (len > 1 && !subMesh._checkCollision(collider))
  7713. continue;
  7714. this._collideForSubMesh(subMesh, transformMatrix, collider);
  7715. }
  7716. };
  7717. AbstractMesh.prototype._checkCollision = function (collider) {
  7718. if (!this._boundingInfo._checkCollision(collider))
  7719. return;
  7720. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  7721. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  7722. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  7723. };
  7724. AbstractMesh.prototype._generatePointsArray = function () {
  7725. return false;
  7726. };
  7727. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  7728. var pickingInfo = new BABYLON.PickingInfo();
  7729. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  7730. return pickingInfo;
  7731. }
  7732. if (!this._generatePointsArray()) {
  7733. return pickingInfo;
  7734. }
  7735. var intersectInfo = null;
  7736. var subMeshes;
  7737. var len;
  7738. if (this._submeshesOctree && this.useOctreeForPicking) {
  7739. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  7740. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  7741. len = intersections.length;
  7742. subMeshes = intersections.data;
  7743. } else {
  7744. subMeshes = this.subMeshes;
  7745. len = subMeshes.length;
  7746. }
  7747. for (var index = 0; index < len; index++) {
  7748. var subMesh = subMeshes[index];
  7749. if (len > 1 && !subMesh.canIntersects(ray))
  7750. continue;
  7751. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  7752. if (currentIntersectInfo) {
  7753. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  7754. intersectInfo = currentIntersectInfo;
  7755. if (fastCheck) {
  7756. break;
  7757. }
  7758. }
  7759. }
  7760. }
  7761. if (intersectInfo) {
  7762. var world = this.getWorldMatrix();
  7763. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  7764. var direction = ray.direction.clone();
  7765. direction.normalize();
  7766. direction = direction.scale(intersectInfo.distance);
  7767. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  7768. var pickedPoint = worldOrigin.add(worldDirection);
  7769. pickingInfo.hit = true;
  7770. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  7771. pickingInfo.pickedPoint = pickedPoint;
  7772. pickingInfo.pickedMesh = this;
  7773. pickingInfo.bu = intersectInfo.bu;
  7774. pickingInfo.bv = intersectInfo.bv;
  7775. pickingInfo.faceId = intersectInfo.faceId;
  7776. return pickingInfo;
  7777. }
  7778. return pickingInfo;
  7779. };
  7780. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  7781. return null;
  7782. };
  7783. AbstractMesh.prototype.releaseSubMeshes = function () {
  7784. if (this.subMeshes) {
  7785. while (this.subMeshes.length) {
  7786. this.subMeshes[0].dispose();
  7787. }
  7788. } else {
  7789. this.subMeshes = new Array();
  7790. }
  7791. };
  7792. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  7793. if (this.getPhysicsImpostor() != BABYLON.PhysicsEngine.NoImpostor) {
  7794. this.setPhysicsState(BABYLON.PhysicsEngine.NoImpostor);
  7795. }
  7796. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  7797. var other = this._intersectionsInProgress[index];
  7798. var pos = other._intersectionsInProgress.indexOf(this);
  7799. other._intersectionsInProgress.splice(pos, 1);
  7800. }
  7801. this._intersectionsInProgress = [];
  7802. this.releaseSubMeshes();
  7803. var index = this.getScene().meshes.indexOf(this);
  7804. if (index != -1) {
  7805. this.getScene().meshes.splice(index, 1);
  7806. }
  7807. if (!doNotRecurse) {
  7808. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  7809. if (this.getScene().particleSystems[index].emitter == this) {
  7810. this.getScene().particleSystems[index].dispose();
  7811. index--;
  7812. }
  7813. }
  7814. var objects = this.getScene().meshes.slice(0);
  7815. for (index = 0; index < objects.length; index++) {
  7816. if (objects[index].parent == this) {
  7817. objects[index].dispose();
  7818. }
  7819. }
  7820. } else {
  7821. for (index = 0; index < this.getScene().meshes.length; index++) {
  7822. var obj = this.getScene().meshes[index];
  7823. if (obj.parent === this) {
  7824. obj.parent = null;
  7825. obj.computeWorldMatrix(true);
  7826. }
  7827. }
  7828. }
  7829. this._isDisposed = true;
  7830. if (this.onDispose) {
  7831. this.onDispose();
  7832. }
  7833. };
  7834. AbstractMesh._BILLBOARDMODE_NONE = 0;
  7835. AbstractMesh._BILLBOARDMODE_X = 1;
  7836. AbstractMesh._BILLBOARDMODE_Y = 2;
  7837. AbstractMesh._BILLBOARDMODE_Z = 4;
  7838. AbstractMesh._BILLBOARDMODE_ALL = 7;
  7839. return AbstractMesh;
  7840. })(BABYLON.Node);
  7841. BABYLON.AbstractMesh = AbstractMesh;
  7842. })(BABYLON || (BABYLON = {}));
  7843. var __extends = this.__extends || function (d, b) {
  7844. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  7845. function __() { this.constructor = d; }
  7846. __.prototype = b.prototype;
  7847. d.prototype = new __();
  7848. };
  7849. var BABYLON;
  7850. (function (BABYLON) {
  7851. var _InstancesBatch = (function () {
  7852. function _InstancesBatch() {
  7853. this.mustReturn = false;
  7854. this.visibleInstances = new Array();
  7855. this.renderSelf = new Array();
  7856. }
  7857. return _InstancesBatch;
  7858. })();
  7859. BABYLON._InstancesBatch = _InstancesBatch;
  7860. var Mesh = (function (_super) {
  7861. __extends(Mesh, _super);
  7862. function Mesh(name, scene) {
  7863. _super.call(this, name, scene);
  7864. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  7865. this.instances = new Array();
  7866. this._onBeforeRenderCallbacks = new Array();
  7867. this._onAfterRenderCallbacks = new Array();
  7868. this._visibleInstances = {};
  7869. this._renderIdForInstances = new Array();
  7870. this._batchCache = new _InstancesBatch();
  7871. this._instancesBufferSize = 32 * 16 * 4;
  7872. }
  7873. Mesh.prototype.getTotalVertices = function () {
  7874. if (!this._geometry) {
  7875. return 0;
  7876. }
  7877. return this._geometry.getTotalVertices();
  7878. };
  7879. Mesh.prototype.getVerticesData = function (kind) {
  7880. if (!this._geometry) {
  7881. return null;
  7882. }
  7883. return this._geometry.getVerticesData(kind);
  7884. };
  7885. Mesh.prototype.getVertexBuffer = function (kind) {
  7886. if (!this._geometry) {
  7887. return undefined;
  7888. }
  7889. return this._geometry.getVertexBuffer(kind);
  7890. };
  7891. Mesh.prototype.isVerticesDataPresent = function (kind) {
  7892. if (!this._geometry) {
  7893. if (this._delayInfo) {
  7894. return this._delayInfo.indexOf(kind) !== -1;
  7895. }
  7896. return false;
  7897. }
  7898. return this._geometry.isVerticesDataPresent(kind);
  7899. };
  7900. Mesh.prototype.getVerticesDataKinds = function () {
  7901. if (!this._geometry) {
  7902. var result = [];
  7903. if (this._delayInfo) {
  7904. for (var kind in this._delayInfo) {
  7905. result.push(kind);
  7906. }
  7907. }
  7908. return result;
  7909. }
  7910. return this._geometry.getVerticesDataKinds();
  7911. };
  7912. Mesh.prototype.getTotalIndices = function () {
  7913. if (!this._geometry) {
  7914. return 0;
  7915. }
  7916. return this._geometry.getTotalIndices();
  7917. };
  7918. Mesh.prototype.getIndices = function () {
  7919. if (!this._geometry) {
  7920. return [];
  7921. }
  7922. return this._geometry.getIndices();
  7923. };
  7924. Mesh.prototype.isReady = function () {
  7925. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  7926. return false;
  7927. }
  7928. return _super.prototype.isReady.call(this);
  7929. };
  7930. Mesh.prototype.isDisposed = function () {
  7931. return this._isDisposed;
  7932. };
  7933. Mesh.prototype._preActivate = function () {
  7934. var sceneRenderId = this.getScene().getRenderId();
  7935. if (this._preActivateId == sceneRenderId) {
  7936. return;
  7937. }
  7938. this._preActivateId = sceneRenderId;
  7939. this._visibleInstances = null;
  7940. };
  7941. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  7942. if (!this._visibleInstances) {
  7943. this._visibleInstances = {};
  7944. this._visibleInstances.defaultRenderId = renderId;
  7945. this._visibleInstances.selfDefaultRenderId = this._renderId;
  7946. }
  7947. if (!this._visibleInstances[renderId]) {
  7948. this._visibleInstances[renderId] = new Array();
  7949. }
  7950. this._visibleInstances[renderId].push(instance);
  7951. };
  7952. Mesh.prototype.refreshBoundingInfo = function () {
  7953. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  7954. if (data) {
  7955. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  7956. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  7957. }
  7958. if (this.subMeshes) {
  7959. for (var index = 0; index < this.subMeshes.length; index++) {
  7960. this.subMeshes[index].refreshBoundingInfo();
  7961. }
  7962. }
  7963. this._updateBoundingInfo();
  7964. };
  7965. Mesh.prototype._createGlobalSubMesh = function () {
  7966. var totalVertices = this.getTotalVertices();
  7967. if (!totalVertices || !this.getIndices()) {
  7968. return null;
  7969. }
  7970. this.releaseSubMeshes();
  7971. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  7972. };
  7973. Mesh.prototype.subdivide = function (count) {
  7974. if (count < 1) {
  7975. return;
  7976. }
  7977. var totalIndices = this.getTotalIndices();
  7978. var subdivisionSize = (totalIndices / count) | 0;
  7979. var offset = 0;
  7980. while (subdivisionSize % 3 != 0) {
  7981. subdivisionSize++;
  7982. }
  7983. this.releaseSubMeshes();
  7984. for (var index = 0; index < count; index++) {
  7985. if (offset >= totalIndices) {
  7986. break;
  7987. }
  7988. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  7989. offset += subdivisionSize;
  7990. }
  7991. this.synchronizeInstances();
  7992. };
  7993. Mesh.prototype.setVerticesData = function (kind, data, updatable) {
  7994. if (kind instanceof Array) {
  7995. var temp = data;
  7996. data = kind;
  7997. kind = temp;
  7998. BABYLON.Tools.Warn("Deprecated usage of setVerticesData detected (since v1.12). Current signature is setVerticesData(kind, data, updatable).");
  7999. }
  8000. if (!this._geometry) {
  8001. var vertexData = new BABYLON.VertexData();
  8002. vertexData.set(data, kind);
  8003. var scene = this.getScene();
  8004. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  8005. } else {
  8006. this._geometry.setVerticesData(kind, data, updatable);
  8007. }
  8008. };
  8009. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  8010. if (!this._geometry) {
  8011. return;
  8012. }
  8013. if (!makeItUnique) {
  8014. this._geometry.updateVerticesData(kind, data, updateExtends);
  8015. } else {
  8016. this.makeGeometryUnique();
  8017. this.updateVerticesData(kind, data, updateExtends, false);
  8018. }
  8019. };
  8020. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, makeItUnique) {
  8021. if (!this._geometry) {
  8022. return;
  8023. }
  8024. if (!makeItUnique) {
  8025. this._geometry.updateVerticesDataDirectly(kind, data);
  8026. } else {
  8027. this.makeGeometryUnique();
  8028. this.updateVerticesDataDirectly(kind, data, false);
  8029. }
  8030. };
  8031. Mesh.prototype.makeGeometryUnique = function () {
  8032. if (!this._geometry) {
  8033. return;
  8034. }
  8035. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  8036. geometry.applyToMesh(this);
  8037. };
  8038. Mesh.prototype.setIndices = function (indices) {
  8039. if (!this._geometry) {
  8040. var vertexData = new BABYLON.VertexData();
  8041. vertexData.indices = indices;
  8042. var scene = this.getScene();
  8043. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  8044. } else {
  8045. this._geometry.setIndices(indices);
  8046. }
  8047. };
  8048. Mesh.prototype._bind = function (subMesh, effect, wireframe) {
  8049. var engine = this.getScene().getEngine();
  8050. var indexToBind = this._geometry.getIndexBuffer();
  8051. if (wireframe) {
  8052. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  8053. }
  8054. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  8055. };
  8056. Mesh.prototype._draw = function (subMesh, useTriangles, instancesCount) {
  8057. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  8058. return;
  8059. }
  8060. var engine = this.getScene().getEngine();
  8061. engine.draw(useTriangles, useTriangles ? subMesh.indexStart : 0, useTriangles ? subMesh.indexCount : subMesh.linesIndexCount, instancesCount);
  8062. };
  8063. Mesh.prototype._fullDraw = function (subMesh, useTriangles, instancesCount) {
  8064. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  8065. return;
  8066. }
  8067. var engine = this.getScene().getEngine();
  8068. engine.draw(useTriangles, useTriangles ? subMesh.indexStart : 0, useTriangles ? subMesh.indexCount : subMesh.linesIndexCount, instancesCount);
  8069. };
  8070. Mesh.prototype.registerBeforeRender = function (func) {
  8071. this._onBeforeRenderCallbacks.push(func);
  8072. };
  8073. Mesh.prototype.unregisterBeforeRender = function (func) {
  8074. var index = this._onBeforeRenderCallbacks.indexOf(func);
  8075. if (index > -1) {
  8076. this._onBeforeRenderCallbacks.splice(index, 1);
  8077. }
  8078. };
  8079. Mesh.prototype.registerAfterRender = function (func) {
  8080. this._onAfterRenderCallbacks.push(func);
  8081. };
  8082. Mesh.prototype.unregisterAfterRender = function (func) {
  8083. var index = this._onAfterRenderCallbacks.indexOf(func);
  8084. if (index > -1) {
  8085. this._onAfterRenderCallbacks.splice(index, 1);
  8086. }
  8087. };
  8088. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  8089. var scene = this.getScene();
  8090. this._batchCache.mustReturn = false;
  8091. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  8092. this._batchCache.visibleInstances[subMeshId] = null;
  8093. if (this._visibleInstances) {
  8094. var currentRenderId = scene.getRenderId();
  8095. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  8096. var selfRenderId = this._renderId;
  8097. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  8098. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  8099. currentRenderId = this._visibleInstances.defaultRenderId;
  8100. selfRenderId = this._visibleInstances.selfDefaultRenderId;
  8101. }
  8102. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  8103. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  8104. this._batchCache.mustReturn = true;
  8105. return this._batchCache;
  8106. }
  8107. if (currentRenderId !== selfRenderId) {
  8108. this._batchCache.renderSelf[subMeshId] = false;
  8109. }
  8110. }
  8111. this._renderIdForInstances[subMeshId] = currentRenderId;
  8112. }
  8113. return this._batchCache;
  8114. };
  8115. Mesh.prototype._renderWithInstances = function (subMesh, wireFrame, batch, effect, engine) {
  8116. var matricesCount = this.instances.length + 1;
  8117. var bufferSize = matricesCount * 16 * 4;
  8118. while (this._instancesBufferSize < bufferSize) {
  8119. this._instancesBufferSize *= 2;
  8120. }
  8121. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  8122. if (this._worldMatricesInstancesBuffer) {
  8123. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  8124. }
  8125. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  8126. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  8127. }
  8128. var offset = 0;
  8129. var instancesCount = 0;
  8130. var world = this.getWorldMatrix();
  8131. if (batch.renderSelf[subMesh._id]) {
  8132. world.copyToArray(this._worldMatricesInstancesArray, offset);
  8133. offset += 16;
  8134. instancesCount++;
  8135. }
  8136. var visibleInstances = batch.visibleInstances[subMesh._id];
  8137. if (visibleInstances) {
  8138. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  8139. var instance = visibleInstances[instanceIndex];
  8140. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  8141. offset += 16;
  8142. instancesCount++;
  8143. }
  8144. }
  8145. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  8146. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  8147. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  8148. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  8149. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  8150. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  8151. this._draw(subMesh, !wireFrame, instancesCount);
  8152. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  8153. };
  8154. Mesh.prototype.render = function (subMesh) {
  8155. var scene = this.getScene();
  8156. var batch = this._getInstancesRenderList(subMesh._id);
  8157. if (batch.mustReturn) {
  8158. return;
  8159. }
  8160. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  8161. return;
  8162. }
  8163. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  8164. this._onBeforeRenderCallbacks[callbackIndex]();
  8165. }
  8166. var engine = scene.getEngine();
  8167. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  8168. var effectiveMaterial = subMesh.getMaterial();
  8169. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  8170. return;
  8171. }
  8172. var savedDepthWrite = engine.getDepthWrite();
  8173. if (this.renderOutline) {
  8174. engine.setDepthWrite(false);
  8175. scene.getOutlineRenderer().render(subMesh, batch);
  8176. }
  8177. effectiveMaterial._preBind();
  8178. var effect = effectiveMaterial.getEffect();
  8179. var wireFrame = engine.forceWireframe || effectiveMaterial.wireframe;
  8180. this._bind(subMesh, effect, wireFrame);
  8181. var world = this.getWorldMatrix();
  8182. effectiveMaterial.bind(world, this);
  8183. if (hardwareInstancedRendering) {
  8184. this._renderWithInstances(subMesh, wireFrame, batch, effect, engine);
  8185. } else {
  8186. if (batch.renderSelf[subMesh._id]) {
  8187. this._draw(subMesh, !wireFrame);
  8188. }
  8189. if (batch.visibleInstances[subMesh._id]) {
  8190. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  8191. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  8192. world = instance.getWorldMatrix();
  8193. effectiveMaterial.bindOnlyWorldMatrix(world);
  8194. this._draw(subMesh, !wireFrame);
  8195. }
  8196. }
  8197. }
  8198. effectiveMaterial.unbind();
  8199. if (this.renderOutline && savedDepthWrite) {
  8200. engine.setDepthWrite(true);
  8201. engine.setColorWrite(false);
  8202. scene.getOutlineRenderer().render(subMesh, batch);
  8203. engine.setColorWrite(true);
  8204. }
  8205. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  8206. this._onAfterRenderCallbacks[callbackIndex]();
  8207. }
  8208. };
  8209. Mesh.prototype.getEmittedParticleSystems = function () {
  8210. var results = new Array();
  8211. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  8212. var particleSystem = this.getScene().particleSystems[index];
  8213. if (particleSystem.emitter === this) {
  8214. results.push(particleSystem);
  8215. }
  8216. }
  8217. return results;
  8218. };
  8219. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  8220. var results = new Array();
  8221. var descendants = this.getDescendants();
  8222. descendants.push(this);
  8223. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  8224. var particleSystem = this.getScene().particleSystems[index];
  8225. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  8226. results.push(particleSystem);
  8227. }
  8228. }
  8229. return results;
  8230. };
  8231. Mesh.prototype.getChildren = function () {
  8232. var results = [];
  8233. for (var index = 0; index < this.getScene().meshes.length; index++) {
  8234. var mesh = this.getScene().meshes[index];
  8235. if (mesh.parent == this) {
  8236. results.push(mesh);
  8237. }
  8238. }
  8239. return results;
  8240. };
  8241. Mesh.prototype._checkDelayState = function () {
  8242. var _this = this;
  8243. var that = this;
  8244. var scene = this.getScene();
  8245. if (this._geometry) {
  8246. this._geometry.load(scene);
  8247. } else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  8248. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  8249. scene._addPendingData(that);
  8250. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1) ? true : false;
  8251. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  8252. if (data instanceof ArrayBuffer) {
  8253. _this._delayLoadingFunction(data, _this);
  8254. } else {
  8255. _this._delayLoadingFunction(JSON.parse(data), _this);
  8256. }
  8257. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  8258. scene._removePendingData(_this);
  8259. }, function () {
  8260. }, scene.database, getBinaryData);
  8261. }
  8262. };
  8263. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  8264. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  8265. return false;
  8266. }
  8267. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  8268. return false;
  8269. }
  8270. this._checkDelayState();
  8271. return true;
  8272. };
  8273. Mesh.prototype.setMaterialByID = function (id) {
  8274. var materials = this.getScene().materials;
  8275. for (var index = 0; index < materials.length; index++) {
  8276. if (materials[index].id == id) {
  8277. this.material = materials[index];
  8278. return;
  8279. }
  8280. }
  8281. var multiMaterials = this.getScene().multiMaterials;
  8282. for (index = 0; index < multiMaterials.length; index++) {
  8283. if (multiMaterials[index].id == id) {
  8284. this.material = multiMaterials[index];
  8285. return;
  8286. }
  8287. }
  8288. };
  8289. Mesh.prototype.getAnimatables = function () {
  8290. var results = [];
  8291. if (this.material) {
  8292. results.push(this.material);
  8293. }
  8294. if (this.skeleton) {
  8295. results.push(this.skeleton);
  8296. }
  8297. return results;
  8298. };
  8299. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  8300. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  8301. return;
  8302. }
  8303. this._resetPointsArrayCache();
  8304. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  8305. var temp = [];
  8306. for (var index = 0; index < data.length; index += 3) {
  8307. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  8308. }
  8309. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  8310. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  8311. return;
  8312. }
  8313. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  8314. for (index = 0; index < data.length; index += 3) {
  8315. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  8316. }
  8317. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  8318. };
  8319. Mesh.prototype._resetPointsArrayCache = function () {
  8320. this._positions = null;
  8321. };
  8322. Mesh.prototype._generatePointsArray = function () {
  8323. if (this._positions)
  8324. return true;
  8325. this._positions = [];
  8326. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  8327. if (!data) {
  8328. return false;
  8329. }
  8330. for (var index = 0; index < data.length; index += 3) {
  8331. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  8332. }
  8333. return true;
  8334. };
  8335. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  8336. var result = new BABYLON.Mesh(name, this.getScene());
  8337. this._geometry.applyToMesh(result);
  8338. BABYLON.Tools.DeepCopy(this, result, ["name", "material", "skeleton"], []);
  8339. result.material = this.material;
  8340. if (newParent) {
  8341. result.parent = newParent;
  8342. }
  8343. if (!doNotCloneChildren) {
  8344. for (var index = 0; index < this.getScene().meshes.length; index++) {
  8345. var mesh = this.getScene().meshes[index];
  8346. if (mesh.parent == this) {
  8347. mesh.clone(mesh.name, result);
  8348. }
  8349. }
  8350. }
  8351. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  8352. var system = this.getScene().particleSystems[index];
  8353. if (system.emitter == this) {
  8354. system.clone(system.name, result);
  8355. }
  8356. }
  8357. result.computeWorldMatrix(true);
  8358. return result;
  8359. };
  8360. Mesh.prototype.dispose = function (doNotRecurse) {
  8361. if (this._geometry) {
  8362. this._geometry.releaseForMesh(this, true);
  8363. }
  8364. if (this._worldMatricesInstancesBuffer) {
  8365. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  8366. this._worldMatricesInstancesBuffer = null;
  8367. }
  8368. while (this.instances.length) {
  8369. this.instances[0].dispose();
  8370. }
  8371. _super.prototype.dispose.call(this, doNotRecurse);
  8372. };
  8373. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight) {
  8374. var _this = this;
  8375. var scene = this.getScene();
  8376. var onload = function (img) {
  8377. var canvas = document.createElement("canvas");
  8378. var context = canvas.getContext("2d");
  8379. var heightMapWidth = img.width;
  8380. var heightMapHeight = img.height;
  8381. canvas.width = heightMapWidth;
  8382. canvas.height = heightMapHeight;
  8383. context.drawImage(img, 0, 0);
  8384. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  8385. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  8386. };
  8387. BABYLON.Tools.LoadImage(url, onload, function () {
  8388. }, scene.database);
  8389. };
  8390. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  8391. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  8392. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  8393. return;
  8394. }
  8395. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  8396. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  8397. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  8398. var position = BABYLON.Vector3.Zero();
  8399. var normal = BABYLON.Vector3.Zero();
  8400. var uv = BABYLON.Vector2.Zero();
  8401. for (var index = 0; index < positions.length; index += 3) {
  8402. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  8403. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  8404. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  8405. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  8406. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  8407. var pos = (u + v * heightMapWidth) * 4;
  8408. var r = buffer[pos] / 255.0;
  8409. var g = buffer[pos + 1] / 255.0;
  8410. var b = buffer[pos + 2] / 255.0;
  8411. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  8412. normal.normalize();
  8413. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  8414. position = position.add(normal);
  8415. position.toArray(positions, index);
  8416. }
  8417. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  8418. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  8419. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  8420. };
  8421. Mesh.prototype.convertToFlatShadedMesh = function () {
  8422. var kinds = this.getVerticesDataKinds();
  8423. var vbs = [];
  8424. var data = [];
  8425. var newdata = [];
  8426. var updatableNormals = false;
  8427. for (var kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  8428. var kind = kinds[kindIndex];
  8429. var vertexBuffer = this.getVertexBuffer(kind);
  8430. if (kind === BABYLON.VertexBuffer.NormalKind) {
  8431. updatableNormals = vertexBuffer.isUpdatable();
  8432. kinds.splice(kindIndex, 1);
  8433. kindIndex--;
  8434. continue;
  8435. }
  8436. vbs[kind] = vertexBuffer;
  8437. data[kind] = vbs[kind].getData();
  8438. newdata[kind] = [];
  8439. }
  8440. var previousSubmeshes = this.subMeshes.slice(0);
  8441. var indices = this.getIndices();
  8442. var totalIndices = this.getTotalIndices();
  8443. for (index = 0; index < totalIndices; index++) {
  8444. var vertexIndex = indices[index];
  8445. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  8446. kind = kinds[kindIndex];
  8447. var stride = vbs[kind].getStrideSize();
  8448. for (var offset = 0; offset < stride; offset++) {
  8449. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  8450. }
  8451. }
  8452. }
  8453. var normals = [];
  8454. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  8455. for (var index = 0; index < totalIndices; index += 3) {
  8456. indices[index] = index;
  8457. indices[index + 1] = index + 1;
  8458. indices[index + 2] = index + 2;
  8459. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  8460. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  8461. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  8462. var p1p2 = p1.subtract(p2);
  8463. var p3p2 = p3.subtract(p2);
  8464. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  8465. for (var localIndex = 0; localIndex < 3; localIndex++) {
  8466. normals.push(normal.x);
  8467. normals.push(normal.y);
  8468. normals.push(normal.z);
  8469. }
  8470. }
  8471. this.setIndices(indices);
  8472. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  8473. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  8474. kind = kinds[kindIndex];
  8475. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  8476. }
  8477. this.releaseSubMeshes();
  8478. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  8479. var previousOne = previousSubmeshes[submeshIndex];
  8480. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  8481. }
  8482. this.synchronizeInstances();
  8483. };
  8484. Mesh.prototype.createInstance = function (name) {
  8485. return new BABYLON.InstancedMesh(name, this);
  8486. };
  8487. Mesh.prototype.synchronizeInstances = function () {
  8488. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  8489. var instance = this.instances[instanceIndex];
  8490. instance._syncSubMeshes();
  8491. }
  8492. };
  8493. Mesh.CreateBox = function (name, size, scene, updatable) {
  8494. var box = new BABYLON.Mesh(name, scene);
  8495. var vertexData = BABYLON.VertexData.CreateBox(size);
  8496. vertexData.applyToMesh(box, updatable);
  8497. return box;
  8498. };
  8499. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable) {
  8500. var sphere = new BABYLON.Mesh(name, scene);
  8501. var vertexData = BABYLON.VertexData.CreateSphere(segments, diameter);
  8502. vertexData.applyToMesh(sphere, updatable);
  8503. return sphere;
  8504. };
  8505. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable) {
  8506. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  8507. if (scene !== undefined) {
  8508. updatable = scene;
  8509. }
  8510. scene = subdivisions;
  8511. subdivisions = 1;
  8512. }
  8513. var cylinder = new BABYLON.Mesh(name, scene);
  8514. var vertexData = BABYLON.VertexData.CreateCylinder(height, diameterTop, diameterBottom, tessellation, subdivisions);
  8515. vertexData.applyToMesh(cylinder, updatable);
  8516. return cylinder;
  8517. };
  8518. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable) {
  8519. var torus = new BABYLON.Mesh(name, scene);
  8520. var vertexData = BABYLON.VertexData.CreateTorus(diameter, thickness, tessellation);
  8521. vertexData.applyToMesh(torus, updatable);
  8522. return torus;
  8523. };
  8524. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable) {
  8525. var torusKnot = new BABYLON.Mesh(name, scene);
  8526. var vertexData = BABYLON.VertexData.CreateTorusKnot(radius, tube, radialSegments, tubularSegments, p, q);
  8527. vertexData.applyToMesh(torusKnot, updatable);
  8528. return torusKnot;
  8529. };
  8530. Mesh.CreateLines = function (name, points, scene, updatable) {
  8531. var lines = new BABYLON.LinesMesh(name, scene, updatable);
  8532. var vertexData = BABYLON.VertexData.CreateLines(points);
  8533. vertexData.applyToMesh(lines, updatable);
  8534. return lines;
  8535. };
  8536. Mesh.CreatePlane = function (name, size, scene, updatable) {
  8537. var plane = new BABYLON.Mesh(name, scene);
  8538. var vertexData = BABYLON.VertexData.CreatePlane(size);
  8539. vertexData.applyToMesh(plane, updatable);
  8540. return plane;
  8541. };
  8542. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  8543. var ground = new BABYLON.GroundMesh(name, scene);
  8544. ground._setReady(false);
  8545. ground._subdivisions = subdivisions;
  8546. var vertexData = BABYLON.VertexData.CreateGround(width, height, subdivisions);
  8547. vertexData.applyToMesh(ground, updatable);
  8548. ground._setReady(true);
  8549. return ground;
  8550. };
  8551. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  8552. var tiledGround = new BABYLON.Mesh(name, scene);
  8553. var vertexData = BABYLON.VertexData.CreateTiledGround(xmin, zmin, xmax, zmax, subdivisions, precision);
  8554. vertexData.applyToMesh(tiledGround, updatable);
  8555. return tiledGround;
  8556. };
  8557. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable) {
  8558. var ground = new BABYLON.GroundMesh(name, scene);
  8559. ground._subdivisions = subdivisions;
  8560. ground._setReady(false);
  8561. var onload = function (img) {
  8562. var canvas = document.createElement("canvas");
  8563. var context = canvas.getContext("2d");
  8564. var heightMapWidth = img.width;
  8565. var heightMapHeight = img.height;
  8566. canvas.width = heightMapWidth;
  8567. canvas.height = heightMapHeight;
  8568. context.drawImage(img, 0, 0);
  8569. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  8570. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap(width, height, subdivisions, minHeight, maxHeight, buffer, heightMapWidth, heightMapHeight);
  8571. vertexData.applyToMesh(ground, updatable);
  8572. ground._setReady(true);
  8573. };
  8574. BABYLON.Tools.LoadImage(url, onload, function () {
  8575. }, scene.database);
  8576. return ground;
  8577. };
  8578. Mesh.MinMax = function (meshes) {
  8579. var minVector = null;
  8580. var maxVector = null;
  8581. for (var i in meshes) {
  8582. var mesh = meshes[i];
  8583. var boundingBox = mesh.getBoundingInfo().boundingBox;
  8584. if (!minVector) {
  8585. minVector = boundingBox.minimumWorld;
  8586. maxVector = boundingBox.maximumWorld;
  8587. continue;
  8588. }
  8589. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  8590. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  8591. }
  8592. return {
  8593. min: minVector,
  8594. max: maxVector
  8595. };
  8596. };
  8597. Mesh.Center = function (meshesOrMinMaxVector) {
  8598. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  8599. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  8600. };
  8601. return Mesh;
  8602. })(BABYLON.AbstractMesh);
  8603. BABYLON.Mesh = Mesh;
  8604. })(BABYLON || (BABYLON = {}));
  8605. var __extends = this.__extends || function (d, b) {
  8606. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  8607. function __() { this.constructor = d; }
  8608. __.prototype = b.prototype;
  8609. d.prototype = new __();
  8610. };
  8611. var BABYLON;
  8612. (function (BABYLON) {
  8613. var GroundMesh = (function (_super) {
  8614. __extends(GroundMesh, _super);
  8615. function GroundMesh(name, scene) {
  8616. _super.call(this, name, scene);
  8617. this.generateOctree = false;
  8618. this._worldInverse = new BABYLON.Matrix();
  8619. }
  8620. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  8621. get: function () {
  8622. return this._subdivisions;
  8623. },
  8624. enumerable: true,
  8625. configurable: true
  8626. });
  8627. GroundMesh.prototype.optimize = function (chunksCount) {
  8628. this.subdivide(this._subdivisions);
  8629. this.createOrUpdateSubmeshesOctree(32);
  8630. };
  8631. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  8632. var ray = new BABYLON.Ray(new BABYLON.Vector3(x, this.getBoundingInfo().boundingBox.maximumWorld.y + 1, z), new BABYLON.Vector3(0, -1, 0));
  8633. this.getWorldMatrix().invertToRef(this._worldInverse);
  8634. ray = BABYLON.Ray.Transform(ray, this._worldInverse);
  8635. var pickInfo = this.intersects(ray);
  8636. if (pickInfo.hit) {
  8637. return pickInfo.pickedPoint.y;
  8638. }
  8639. return 0;
  8640. };
  8641. return GroundMesh;
  8642. })(BABYLON.Mesh);
  8643. BABYLON.GroundMesh = GroundMesh;
  8644. })(BABYLON || (BABYLON = {}));
  8645. var __extends = this.__extends || function (d, b) {
  8646. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  8647. function __() { this.constructor = d; }
  8648. __.prototype = b.prototype;
  8649. d.prototype = new __();
  8650. };
  8651. var BABYLON;
  8652. (function (BABYLON) {
  8653. var InstancedMesh = (function (_super) {
  8654. __extends(InstancedMesh, _super);
  8655. function InstancedMesh(name, source) {
  8656. _super.call(this, name, source.getScene());
  8657. source.instances.push(this);
  8658. this._sourceMesh = source;
  8659. this.position.copyFrom(source.position);
  8660. this.rotation.copyFrom(source.rotation);
  8661. this.scaling.copyFrom(source.scaling);
  8662. if (source.rotationQuaternion) {
  8663. this.rotationQuaternion = source.rotationQuaternion.clone();
  8664. }
  8665. this.infiniteDistance = source.infiniteDistance;
  8666. this.setPivotMatrix(source.getPivotMatrix());
  8667. this.refreshBoundingInfo();
  8668. this._syncSubMeshes();
  8669. }
  8670. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  8671. get: function () {
  8672. return this._sourceMesh.receiveShadows;
  8673. },
  8674. enumerable: true,
  8675. configurable: true
  8676. });
  8677. Object.defineProperty(InstancedMesh.prototype, "material", {
  8678. get: function () {
  8679. return this._sourceMesh.material;
  8680. },
  8681. enumerable: true,
  8682. configurable: true
  8683. });
  8684. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  8685. get: function () {
  8686. return this._sourceMesh.visibility;
  8687. },
  8688. enumerable: true,
  8689. configurable: true
  8690. });
  8691. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  8692. get: function () {
  8693. return this._sourceMesh.skeleton;
  8694. },
  8695. enumerable: true,
  8696. configurable: true
  8697. });
  8698. InstancedMesh.prototype.getTotalVertices = function () {
  8699. return this._sourceMesh.getTotalVertices();
  8700. };
  8701. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  8702. get: function () {
  8703. return this._sourceMesh;
  8704. },
  8705. enumerable: true,
  8706. configurable: true
  8707. });
  8708. InstancedMesh.prototype.getVerticesData = function (kind) {
  8709. return this._sourceMesh.getVerticesData(kind);
  8710. };
  8711. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  8712. return this._sourceMesh.isVerticesDataPresent(kind);
  8713. };
  8714. InstancedMesh.prototype.getIndices = function () {
  8715. return this._sourceMesh.getIndices();
  8716. };
  8717. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  8718. get: function () {
  8719. return this._sourceMesh._positions;
  8720. },
  8721. enumerable: true,
  8722. configurable: true
  8723. });
  8724. InstancedMesh.prototype.refreshBoundingInfo = function () {
  8725. var data = this._sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  8726. if (data) {
  8727. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._sourceMesh.getTotalVertices());
  8728. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  8729. }
  8730. this._updateBoundingInfo();
  8731. };
  8732. InstancedMesh.prototype._preActivate = function () {
  8733. this.sourceMesh._preActivate();
  8734. };
  8735. InstancedMesh.prototype._activate = function (renderId) {
  8736. this.sourceMesh._registerInstanceForRenderId(this, renderId);
  8737. };
  8738. InstancedMesh.prototype._syncSubMeshes = function () {
  8739. this.releaseSubMeshes();
  8740. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  8741. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  8742. }
  8743. };
  8744. InstancedMesh.prototype._generatePointsArray = function () {
  8745. return this._sourceMesh._generatePointsArray();
  8746. };
  8747. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  8748. var result = this._sourceMesh.createInstance(name);
  8749. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  8750. this.refreshBoundingInfo();
  8751. if (newParent) {
  8752. result.parent = newParent;
  8753. }
  8754. if (!doNotCloneChildren) {
  8755. for (var index = 0; index < this.getScene().meshes.length; index++) {
  8756. var mesh = this.getScene().meshes[index];
  8757. if (mesh.parent == this) {
  8758. mesh.clone(mesh.name, result);
  8759. }
  8760. }
  8761. }
  8762. result.computeWorldMatrix(true);
  8763. return result;
  8764. };
  8765. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  8766. var index = this._sourceMesh.instances.indexOf(this);
  8767. this._sourceMesh.instances.splice(index, 1);
  8768. _super.prototype.dispose.call(this, doNotRecurse);
  8769. };
  8770. return InstancedMesh;
  8771. })(BABYLON.AbstractMesh);
  8772. BABYLON.InstancedMesh = InstancedMesh;
  8773. })(BABYLON || (BABYLON = {}));
  8774. var BABYLON;
  8775. (function (BABYLON) {
  8776. var SubMesh = (function () {
  8777. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  8778. if (typeof createBoundingBox === "undefined") { createBoundingBox = true; }
  8779. this.materialIndex = materialIndex;
  8780. this.verticesStart = verticesStart;
  8781. this.verticesCount = verticesCount;
  8782. this.indexStart = indexStart;
  8783. this.indexCount = indexCount;
  8784. this._renderId = 0;
  8785. this._mesh = mesh;
  8786. this._renderingMesh = renderingMesh || mesh;
  8787. mesh.subMeshes.push(this);
  8788. this._id = mesh.subMeshes.length - 1;
  8789. if (createBoundingBox) {
  8790. this.refreshBoundingInfo();
  8791. }
  8792. }
  8793. SubMesh.prototype.getBoundingInfo = function () {
  8794. return this._boundingInfo;
  8795. };
  8796. SubMesh.prototype.getMesh = function () {
  8797. return this._mesh;
  8798. };
  8799. SubMesh.prototype.getRenderingMesh = function () {
  8800. return this._renderingMesh;
  8801. };
  8802. SubMesh.prototype.getMaterial = function () {
  8803. var rootMaterial = this._renderingMesh.material;
  8804. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  8805. var multiMaterial = rootMaterial;
  8806. return multiMaterial.getSubMaterial(this.materialIndex);
  8807. }
  8808. if (!rootMaterial) {
  8809. return this._mesh.getScene().defaultMaterial;
  8810. }
  8811. return rootMaterial;
  8812. };
  8813. SubMesh.prototype.refreshBoundingInfo = function () {
  8814. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  8815. if (!data) {
  8816. this._boundingInfo = this._mesh._boundingInfo;
  8817. return;
  8818. }
  8819. var indices = this._renderingMesh.getIndices();
  8820. var extend;
  8821. if (this.indexStart === 0 && this.indexCount === indices.length) {
  8822. extend = BABYLON.Tools.ExtractMinAndMax(data, this.verticesStart, this.verticesCount);
  8823. } else {
  8824. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
  8825. }
  8826. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  8827. };
  8828. SubMesh.prototype._checkCollision = function (collider) {
  8829. return this._boundingInfo._checkCollision(collider);
  8830. };
  8831. SubMesh.prototype.updateBoundingInfo = function (world) {
  8832. if (!this._boundingInfo) {
  8833. this.refreshBoundingInfo();
  8834. }
  8835. this._boundingInfo._update(world);
  8836. };
  8837. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  8838. return this._boundingInfo.isInFrustum(frustumPlanes);
  8839. };
  8840. SubMesh.prototype.render = function () {
  8841. this._renderingMesh.render(this);
  8842. };
  8843. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  8844. if (!this._linesIndexBuffer) {
  8845. var linesIndices = [];
  8846. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  8847. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  8848. }
  8849. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  8850. this.linesIndexCount = linesIndices.length;
  8851. }
  8852. return this._linesIndexBuffer;
  8853. };
  8854. SubMesh.prototype.canIntersects = function (ray) {
  8855. return ray.intersectsBox(this._boundingInfo.boundingBox);
  8856. };
  8857. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  8858. var intersectInfo = null;
  8859. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  8860. var p0 = positions[indices[index]];
  8861. var p1 = positions[indices[index + 1]];
  8862. var p2 = positions[indices[index + 2]];
  8863. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  8864. if (currentIntersectInfo) {
  8865. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  8866. intersectInfo = currentIntersectInfo;
  8867. intersectInfo.faceId = index / 3;
  8868. if (fastCheck) {
  8869. break;
  8870. }
  8871. }
  8872. }
  8873. }
  8874. return intersectInfo;
  8875. };
  8876. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  8877. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  8878. result._boundingInfo = new BABYLON.BoundingInfo(this._boundingInfo.minimum, this._boundingInfo.maximum);
  8879. return result;
  8880. };
  8881. SubMesh.prototype.dispose = function () {
  8882. if (this._linesIndexBuffer) {
  8883. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  8884. this._linesIndexBuffer = null;
  8885. }
  8886. var index = this._mesh.subMeshes.indexOf(this);
  8887. this._mesh.subMeshes.splice(index, 1);
  8888. };
  8889. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  8890. var minVertexIndex = Number.MAX_VALUE;
  8891. var maxVertexIndex = -Number.MAX_VALUE;
  8892. renderingMesh = renderingMesh || mesh;
  8893. var indices = renderingMesh.getIndices();
  8894. for (var index = startIndex; index < startIndex + indexCount; index++) {
  8895. var vertexIndex = indices[index];
  8896. if (vertexIndex < minVertexIndex)
  8897. minVertexIndex = vertexIndex;
  8898. if (vertexIndex > maxVertexIndex)
  8899. maxVertexIndex = vertexIndex;
  8900. }
  8901. return new BABYLON.SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  8902. };
  8903. return SubMesh;
  8904. })();
  8905. BABYLON.SubMesh = SubMesh;
  8906. })(BABYLON || (BABYLON = {}));
  8907. var BABYLON;
  8908. (function (BABYLON) {
  8909. var BaseTexture = (function () {
  8910. function BaseTexture(scene) {
  8911. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  8912. this.hasAlpha = false;
  8913. this.getAlphaFromRGB = false;
  8914. this.level = 1;
  8915. this.isCube = false;
  8916. this.isRenderTarget = false;
  8917. this.animations = new Array();
  8918. this.coordinatesIndex = 0;
  8919. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  8920. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  8921. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  8922. this.anisotropicFilteringLevel = 4;
  8923. this._scene = scene;
  8924. this._scene.textures.push(this);
  8925. }
  8926. BaseTexture.prototype.getScene = function () {
  8927. return this._scene;
  8928. };
  8929. BaseTexture.prototype.getTextureMatrix = function () {
  8930. return null;
  8931. };
  8932. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  8933. return null;
  8934. };
  8935. BaseTexture.prototype.getInternalTexture = function () {
  8936. return this._texture;
  8937. };
  8938. BaseTexture.prototype.isReady = function () {
  8939. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  8940. return true;
  8941. }
  8942. if (this._texture) {
  8943. return this._texture.isReady;
  8944. }
  8945. return false;
  8946. };
  8947. BaseTexture.prototype.getSize = function () {
  8948. if (this._texture._width) {
  8949. return { width: this._texture._width, height: this._texture._height };
  8950. }
  8951. if (this._texture._size) {
  8952. return { width: this._texture._size, height: this._texture._size };
  8953. }
  8954. return { width: 0, height: 0 };
  8955. };
  8956. BaseTexture.prototype.getBaseSize = function () {
  8957. if (!this.isReady())
  8958. return { width: 0, height: 0 };
  8959. if (this._texture._size) {
  8960. return { width: this._texture._size, height: this._texture._size };
  8961. }
  8962. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  8963. };
  8964. BaseTexture.prototype._getFromCache = function (url, noMipmap) {
  8965. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  8966. for (var index = 0; index < texturesCache.length; index++) {
  8967. var texturesCacheEntry = texturesCache[index];
  8968. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  8969. texturesCacheEntry.references++;
  8970. return texturesCacheEntry;
  8971. }
  8972. }
  8973. return null;
  8974. };
  8975. BaseTexture.prototype.delayLoad = function () {
  8976. };
  8977. BaseTexture.prototype.releaseInternalTexture = function () {
  8978. if (!this._texture) {
  8979. return;
  8980. }
  8981. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  8982. this._texture.references--;
  8983. if (this._texture.references == 0) {
  8984. var index = texturesCache.indexOf(this._texture);
  8985. texturesCache.splice(index, 1);
  8986. this._scene.getEngine()._releaseTexture(this._texture);
  8987. delete this._texture;
  8988. }
  8989. };
  8990. BaseTexture.prototype.clone = function () {
  8991. return null;
  8992. };
  8993. BaseTexture.prototype.dispose = function () {
  8994. var index = this._scene.textures.indexOf(this);
  8995. if (index >= 0) {
  8996. this._scene.textures.splice(index, 1);
  8997. }
  8998. if (this._texture === undefined) {
  8999. return;
  9000. }
  9001. this.releaseInternalTexture();
  9002. if (this.onDispose) {
  9003. this.onDispose();
  9004. }
  9005. };
  9006. return BaseTexture;
  9007. })();
  9008. BABYLON.BaseTexture = BaseTexture;
  9009. })(BABYLON || (BABYLON = {}));
  9010. var BABYLON;
  9011. (function (BABYLON) {
  9012. var RenderingGroup = (function () {
  9013. function RenderingGroup(index, scene) {
  9014. this.index = index;
  9015. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  9016. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  9017. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  9018. this._scene = scene;
  9019. }
  9020. RenderingGroup.prototype.render = function (customRenderFunction, beforeTransparents) {
  9021. if (customRenderFunction) {
  9022. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, beforeTransparents);
  9023. return true;
  9024. }
  9025. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  9026. return false;
  9027. }
  9028. var engine = this._scene.getEngine();
  9029. var subIndex;
  9030. var submesh;
  9031. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  9032. submesh = this._opaqueSubMeshes.data[subIndex];
  9033. this._activeVertices += submesh.verticesCount;
  9034. submesh.render();
  9035. }
  9036. engine.setAlphaTesting(true);
  9037. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  9038. submesh = this._alphaTestSubMeshes.data[subIndex];
  9039. this._activeVertices += submesh.verticesCount;
  9040. submesh.render();
  9041. }
  9042. engine.setAlphaTesting(false);
  9043. if (beforeTransparents) {
  9044. beforeTransparents();
  9045. }
  9046. if (this._transparentSubMeshes.length) {
  9047. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  9048. submesh = this._transparentSubMeshes.data[subIndex];
  9049. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.position).length();
  9050. }
  9051. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  9052. sortedArray.sort(function (a, b) {
  9053. if (a._distanceToCamera < b._distanceToCamera) {
  9054. return 1;
  9055. }
  9056. if (a._distanceToCamera > b._distanceToCamera) {
  9057. return -1;
  9058. }
  9059. return 0;
  9060. });
  9061. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  9062. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  9063. submesh = sortedArray[subIndex];
  9064. this._activeVertices += submesh.verticesCount;
  9065. submesh.render();
  9066. }
  9067. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  9068. }
  9069. return true;
  9070. };
  9071. RenderingGroup.prototype.prepare = function () {
  9072. this._opaqueSubMeshes.reset();
  9073. this._transparentSubMeshes.reset();
  9074. this._alphaTestSubMeshes.reset();
  9075. };
  9076. RenderingGroup.prototype.dispatch = function (subMesh) {
  9077. var material = subMesh.getMaterial();
  9078. var mesh = subMesh.getMesh();
  9079. if (material.needAlphaBlending() || mesh.visibility < 1.0) {
  9080. if (material.alpha > 0 || mesh.visibility < 1.0) {
  9081. this._transparentSubMeshes.push(subMesh);
  9082. }
  9083. } else if (material.needAlphaTesting()) {
  9084. this._alphaTestSubMeshes.push(subMesh);
  9085. } else {
  9086. this._opaqueSubMeshes.push(subMesh);
  9087. }
  9088. };
  9089. return RenderingGroup;
  9090. })();
  9091. BABYLON.RenderingGroup = RenderingGroup;
  9092. })(BABYLON || (BABYLON = {}));
  9093. var BABYLON;
  9094. (function (BABYLON) {
  9095. var RenderingManager = (function () {
  9096. function RenderingManager(scene) {
  9097. this._renderingGroups = new Array();
  9098. this._scene = scene;
  9099. }
  9100. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  9101. if (this._scene._activeParticleSystems.length === 0) {
  9102. return;
  9103. }
  9104. var beforeParticlesDate = new Date().getTime();
  9105. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  9106. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  9107. if (particleSystem.renderingGroupId !== index) {
  9108. continue;
  9109. }
  9110. this._clearDepthBuffer();
  9111. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  9112. this._scene._activeParticles += particleSystem.render();
  9113. }
  9114. }
  9115. this._scene._particlesDuration += new Date().getTime() - beforeParticlesDate;
  9116. };
  9117. RenderingManager.prototype._renderSprites = function (index) {
  9118. if (this._scene.spriteManagers.length === 0) {
  9119. return;
  9120. }
  9121. var beforeSpritessDate = new Date().getTime();
  9122. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  9123. var spriteManager = this._scene.spriteManagers[id];
  9124. if (spriteManager.renderingGroupId === index) {
  9125. this._clearDepthBuffer();
  9126. spriteManager.render();
  9127. }
  9128. }
  9129. this._scene._spritesDuration += new Date().getTime() - beforeSpritessDate;
  9130. };
  9131. RenderingManager.prototype._clearDepthBuffer = function () {
  9132. if (this._depthBufferAlreadyCleaned) {
  9133. return;
  9134. }
  9135. this._scene.getEngine().clear(0, false, true);
  9136. this._depthBufferAlreadyCleaned = true;
  9137. };
  9138. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  9139. var _this = this;
  9140. for (var index = 0; index < BABYLON.RenderingManager.MAX_RENDERINGGROUPS; index++) {
  9141. this._depthBufferAlreadyCleaned = false;
  9142. var renderingGroup = this._renderingGroups[index];
  9143. if (renderingGroup) {
  9144. this._clearDepthBuffer();
  9145. if (!renderingGroup.render(customRenderFunction, function () {
  9146. if (renderSprites) {
  9147. _this._renderSprites(index);
  9148. }
  9149. })) {
  9150. this._renderingGroups.splice(index, 1);
  9151. }
  9152. } else if (renderSprites) {
  9153. this._renderSprites(index);
  9154. }
  9155. if (renderParticles) {
  9156. this._renderParticles(index, activeMeshes);
  9157. }
  9158. }
  9159. };
  9160. RenderingManager.prototype.reset = function () {
  9161. for (var index in this._renderingGroups) {
  9162. var renderingGroup = this._renderingGroups[index];
  9163. renderingGroup.prepare();
  9164. }
  9165. };
  9166. RenderingManager.prototype.dispatch = function (subMesh) {
  9167. var mesh = subMesh.getMesh();
  9168. var renderingGroupId = mesh.renderingGroupId || 0;
  9169. if (!this._renderingGroups[renderingGroupId]) {
  9170. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  9171. }
  9172. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  9173. };
  9174. RenderingManager.MAX_RENDERINGGROUPS = 4;
  9175. return RenderingManager;
  9176. })();
  9177. BABYLON.RenderingManager = RenderingManager;
  9178. })(BABYLON || (BABYLON = {}));
  9179. var __extends = this.__extends || function (d, b) {
  9180. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9181. function __() { this.constructor = d; }
  9182. __.prototype = b.prototype;
  9183. d.prototype = new __();
  9184. };
  9185. var BABYLON;
  9186. (function (BABYLON) {
  9187. var Texture = (function (_super) {
  9188. __extends(Texture, _super);
  9189. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  9190. if (typeof samplingMode === "undefined") { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  9191. if (typeof onLoad === "undefined") { onLoad = null; }
  9192. if (typeof onError === "undefined") { onError = null; }
  9193. if (typeof buffer === "undefined") { buffer = null; }
  9194. if (typeof deleteBuffer === "undefined") { deleteBuffer = false; }
  9195. _super.call(this, scene);
  9196. this.uOffset = 0;
  9197. this.vOffset = 0;
  9198. this.uScale = 1.0;
  9199. this.vScale = 1.0;
  9200. this.uAng = 0;
  9201. this.vAng = 0;
  9202. this.wAng = 0;
  9203. this.name = url;
  9204. this.url = url;
  9205. this._noMipmap = noMipmap;
  9206. this._invertY = invertY;
  9207. this._samplingMode = samplingMode;
  9208. this._buffer = buffer;
  9209. this._deleteBuffer = deleteBuffer;
  9210. if (!url) {
  9211. return;
  9212. }
  9213. this._texture = this._getFromCache(url, noMipmap);
  9214. if (!this._texture) {
  9215. if (!scene.useDelayedTextureLoading) {
  9216. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  9217. if (deleteBuffer) {
  9218. delete this._buffer;
  9219. }
  9220. } else {
  9221. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  9222. }
  9223. }
  9224. }
  9225. Texture.prototype.delayLoad = function () {
  9226. if (this.delayLoadState != BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  9227. return;
  9228. }
  9229. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  9230. this._texture = this._getFromCache(this.url, this._noMipmap);
  9231. if (!this._texture) {
  9232. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, null, null, this._buffer);
  9233. if (this._deleteBuffer) {
  9234. delete this._buffer;
  9235. }
  9236. }
  9237. };
  9238. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  9239. x -= this.uOffset + 0.5;
  9240. y -= this.vOffset + 0.5;
  9241. z -= 0.5;
  9242. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  9243. t.x *= this.uScale;
  9244. t.y *= this.vScale;
  9245. t.x += 0.5;
  9246. t.y += 0.5;
  9247. t.z += 0.5;
  9248. };
  9249. Texture.prototype.getTextureMatrix = function () {
  9250. 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) {
  9251. return this._cachedTextureMatrix;
  9252. }
  9253. this._cachedUOffset = this.uOffset;
  9254. this._cachedVOffset = this.vOffset;
  9255. this._cachedUScale = this.uScale;
  9256. this._cachedVScale = this.vScale;
  9257. this._cachedUAng = this.uAng;
  9258. this._cachedVAng = this.vAng;
  9259. this._cachedWAng = this.wAng;
  9260. if (!this._cachedTextureMatrix) {
  9261. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  9262. this._rowGenerationMatrix = new BABYLON.Matrix();
  9263. this._t0 = BABYLON.Vector3.Zero();
  9264. this._t1 = BABYLON.Vector3.Zero();
  9265. this._t2 = BABYLON.Vector3.Zero();
  9266. }
  9267. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  9268. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  9269. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  9270. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  9271. this._t1.subtractInPlace(this._t0);
  9272. this._t2.subtractInPlace(this._t0);
  9273. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  9274. this._cachedTextureMatrix.m[0] = this._t1.x;
  9275. this._cachedTextureMatrix.m[1] = this._t1.y;
  9276. this._cachedTextureMatrix.m[2] = this._t1.z;
  9277. this._cachedTextureMatrix.m[4] = this._t2.x;
  9278. this._cachedTextureMatrix.m[5] = this._t2.y;
  9279. this._cachedTextureMatrix.m[6] = this._t2.z;
  9280. this._cachedTextureMatrix.m[8] = this._t0.x;
  9281. this._cachedTextureMatrix.m[9] = this._t0.y;
  9282. this._cachedTextureMatrix.m[10] = this._t0.z;
  9283. return this._cachedTextureMatrix;
  9284. };
  9285. Texture.prototype.getReflectionTextureMatrix = function () {
  9286. if (this.uOffset === this._cachedUOffset && this.vOffset === this._cachedVOffset && this.uScale === this._cachedUScale && this.vScale === this._cachedVScale && this.coordinatesMode === this._cachedCoordinatesMode) {
  9287. return this._cachedTextureMatrix;
  9288. }
  9289. if (!this._cachedTextureMatrix) {
  9290. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  9291. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  9292. }
  9293. switch (this.coordinatesMode) {
  9294. case BABYLON.Texture.SPHERICAL_MODE:
  9295. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  9296. this._cachedTextureMatrix[0] = -0.5 * this.uScale;
  9297. this._cachedTextureMatrix[5] = -0.5 * this.vScale;
  9298. this._cachedTextureMatrix[12] = 0.5 + this.uOffset;
  9299. this._cachedTextureMatrix[13] = 0.5 + this.vOffset;
  9300. break;
  9301. case BABYLON.Texture.PLANAR_MODE:
  9302. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  9303. this._cachedTextureMatrix[0] = this.uScale;
  9304. this._cachedTextureMatrix[5] = this.vScale;
  9305. this._cachedTextureMatrix[12] = this.uOffset;
  9306. this._cachedTextureMatrix[13] = this.vOffset;
  9307. break;
  9308. case BABYLON.Texture.PROJECTION_MODE:
  9309. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  9310. this._projectionModeMatrix.m[0] = 0.5;
  9311. this._projectionModeMatrix.m[5] = -0.5;
  9312. this._projectionModeMatrix.m[10] = 0.0;
  9313. this._projectionModeMatrix.m[12] = 0.5;
  9314. this._projectionModeMatrix.m[13] = 0.5;
  9315. this._projectionModeMatrix.m[14] = 1.0;
  9316. this._projectionModeMatrix.m[15] = 1.0;
  9317. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  9318. break;
  9319. default:
  9320. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  9321. break;
  9322. }
  9323. return this._cachedTextureMatrix;
  9324. };
  9325. Texture.prototype.clone = function () {
  9326. var newTexture = new BABYLON.Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY);
  9327. newTexture.hasAlpha = this.hasAlpha;
  9328. newTexture.level = this.level;
  9329. newTexture.wrapU = this.wrapU;
  9330. newTexture.wrapV = this.wrapV;
  9331. newTexture.coordinatesIndex = this.coordinatesIndex;
  9332. newTexture.coordinatesMode = this.coordinatesMode;
  9333. newTexture.uOffset = this.uOffset;
  9334. newTexture.vOffset = this.vOffset;
  9335. newTexture.uScale = this.uScale;
  9336. newTexture.vScale = this.vScale;
  9337. newTexture.uAng = this.uAng;
  9338. newTexture.vAng = this.vAng;
  9339. newTexture.wAng = this.wAng;
  9340. return newTexture;
  9341. };
  9342. Texture.NEAREST_SAMPLINGMODE = 1;
  9343. Texture.BILINEAR_SAMPLINGMODE = 2;
  9344. Texture.TRILINEAR_SAMPLINGMODE = 3;
  9345. Texture.EXPLICIT_MODE = 0;
  9346. Texture.SPHERICAL_MODE = 1;
  9347. Texture.PLANAR_MODE = 2;
  9348. Texture.CUBIC_MODE = 3;
  9349. Texture.PROJECTION_MODE = 4;
  9350. Texture.SKYBOX_MODE = 5;
  9351. Texture.CLAMP_ADDRESSMODE = 0;
  9352. Texture.WRAP_ADDRESSMODE = 1;
  9353. Texture.MIRROR_ADDRESSMODE = 2;
  9354. return Texture;
  9355. })(BABYLON.BaseTexture);
  9356. BABYLON.Texture = Texture;
  9357. })(BABYLON || (BABYLON = {}));
  9358. var __extends = this.__extends || function (d, b) {
  9359. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9360. function __() { this.constructor = d; }
  9361. __.prototype = b.prototype;
  9362. d.prototype = new __();
  9363. };
  9364. var BABYLON;
  9365. (function (BABYLON) {
  9366. var CubeTexture = (function (_super) {
  9367. __extends(CubeTexture, _super);
  9368. function CubeTexture(rootUrl, scene, extensions, noMipmap) {
  9369. _super.call(this, scene);
  9370. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  9371. this.name = rootUrl;
  9372. this.url = rootUrl;
  9373. this._noMipmap = noMipmap;
  9374. this.hasAlpha = false;
  9375. this._texture = this._getFromCache(rootUrl, noMipmap);
  9376. if (!extensions) {
  9377. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  9378. }
  9379. this._extensions = extensions;
  9380. if (!this._texture) {
  9381. if (!scene.useDelayedTextureLoading) {
  9382. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, extensions, noMipmap);
  9383. } else {
  9384. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  9385. }
  9386. }
  9387. this.isCube = true;
  9388. this._textureMatrix = BABYLON.Matrix.Identity();
  9389. }
  9390. CubeTexture.prototype.clone = function () {
  9391. var newTexture = new BABYLON.CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap);
  9392. newTexture.level = this.level;
  9393. newTexture.wrapU = this.wrapU;
  9394. newTexture.wrapV = this.wrapV;
  9395. newTexture.coordinatesIndex = this.coordinatesIndex;
  9396. newTexture.coordinatesMode = this.coordinatesMode;
  9397. return newTexture;
  9398. };
  9399. CubeTexture.prototype.delayLoad = function () {
  9400. if (this.delayLoadState != BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  9401. return;
  9402. }
  9403. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  9404. this._texture = this._getFromCache(this.url, this._noMipmap);
  9405. if (!this._texture) {
  9406. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  9407. }
  9408. };
  9409. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  9410. return this._textureMatrix;
  9411. };
  9412. return CubeTexture;
  9413. })(BABYLON.BaseTexture);
  9414. BABYLON.CubeTexture = CubeTexture;
  9415. })(BABYLON || (BABYLON = {}));
  9416. var __extends = this.__extends || function (d, b) {
  9417. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9418. function __() { this.constructor = d; }
  9419. __.prototype = b.prototype;
  9420. d.prototype = new __();
  9421. };
  9422. var BABYLON;
  9423. (function (BABYLON) {
  9424. var RenderTargetTexture = (function (_super) {
  9425. __extends(RenderTargetTexture, _super);
  9426. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio) {
  9427. if (typeof doNotChangeAspectRatio === "undefined") { doNotChangeAspectRatio = true; }
  9428. _super.call(this, null, scene, !generateMipMaps);
  9429. this.renderList = new Array();
  9430. this.renderParticles = true;
  9431. this.renderSprites = false;
  9432. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  9433. this._currentRefreshId = -1;
  9434. this._refreshRate = 1;
  9435. this.name = name;
  9436. this.isRenderTarget = true;
  9437. this._size = size;
  9438. this._generateMipMaps = generateMipMaps;
  9439. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  9440. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  9441. this._renderingManager = new BABYLON.RenderingManager(scene);
  9442. }
  9443. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  9444. this._currentRefreshId = -1;
  9445. };
  9446. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  9447. get: function () {
  9448. return this._refreshRate;
  9449. },
  9450. set: function (value) {
  9451. this._refreshRate = value;
  9452. this.resetRefreshCounter();
  9453. },
  9454. enumerable: true,
  9455. configurable: true
  9456. });
  9457. RenderTargetTexture.prototype._shouldRender = function () {
  9458. if (this._currentRefreshId === -1) {
  9459. this._currentRefreshId = 1;
  9460. return true;
  9461. }
  9462. if (this.refreshRate == this._currentRefreshId) {
  9463. this._currentRefreshId = 1;
  9464. return true;
  9465. }
  9466. this._currentRefreshId++;
  9467. return false;
  9468. };
  9469. RenderTargetTexture.prototype.getRenderSize = function () {
  9470. return this._size;
  9471. };
  9472. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  9473. this.releaseInternalTexture();
  9474. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  9475. };
  9476. RenderTargetTexture.prototype.render = function (useCameraPostProcess) {
  9477. var scene = this.getScene();
  9478. var engine = scene.getEngine();
  9479. if (this._waitingRenderList) {
  9480. this.renderList = [];
  9481. for (var index = 0; index < this._waitingRenderList.length; index++) {
  9482. var id = this._waitingRenderList[index];
  9483. this.renderList.push(scene.getMeshByID(id));
  9484. }
  9485. delete this._waitingRenderList;
  9486. }
  9487. if (!this.renderList) {
  9488. return;
  9489. }
  9490. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  9491. engine.bindFramebuffer(this._texture);
  9492. }
  9493. engine.clear(scene.clearColor, true, true);
  9494. this._renderingManager.reset();
  9495. for (var meshIndex = 0; meshIndex < this.renderList.length; meshIndex++) {
  9496. var mesh = this.renderList[meshIndex];
  9497. if (mesh) {
  9498. if (!mesh.isReady() || (mesh.material && !mesh.material.isReady())) {
  9499. this.resetRefreshCounter();
  9500. continue;
  9501. }
  9502. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) != 0)) {
  9503. mesh._activate(scene.getRenderId());
  9504. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  9505. var subMesh = mesh.subMeshes[subIndex];
  9506. scene._activeVertices += subMesh.verticesCount;
  9507. this._renderingManager.dispatch(subMesh);
  9508. }
  9509. }
  9510. }
  9511. }
  9512. if (!this._doNotChangeAspectRatio) {
  9513. scene.updateTransformMatrix(true);
  9514. }
  9515. if (this.onBeforeRender) {
  9516. this.onBeforeRender();
  9517. }
  9518. this._renderingManager.render(this.customRenderFunction, this.renderList, this.renderParticles, this.renderSprites);
  9519. if (useCameraPostProcess) {
  9520. scene.postProcessManager._finalizeFrame(false, this._texture);
  9521. }
  9522. if (this.onAfterRender) {
  9523. this.onAfterRender();
  9524. }
  9525. engine.unBindFramebuffer(this._texture);
  9526. if (!this._doNotChangeAspectRatio) {
  9527. scene.updateTransformMatrix(true);
  9528. }
  9529. };
  9530. RenderTargetTexture.prototype.clone = function () {
  9531. var textureSize = this.getSize();
  9532. var newTexture = new BABYLON.RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  9533. newTexture.hasAlpha = this.hasAlpha;
  9534. newTexture.level = this.level;
  9535. newTexture.coordinatesMode = this.coordinatesMode;
  9536. newTexture.renderList = this.renderList.slice(0);
  9537. return newTexture;
  9538. };
  9539. return RenderTargetTexture;
  9540. })(BABYLON.Texture);
  9541. BABYLON.RenderTargetTexture = RenderTargetTexture;
  9542. })(BABYLON || (BABYLON = {}));
  9543. var __extends = this.__extends || function (d, b) {
  9544. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9545. function __() { this.constructor = d; }
  9546. __.prototype = b.prototype;
  9547. d.prototype = new __();
  9548. };
  9549. var BABYLON;
  9550. (function (BABYLON) {
  9551. var ProceduralTexture = (function (_super) {
  9552. __extends(ProceduralTexture, _super);
  9553. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps) {
  9554. _super.call(this, null, scene, !generateMipMaps);
  9555. this._currentRefreshId = -1;
  9556. this._refreshRate = 1;
  9557. this._vertexDeclaration = [2];
  9558. this._vertexStrideSize = 2 * 4;
  9559. this._uniforms = new Array();
  9560. this._samplers = new Array();
  9561. this._textures = new Array();
  9562. this._floats = new Array();
  9563. this._floatsArrays = {};
  9564. this._colors3 = new Array();
  9565. this._colors4 = new Array();
  9566. this._vectors2 = new Array();
  9567. this._vectors3 = new Array();
  9568. this._matrices = new Array();
  9569. scene._proceduralTextures.push(this);
  9570. this.name = name;
  9571. this.isRenderTarget = true;
  9572. this._size = size;
  9573. this._generateMipMaps = generateMipMaps;
  9574. this._fragment = fragment;
  9575. this._fallbackTexture = fallbackTexture;
  9576. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  9577. var vertices = [];
  9578. vertices.push(1, 1);
  9579. vertices.push(-1, 1);
  9580. vertices.push(-1, -1);
  9581. vertices.push(1, -1);
  9582. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  9583. var indices = [];
  9584. indices.push(0);
  9585. indices.push(1);
  9586. indices.push(2);
  9587. indices.push(0);
  9588. indices.push(2);
  9589. indices.push(3);
  9590. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  9591. }
  9592. ProceduralTexture.prototype.isReady = function () {
  9593. var _this = this;
  9594. var engine = this.getScene().getEngine();
  9595. this._effect = engine.createEffect({ vertex: "procedural", fragment: this._fragment }, ["position"], this._uniforms, this._samplers, "", null, null, function () {
  9596. _this.releaseInternalTexture();
  9597. _this._texture = _this._fallbackTexture._texture;
  9598. _this._texture.references++;
  9599. });
  9600. return this._effect.isReady();
  9601. };
  9602. ProceduralTexture.prototype.resetRefreshCounter = function () {
  9603. this._currentRefreshId = -1;
  9604. };
  9605. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  9606. get: function () {
  9607. return this._refreshRate;
  9608. },
  9609. set: function (value) {
  9610. this._refreshRate = value;
  9611. this.resetRefreshCounter();
  9612. },
  9613. enumerable: true,
  9614. configurable: true
  9615. });
  9616. ProceduralTexture.prototype._shouldRender = function () {
  9617. if (!this.isReady() || !this._texture) {
  9618. return false;
  9619. }
  9620. if (this._currentRefreshId === -1) {
  9621. this._currentRefreshId = 1;
  9622. return true;
  9623. }
  9624. if (this.refreshRate == this._currentRefreshId) {
  9625. this._currentRefreshId = 1;
  9626. return true;
  9627. }
  9628. this._currentRefreshId++;
  9629. return false;
  9630. };
  9631. ProceduralTexture.prototype.getRenderSize = function () {
  9632. return this._size;
  9633. };
  9634. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  9635. this.releaseInternalTexture();
  9636. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  9637. };
  9638. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  9639. if (this._uniforms.indexOf(uniformName) === -1) {
  9640. this._uniforms.push(uniformName);
  9641. }
  9642. };
  9643. ProceduralTexture.prototype.setTexture = function (name, texture) {
  9644. if (this._samplers.indexOf(name) === -1) {
  9645. this._samplers.push(name);
  9646. }
  9647. this._textures[name] = texture;
  9648. return this;
  9649. };
  9650. ProceduralTexture.prototype.setFloat = function (name, value) {
  9651. this._checkUniform(name);
  9652. this._floats[name] = value;
  9653. return this;
  9654. };
  9655. ProceduralTexture.prototype.setFloats = function (name, value) {
  9656. this._checkUniform(name);
  9657. this._floatsArrays[name] = value;
  9658. return this;
  9659. };
  9660. ProceduralTexture.prototype.setColor3 = function (name, value) {
  9661. this._checkUniform(name);
  9662. this._colors3[name] = value;
  9663. return this;
  9664. };
  9665. ProceduralTexture.prototype.setColor4 = function (name, value) {
  9666. this._checkUniform(name);
  9667. this._colors4[name] = value;
  9668. return this;
  9669. };
  9670. ProceduralTexture.prototype.setVector2 = function (name, value) {
  9671. this._checkUniform(name);
  9672. this._vectors2[name] = value;
  9673. return this;
  9674. };
  9675. ProceduralTexture.prototype.setVector3 = function (name, value) {
  9676. this._checkUniform(name);
  9677. this._vectors3[name] = value;
  9678. return this;
  9679. };
  9680. ProceduralTexture.prototype.setMatrix = function (name, value) {
  9681. this._checkUniform(name);
  9682. this._matrices[name] = value;
  9683. return this;
  9684. };
  9685. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  9686. var scene = this.getScene();
  9687. var engine = scene.getEngine();
  9688. engine.bindFramebuffer(this._texture);
  9689. engine.clear(scene.clearColor, true, true);
  9690. engine.enableEffect(this._effect);
  9691. engine.setState(false);
  9692. for (var name in this._textures) {
  9693. this._effect.setTexture(name, this._textures[name]);
  9694. }
  9695. for (name in this._floats) {
  9696. this._effect.setFloat(name, this._floats[name]);
  9697. }
  9698. for (name in this._floatsArrays) {
  9699. this._effect.setArray(name, this._floatsArrays[name]);
  9700. }
  9701. for (name in this._colors3) {
  9702. this._effect.setColor3(name, this._colors3[name]);
  9703. }
  9704. for (name in this._colors4) {
  9705. var color = this._colors4[name];
  9706. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  9707. }
  9708. for (name in this._vectors2) {
  9709. this._effect.setVector2(name, this._vectors2[name]);
  9710. }
  9711. for (name in this._vectors3) {
  9712. this._effect.setVector3(name, this._vectors3[name]);
  9713. }
  9714. for (name in this._matrices) {
  9715. this._effect.setMatrix(name, this._matrices[name]);
  9716. }
  9717. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  9718. engine.draw(true, 0, 6);
  9719. engine.unBindFramebuffer(this._texture);
  9720. };
  9721. ProceduralTexture.prototype.clone = function () {
  9722. var textureSize = this.getSize();
  9723. var newTexture = new BABYLON.ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  9724. newTexture.hasAlpha = this.hasAlpha;
  9725. newTexture.level = this.level;
  9726. newTexture.coordinatesMode = this.coordinatesMode;
  9727. return newTexture;
  9728. };
  9729. ProceduralTexture.prototype.dispose = function () {
  9730. var index = this.getScene()._proceduralTextures.indexOf(this);
  9731. if (index >= 0) {
  9732. this.getScene()._proceduralTextures.splice(index, 1);
  9733. }
  9734. _super.prototype.dispose.call(this);
  9735. };
  9736. return ProceduralTexture;
  9737. })(BABYLON.Texture);
  9738. BABYLON.ProceduralTexture = ProceduralTexture;
  9739. })(BABYLON || (BABYLON = {}));
  9740. var __extends = this.__extends || function (d, b) {
  9741. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9742. function __() { this.constructor = d; }
  9743. __.prototype = b.prototype;
  9744. d.prototype = new __();
  9745. };
  9746. var BABYLON;
  9747. (function (BABYLON) {
  9748. var WoodProceduralTexture = (function (_super) {
  9749. __extends(WoodProceduralTexture, _super);
  9750. function WoodProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  9751. _super.call(this, name, size, "wood", scene, fallbackTexture, generateMipMaps);
  9752. this._ampScale = 0.03;
  9753. this._ringScale = 5;
  9754. this._woodColor1 = new BABYLON.Color3(0.80, 0.55, 0.01);
  9755. this._woodColor2 = new BABYLON.Color3(0.60, 0.41, 0.0);
  9756. this.updateShaderUniforms();
  9757. this.refreshRate = 0;
  9758. }
  9759. WoodProceduralTexture.prototype.updateShaderUniforms = function () {
  9760. this.setFloat("ampScale", this._ampScale);
  9761. this.setFloat("ringScale", this._ringScale);
  9762. this.setColor3("woodColor1", this._woodColor1);
  9763. this.setColor3("woodColor2", this._woodColor2);
  9764. };
  9765. Object.defineProperty(WoodProceduralTexture.prototype, "ampScale", {
  9766. get: function () {
  9767. return this._ampScale;
  9768. },
  9769. set: function (value) {
  9770. this._ampScale = value;
  9771. this.updateShaderUniforms();
  9772. },
  9773. enumerable: true,
  9774. configurable: true
  9775. });
  9776. Object.defineProperty(WoodProceduralTexture.prototype, "ringScale", {
  9777. get: function () {
  9778. return this._ringScale;
  9779. },
  9780. set: function (value) {
  9781. this._ringScale = value;
  9782. this.updateShaderUniforms();
  9783. },
  9784. enumerable: true,
  9785. configurable: true
  9786. });
  9787. Object.defineProperty(WoodProceduralTexture.prototype, "woodColor1", {
  9788. get: function () {
  9789. return this._woodColor1;
  9790. },
  9791. set: function (value) {
  9792. this._woodColor1 = value;
  9793. this.updateShaderUniforms();
  9794. },
  9795. enumerable: true,
  9796. configurable: true
  9797. });
  9798. Object.defineProperty(WoodProceduralTexture.prototype, "woodColor2", {
  9799. get: function () {
  9800. return this._woodColor2;
  9801. },
  9802. set: function (value) {
  9803. this._woodColor2 = value;
  9804. this.updateShaderUniforms();
  9805. },
  9806. enumerable: true,
  9807. configurable: true
  9808. });
  9809. return WoodProceduralTexture;
  9810. })(BABYLON.ProceduralTexture);
  9811. BABYLON.WoodProceduralTexture = WoodProceduralTexture;
  9812. var FireProceduralTexture = (function (_super) {
  9813. __extends(FireProceduralTexture, _super);
  9814. function FireProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  9815. _super.call(this, name, size, "fire", scene, fallbackTexture, generateMipMaps);
  9816. this._time = 0.0;
  9817. this._speed = new BABYLON.Vector2(0.5, 0.3);
  9818. this._shift = 1.6;
  9819. this._alpha = 1.0;
  9820. this._autoGenerateTime = true;
  9821. this._fireColors = FireProceduralTexture.RedFireColors;
  9822. this.updateShaderUniforms();
  9823. this.refreshRate = 1;
  9824. }
  9825. FireProceduralTexture.prototype.updateShaderUniforms = function () {
  9826. this.setFloat("iGlobalTime", this._time);
  9827. this.setVector2("speed", this._speed);
  9828. this.setFloat("shift", this._shift);
  9829. this.setFloat("alpha", this._alpha);
  9830. this.setColor3("c1", new BABYLON.Color3(this._fireColors[0][0], this._fireColors[0][1], this._fireColors[0][2]));
  9831. this.setColor3("c2", new BABYLON.Color3(this._fireColors[1][0], this._fireColors[1][1], this._fireColors[1][2]));
  9832. this.setColor3("c3", new BABYLON.Color3(this._fireColors[2][0], this._fireColors[2][1], this._fireColors[2][2]));
  9833. this.setColor3("c4", new BABYLON.Color3(this._fireColors[3][0], this._fireColors[3][1], this._fireColors[3][2]));
  9834. this.setColor3("c5", new BABYLON.Color3(this._fireColors[4][0], this._fireColors[4][1], this._fireColors[4][2]));
  9835. this.setColor3("c6", new BABYLON.Color3(this._fireColors[5][0], this._fireColors[5][1], this._fireColors[5][2]));
  9836. };
  9837. FireProceduralTexture.prototype.render = function (useCameraPostProcess) {
  9838. if (this._autoGenerateTime) {
  9839. this._time += this.getScene().getAnimationRatio() * 0.03;
  9840. this.updateShaderUniforms();
  9841. }
  9842. _super.prototype.render.call(this, useCameraPostProcess);
  9843. };
  9844. Object.defineProperty(FireProceduralTexture, "PurpleFireColors", {
  9845. get: function () {
  9846. return [
  9847. [0.5, 0.0, 1.0],
  9848. [0.9, 0.0, 1.0],
  9849. [0.2, 0.0, 1.0],
  9850. [1.0, 0.9, 1.0],
  9851. [0.1, 0.1, 1.0],
  9852. [0.9, 0.9, 1.0]
  9853. ];
  9854. },
  9855. enumerable: true,
  9856. configurable: true
  9857. });
  9858. Object.defineProperty(FireProceduralTexture, "GreenFireColors", {
  9859. get: function () {
  9860. return [
  9861. [0.5, 1.0, 0.0],
  9862. [0.5, 1.0, 0.0],
  9863. [0.3, 0.4, 0.0],
  9864. [0.5, 1.0, 0.0],
  9865. [0.2, 0.0, 0.0],
  9866. [0.5, 1.0, 0.0]
  9867. ];
  9868. },
  9869. enumerable: true,
  9870. configurable: true
  9871. });
  9872. Object.defineProperty(FireProceduralTexture, "RedFireColors", {
  9873. get: function () {
  9874. return [
  9875. [0.5, 0.0, 0.1],
  9876. [0.9, 0.0, 0.0],
  9877. [0.2, 0.0, 0.0],
  9878. [1.0, 0.9, 0.0],
  9879. [0.1, 0.1, 0.1],
  9880. [0.9, 0.9, 0.9]
  9881. ];
  9882. },
  9883. enumerable: true,
  9884. configurable: true
  9885. });
  9886. Object.defineProperty(FireProceduralTexture, "BlueFireColors", {
  9887. get: function () {
  9888. return [
  9889. [0.1, 0.0, 0.5],
  9890. [0.0, 0.0, 0.5],
  9891. [0.1, 0.0, 0.2],
  9892. [0.0, 0.0, 1.0],
  9893. [0.1, 0.2, 0.3],
  9894. [0.0, 0.2, 0.9]
  9895. ];
  9896. },
  9897. enumerable: true,
  9898. configurable: true
  9899. });
  9900. Object.defineProperty(FireProceduralTexture.prototype, "fireColors", {
  9901. get: function () {
  9902. return this._fireColors;
  9903. },
  9904. set: function (value) {
  9905. this._fireColors = value;
  9906. this.updateShaderUniforms();
  9907. },
  9908. enumerable: true,
  9909. configurable: true
  9910. });
  9911. Object.defineProperty(FireProceduralTexture.prototype, "time", {
  9912. get: function () {
  9913. return this._time;
  9914. },
  9915. set: function (value) {
  9916. this._time = value;
  9917. this.updateShaderUniforms();
  9918. },
  9919. enumerable: true,
  9920. configurable: true
  9921. });
  9922. Object.defineProperty(FireProceduralTexture.prototype, "speed", {
  9923. get: function () {
  9924. return this._speed;
  9925. },
  9926. set: function (value) {
  9927. this._speed = value;
  9928. this.updateShaderUniforms();
  9929. },
  9930. enumerable: true,
  9931. configurable: true
  9932. });
  9933. Object.defineProperty(FireProceduralTexture.prototype, "shift", {
  9934. get: function () {
  9935. return this._shift;
  9936. },
  9937. set: function (value) {
  9938. this._shift = value;
  9939. this.updateShaderUniforms();
  9940. },
  9941. enumerable: true,
  9942. configurable: true
  9943. });
  9944. Object.defineProperty(FireProceduralTexture.prototype, "alpha", {
  9945. get: function () {
  9946. return this._alpha;
  9947. },
  9948. set: function (value) {
  9949. this._alpha = value;
  9950. this.updateShaderUniforms();
  9951. },
  9952. enumerable: true,
  9953. configurable: true
  9954. });
  9955. return FireProceduralTexture;
  9956. })(BABYLON.ProceduralTexture);
  9957. BABYLON.FireProceduralTexture = FireProceduralTexture;
  9958. })(BABYLON || (BABYLON = {}));
  9959. var __extends = this.__extends || function (d, b) {
  9960. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9961. function __() { this.constructor = d; }
  9962. __.prototype = b.prototype;
  9963. d.prototype = new __();
  9964. };
  9965. var BABYLON;
  9966. (function (BABYLON) {
  9967. var MirrorTexture = (function (_super) {
  9968. __extends(MirrorTexture, _super);
  9969. function MirrorTexture(name, size, scene, generateMipMaps) {
  9970. var _this = this;
  9971. _super.call(this, name, size, scene, generateMipMaps, true);
  9972. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  9973. this._transformMatrix = BABYLON.Matrix.Zero();
  9974. this._mirrorMatrix = BABYLON.Matrix.Zero();
  9975. this.onBeforeRender = function () {
  9976. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  9977. _this._savedViewMatrix = scene.getViewMatrix();
  9978. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  9979. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  9980. scene.clipPlane = _this.mirrorPlane;
  9981. scene.getEngine().cullBackFaces = false;
  9982. };
  9983. this.onAfterRender = function () {
  9984. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  9985. scene.getEngine().cullBackFaces = true;
  9986. delete scene.clipPlane;
  9987. };
  9988. }
  9989. MirrorTexture.prototype.clone = function () {
  9990. var textureSize = this.getSize();
  9991. var newTexture = new BABYLON.MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  9992. newTexture.hasAlpha = this.hasAlpha;
  9993. newTexture.level = this.level;
  9994. newTexture.mirrorPlane = this.mirrorPlane.clone();
  9995. newTexture.renderList = this.renderList.slice(0);
  9996. return newTexture;
  9997. };
  9998. return MirrorTexture;
  9999. })(BABYLON.RenderTargetTexture);
  10000. BABYLON.MirrorTexture = MirrorTexture;
  10001. })(BABYLON || (BABYLON = {}));
  10002. var __extends = this.__extends || function (d, b) {
  10003. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  10004. function __() { this.constructor = d; }
  10005. __.prototype = b.prototype;
  10006. d.prototype = new __();
  10007. };
  10008. var BABYLON;
  10009. (function (BABYLON) {
  10010. var DynamicTexture = (function (_super) {
  10011. __extends(DynamicTexture, _super);
  10012. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  10013. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  10014. _super.call(this, null, scene, !generateMipMaps);
  10015. this.name = name;
  10016. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  10017. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  10018. this._generateMipMaps = generateMipMaps;
  10019. if (options.getContext) {
  10020. this._canvas = options;
  10021. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  10022. } else {
  10023. this._canvas = document.createElement("canvas");
  10024. if (options.width) {
  10025. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  10026. } else {
  10027. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  10028. }
  10029. }
  10030. var textureSize = this.getSize();
  10031. this._canvas.width = textureSize.width;
  10032. this._canvas.height = textureSize.height;
  10033. this._context = this._canvas.getContext("2d");
  10034. }
  10035. DynamicTexture.prototype.getContext = function () {
  10036. return this._context;
  10037. };
  10038. DynamicTexture.prototype.update = function (invertY) {
  10039. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  10040. };
  10041. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY) {
  10042. var size = this.getSize();
  10043. if (clearColor) {
  10044. this._context.fillStyle = clearColor;
  10045. this._context.fillRect(0, 0, size.width, size.height);
  10046. }
  10047. this._context.font = font;
  10048. if (x === null) {
  10049. var textSize = this._context.measureText(text);
  10050. x = (size.width - textSize.width) / 2;
  10051. }
  10052. this._context.fillStyle = color;
  10053. this._context.fillText(text, x, y);
  10054. this.update(invertY);
  10055. };
  10056. DynamicTexture.prototype.clone = function () {
  10057. var textureSize = this.getSize();
  10058. var newTexture = new BABYLON.DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  10059. newTexture.hasAlpha = this.hasAlpha;
  10060. newTexture.level = this.level;
  10061. newTexture.wrapU = this.wrapU;
  10062. newTexture.wrapV = this.wrapV;
  10063. return newTexture;
  10064. };
  10065. return DynamicTexture;
  10066. })(BABYLON.Texture);
  10067. BABYLON.DynamicTexture = DynamicTexture;
  10068. })(BABYLON || (BABYLON = {}));
  10069. var __extends = this.__extends || function (d, b) {
  10070. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  10071. function __() { this.constructor = d; }
  10072. __.prototype = b.prototype;
  10073. d.prototype = new __();
  10074. };
  10075. var BABYLON;
  10076. (function (BABYLON) {
  10077. var VideoTexture = (function (_super) {
  10078. __extends(VideoTexture, _super);
  10079. function VideoTexture(name, urls, size, scene, generateMipMaps, invertY, samplingMode) {
  10080. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  10081. var _this = this;
  10082. _super.call(this, null, scene, !generateMipMaps, invertY);
  10083. this._autoLaunch = true;
  10084. this.name = name;
  10085. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  10086. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  10087. var requiredWidth = size.width || size;
  10088. var requiredHeight = size.height || size;
  10089. this._texture = scene.getEngine().createDynamicTexture(requiredWidth, requiredHeight, generateMipMaps, samplingMode);
  10090. var textureSize = this.getSize();
  10091. this.video = document.createElement("video");
  10092. this.video.width = textureSize.width;
  10093. this.video.height = textureSize.height;
  10094. this.video.autoplay = false;
  10095. this.video.loop = true;
  10096. this.video.addEventListener("canplaythrough", function () {
  10097. if (_this._texture) {
  10098. _this._texture.isReady = true;
  10099. }
  10100. });
  10101. urls.forEach(function (url) {
  10102. var source = document.createElement("source");
  10103. source.src = url;
  10104. _this.video.appendChild(source);
  10105. });
  10106. this._lastUpdate = new Date().getTime();
  10107. }
  10108. VideoTexture.prototype.update = function () {
  10109. if (this._autoLaunch) {
  10110. this._autoLaunch = false;
  10111. this.video.play();
  10112. }
  10113. var now = new Date().getTime();
  10114. if (now - this._lastUpdate < 15) {
  10115. return false;
  10116. }
  10117. this._lastUpdate = now;
  10118. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  10119. return true;
  10120. };
  10121. return VideoTexture;
  10122. })(BABYLON.Texture);
  10123. BABYLON.VideoTexture = VideoTexture;
  10124. })(BABYLON || (BABYLON = {}));
  10125. var BABYLON;
  10126. (function (BABYLON) {
  10127. var EffectFallbacks = (function () {
  10128. function EffectFallbacks() {
  10129. this._defines = {};
  10130. this._currentRank = 32;
  10131. this._maxRank = -1;
  10132. }
  10133. EffectFallbacks.prototype.addFallback = function (rank, define) {
  10134. if (!this._defines[rank]) {
  10135. if (rank < this._currentRank) {
  10136. this._currentRank = rank;
  10137. }
  10138. if (rank > this._maxRank) {
  10139. this._maxRank = rank;
  10140. }
  10141. this._defines[rank] = new Array();
  10142. }
  10143. this._defines[rank].push(define);
  10144. };
  10145. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  10146. get: function () {
  10147. return this._currentRank <= this._maxRank;
  10148. },
  10149. enumerable: true,
  10150. configurable: true
  10151. });
  10152. EffectFallbacks.prototype.reduce = function (currentDefines) {
  10153. var currentFallbacks = this._defines[this._currentRank];
  10154. for (var index = 0; index < currentFallbacks.length; index++) {
  10155. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  10156. }
  10157. this._currentRank++;
  10158. return currentDefines;
  10159. };
  10160. return EffectFallbacks;
  10161. })();
  10162. BABYLON.EffectFallbacks = EffectFallbacks;
  10163. var Effect = (function () {
  10164. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  10165. var _this = this;
  10166. this._isReady = false;
  10167. this._compilationError = "";
  10168. this._valueCache = [];
  10169. this._engine = engine;
  10170. this.name = baseName;
  10171. this.defines = defines;
  10172. this._uniformsNames = uniformsNames.concat(samplers);
  10173. this._samplers = samplers;
  10174. this._attributesNames = attributesNames;
  10175. this.onError = onError;
  10176. this.onCompiled = onCompiled;
  10177. var vertexSource;
  10178. var fragmentSource;
  10179. if (baseName.vertexElement) {
  10180. vertexSource = document.getElementById(baseName.vertexElement);
  10181. if (!vertexSource) {
  10182. vertexSource = baseName.vertexElement;
  10183. }
  10184. } else {
  10185. vertexSource = baseName.vertex || baseName;
  10186. }
  10187. if (baseName.fragmentElement) {
  10188. fragmentSource = document.getElementById(baseName.fragmentElement);
  10189. if (!fragmentSource) {
  10190. fragmentSource = baseName.fragmentElement;
  10191. }
  10192. } else {
  10193. fragmentSource = baseName.fragment || baseName;
  10194. }
  10195. this._loadVertexShader(vertexSource, function (vertexCode) {
  10196. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  10197. _this._prepareEffect(vertexCode, fragmentCode, attributesNames, defines, fallbacks);
  10198. });
  10199. });
  10200. }
  10201. Effect.prototype.isReady = function () {
  10202. return this._isReady;
  10203. };
  10204. Effect.prototype.getProgram = function () {
  10205. return this._program;
  10206. };
  10207. Effect.prototype.getAttributesNames = function () {
  10208. return this._attributesNames;
  10209. };
  10210. Effect.prototype.getAttributeLocation = function (index) {
  10211. return this._attributes[index];
  10212. };
  10213. Effect.prototype.getAttributeLocationByName = function (name) {
  10214. var index = this._attributesNames.indexOf(name);
  10215. return this._attributes[index];
  10216. };
  10217. Effect.prototype.getAttributesCount = function () {
  10218. return this._attributes.length;
  10219. };
  10220. Effect.prototype.getUniformIndex = function (uniformName) {
  10221. return this._uniformsNames.indexOf(uniformName);
  10222. };
  10223. Effect.prototype.getUniform = function (uniformName) {
  10224. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  10225. };
  10226. Effect.prototype.getSamplers = function () {
  10227. return this._samplers;
  10228. };
  10229. Effect.prototype.getCompilationError = function () {
  10230. return this._compilationError;
  10231. };
  10232. Effect.prototype._loadVertexShader = function (vertex, callback) {
  10233. if (vertex instanceof HTMLElement) {
  10234. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  10235. callback(vertexCode);
  10236. return;
  10237. }
  10238. if (BABYLON.Effect.ShadersStore[vertex + "VertexShader"]) {
  10239. callback(BABYLON.Effect.ShadersStore[vertex + "VertexShader"]);
  10240. return;
  10241. }
  10242. var vertexShaderUrl;
  10243. if (vertex[0] === ".") {
  10244. vertexShaderUrl = vertex;
  10245. } else {
  10246. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  10247. }
  10248. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  10249. };
  10250. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  10251. if (fragment instanceof HTMLElement) {
  10252. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  10253. callback(fragmentCode);
  10254. return;
  10255. }
  10256. if (BABYLON.Effect.ShadersStore[fragment + "PixelShader"]) {
  10257. callback(BABYLON.Effect.ShadersStore[fragment + "PixelShader"]);
  10258. return;
  10259. }
  10260. if (BABYLON.Effect.ShadersStore[fragment + "FragmentShader"]) {
  10261. callback(BABYLON.Effect.ShadersStore[fragment + "FragmentShader"]);
  10262. return;
  10263. }
  10264. var fragmentShaderUrl;
  10265. if (fragment[0] === ".") {
  10266. fragmentShaderUrl = fragment;
  10267. } else {
  10268. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  10269. }
  10270. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  10271. };
  10272. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  10273. try {
  10274. var engine = this._engine;
  10275. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  10276. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  10277. this._attributes = engine.getAttributes(this._program, attributesNames);
  10278. for (var index = 0; index < this._samplers.length; index++) {
  10279. var sampler = this.getUniform(this._samplers[index]);
  10280. if (sampler == null) {
  10281. this._samplers.splice(index, 1);
  10282. index--;
  10283. }
  10284. }
  10285. engine.bindSamplers(this);
  10286. this._isReady = true;
  10287. if (this.onCompiled) {
  10288. this.onCompiled(this);
  10289. }
  10290. } catch (e) {
  10291. if (fallbacks && fallbacks.isMoreFallbacks) {
  10292. defines = fallbacks.reduce(defines);
  10293. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  10294. } else {
  10295. BABYLON.Tools.Error("Unable to compile effect: " + this.name);
  10296. BABYLON.Tools.Error("Defines: " + defines);
  10297. BABYLON.Tools.Error("Error: " + e.message);
  10298. this._compilationError = e.message;
  10299. if (this.onError) {
  10300. this.onError(this, this._compilationError);
  10301. }
  10302. }
  10303. }
  10304. };
  10305. Effect.prototype._bindTexture = function (channel, texture) {
  10306. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  10307. };
  10308. Effect.prototype.setTexture = function (channel, texture) {
  10309. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  10310. };
  10311. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  10312. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  10313. };
  10314. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  10315. if (!this._valueCache[uniformName]) {
  10316. this._valueCache[uniformName] = [x, y];
  10317. return;
  10318. }
  10319. this._valueCache[uniformName][0] = x;
  10320. this._valueCache[uniformName][1] = y;
  10321. };
  10322. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  10323. if (!this._valueCache[uniformName]) {
  10324. this._valueCache[uniformName] = [x, y, z];
  10325. return;
  10326. }
  10327. this._valueCache[uniformName][0] = x;
  10328. this._valueCache[uniformName][1] = y;
  10329. this._valueCache[uniformName][2] = z;
  10330. };
  10331. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  10332. if (!this._valueCache[uniformName]) {
  10333. this._valueCache[uniformName] = [x, y, z, w];
  10334. return;
  10335. }
  10336. this._valueCache[uniformName][0] = x;
  10337. this._valueCache[uniformName][1] = y;
  10338. this._valueCache[uniformName][2] = z;
  10339. this._valueCache[uniformName][3] = w;
  10340. };
  10341. Effect.prototype.setArray = function (uniformName, array) {
  10342. this._engine.setArray(this.getUniform(uniformName), array);
  10343. return this;
  10344. };
  10345. Effect.prototype.setMatrices = function (uniformName, matrices) {
  10346. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  10347. return this;
  10348. };
  10349. Effect.prototype.setMatrix = function (uniformName, matrix) {
  10350. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  10351. return this;
  10352. };
  10353. Effect.prototype.setFloat = function (uniformName, value) {
  10354. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  10355. return this;
  10356. this._valueCache[uniformName] = value;
  10357. this._engine.setFloat(this.getUniform(uniformName), value);
  10358. return this;
  10359. };
  10360. Effect.prototype.setBool = function (uniformName, bool) {
  10361. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  10362. return this;
  10363. this._valueCache[uniformName] = bool;
  10364. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  10365. return this;
  10366. };
  10367. Effect.prototype.setVector2 = function (uniformName, vector2) {
  10368. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] == vector2.x && this._valueCache[uniformName][1] == vector2.y)
  10369. return this;
  10370. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  10371. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  10372. return this;
  10373. };
  10374. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  10375. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] == x && this._valueCache[uniformName][1] == y)
  10376. return this;
  10377. this._cacheFloat2(uniformName, x, y);
  10378. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  10379. return this;
  10380. };
  10381. Effect.prototype.setVector3 = function (uniformName, vector3) {
  10382. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] == vector3.x && this._valueCache[uniformName][1] == vector3.y && this._valueCache[uniformName][2] == vector3.z)
  10383. return this;
  10384. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  10385. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  10386. return this;
  10387. };
  10388. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  10389. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] == x && this._valueCache[uniformName][1] == y && this._valueCache[uniformName][2] == z)
  10390. return this;
  10391. this._cacheFloat3(uniformName, x, y, z);
  10392. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  10393. return this;
  10394. };
  10395. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  10396. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] == x && this._valueCache[uniformName][1] == y && this._valueCache[uniformName][2] == z && this._valueCache[uniformName][3] == w)
  10397. return this;
  10398. this._cacheFloat4(uniformName, x, y, z, w);
  10399. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  10400. return this;
  10401. };
  10402. Effect.prototype.setColor3 = function (uniformName, color3) {
  10403. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] == color3.r && this._valueCache[uniformName][1] == color3.g && this._valueCache[uniformName][2] == color3.b)
  10404. return this;
  10405. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  10406. this._engine.setColor3(this.getUniform(uniformName), color3);
  10407. return this;
  10408. };
  10409. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  10410. 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)
  10411. return this;
  10412. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  10413. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  10414. return this;
  10415. };
  10416. 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}",
  10417. 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}",
  10418. 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}",
  10419. colorPixelShader:"precision highp float;\n\nuniform vec4 color;\n\nvoid main(void) {\n gl_FragColor = color;\n}",
  10420. 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}",
  10421. 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}",
  10422. 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 vec3 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 for (int i = 0; i<4; i++){\n if (unpack(texture2D(shadowSampler, uv + poissonDisk[i] / 1500.0)) < depth.z){\n visibility -= 0.2;\n }\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 * vBumpInfos.y;\n map = map * 255. / 127. - 128. / 127.;\n mat3 TBN = cotangent_frame(vNormalW, -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 diffuseColor *= vColor;\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 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}",
  10423. 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 vec3 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// Output\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n\n#ifdef VERTEXCOLOR\nvarying vec3 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 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#ifdef INSTANCES\n finalWorld = mat4(world0, world1, world2, world3);\n#else\n finalWorld = world;\n#endif\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}",
  10424. 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}",
  10425. 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}",
  10426. firePixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nuniform float iGlobalTime;\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 alpha;\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\n vec2 p = vUV * 8.0;\n float q = fbm(p - iGlobalTime * 0.1);\n vec2 r = vec2(fbm(p + q + iGlobalTime * speed.x - p.x - p.y), fbm(p + q - iGlobalTime * speed.y));\n vec3 c = mix(c1, c2, fbm(p + r)) + mix(c3, c4, r.x) - mix(c5, c6, r.y);\n gl_FragColor = vec4(c * cos(shift * vUV.y), alpha);\n\n}",
  10427. 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}",
  10428. 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}",
  10429. 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}",
  10430. 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 vec3 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 diffuseColor *= vColor;\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 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}",
  10431. 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 vec3 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 vec3 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}",
  10432. 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}",
  10433. 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}",
  10434. 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}",
  10435. outlinePixelShader:"precision highp float;\n\nuniform vec3 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 = vec4(color, 1.);\n}",
  10436. 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}",
  10437. 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}",
  10438. 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}",
  10439. 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}",
  10440. 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}",
  10441. 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}",
  10442. 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}",
  10443. 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}",
  10444. 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}",
  10445. 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}",
  10446. 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}",
  10447. woodPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vPosition; \nvarying vec2 vUV; \n\nuniform float ampScale;\nuniform float ringScale;\nuniform vec3 woodColor1;\nuniform vec3 woodColor2;\n\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\n vec2 positionWood = vPosition;\n float r = ringScale * sqrt(dot(positionWood.xy, positionWood.xy));\n r = r + fbm(vPosition);\n r = r - floor(r);\n r = smoothstep(0.0, 0.8, r) - smoothstep(0.8, 1.0, r);\n\n gl_FragColor = vec4(mix(woodColor1, woodColor2, r), 1.0);\n}",
  10448. };
  10449. return Effect;
  10450. })();
  10451. BABYLON.Effect = Effect;
  10452. })(BABYLON || (BABYLON = {}));
  10453. var BABYLON;
  10454. (function (BABYLON) {
  10455. var Material = (function () {
  10456. function Material(name, scene, doNotAdd) {
  10457. this.name = name;
  10458. this.checkReadyOnEveryCall = true;
  10459. this.checkReadyOnlyOnce = false;
  10460. this.state = "";
  10461. this.alpha = 1.0;
  10462. this.wireframe = false;
  10463. this.backFaceCulling = true;
  10464. this._wasPreviouslyReady = false;
  10465. this.id = name;
  10466. this._scene = scene;
  10467. if (!doNotAdd) {
  10468. scene.materials.push(this);
  10469. }
  10470. }
  10471. Material.prototype.isReady = function (mesh, useInstances) {
  10472. return true;
  10473. };
  10474. Material.prototype.getEffect = function () {
  10475. return this._effect;
  10476. };
  10477. Material.prototype.getScene = function () {
  10478. return this._scene;
  10479. };
  10480. Material.prototype.needAlphaBlending = function () {
  10481. return (this.alpha < 1.0);
  10482. };
  10483. Material.prototype.needAlphaTesting = function () {
  10484. return false;
  10485. };
  10486. Material.prototype.getAlphaTestTexture = function () {
  10487. return null;
  10488. };
  10489. Material.prototype.trackCreation = function (onCompiled, onError) {
  10490. };
  10491. Material.prototype._preBind = function () {
  10492. var engine = this._scene.getEngine();
  10493. engine.enableEffect(this._effect);
  10494. engine.setState(this.backFaceCulling);
  10495. };
  10496. Material.prototype.bind = function (world, mesh) {
  10497. };
  10498. Material.prototype.bindOnlyWorldMatrix = function (world) {
  10499. };
  10500. Material.prototype.unbind = function () {
  10501. };
  10502. Material.prototype.dispose = function (forceDisposeEffect) {
  10503. var index = this._scene.materials.indexOf(this);
  10504. this._scene.materials.splice(index, 1);
  10505. if (forceDisposeEffect && this._effect) {
  10506. this._scene.getEngine()._releaseEffect(this._effect);
  10507. this._effect = null;
  10508. }
  10509. if (this.onDispose) {
  10510. this.onDispose();
  10511. }
  10512. };
  10513. return Material;
  10514. })();
  10515. BABYLON.Material = Material;
  10516. })(BABYLON || (BABYLON = {}));
  10517. var __extends = this.__extends || function (d, b) {
  10518. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  10519. function __() { this.constructor = d; }
  10520. __.prototype = b.prototype;
  10521. d.prototype = new __();
  10522. };
  10523. var BABYLON;
  10524. (function (BABYLON) {
  10525. var maxSimultaneousLights = 4;
  10526. var FresnelParameters = (function () {
  10527. function FresnelParameters() {
  10528. this.isEnabled = true;
  10529. this.leftColor = BABYLON.Color3.White();
  10530. this.rightColor = BABYLON.Color3.Black();
  10531. this.bias = 0;
  10532. this.power = 1;
  10533. }
  10534. return FresnelParameters;
  10535. })();
  10536. BABYLON.FresnelParameters = FresnelParameters;
  10537. var StandardMaterial = (function (_super) {
  10538. __extends(StandardMaterial, _super);
  10539. function StandardMaterial(name, scene) {
  10540. var _this = this;
  10541. _super.call(this, name, scene);
  10542. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  10543. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  10544. this.specularColor = new BABYLON.Color3(1, 1, 1);
  10545. this.specularPower = 64;
  10546. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  10547. this.useAlphaFromDiffuseTexture = false;
  10548. this.useSpecularOverAlpha = true;
  10549. this._cachedDefines = null;
  10550. this._renderTargets = new BABYLON.SmartArray(16);
  10551. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  10552. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  10553. this._scaledDiffuse = new BABYLON.Color3();
  10554. this._scaledSpecular = new BABYLON.Color3();
  10555. this.getRenderTargetTextures = function () {
  10556. _this._renderTargets.reset();
  10557. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  10558. _this._renderTargets.push(_this.reflectionTexture);
  10559. }
  10560. return _this._renderTargets;
  10561. };
  10562. }
  10563. StandardMaterial.prototype.needAlphaBlending = function () {
  10564. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  10565. };
  10566. StandardMaterial.prototype.needAlphaTesting = function () {
  10567. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && !this.diffuseTexture.getAlphaFromRGB;
  10568. };
  10569. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  10570. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  10571. };
  10572. StandardMaterial.prototype.getAlphaTestTexture = function () {
  10573. return this.diffuseTexture;
  10574. };
  10575. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  10576. if (this.checkReadyOnlyOnce) {
  10577. if (this._wasPreviouslyReady) {
  10578. return true;
  10579. }
  10580. }
  10581. var scene = this.getScene();
  10582. if (!this.checkReadyOnEveryCall) {
  10583. if (this._renderId === scene.getRenderId()) {
  10584. return true;
  10585. }
  10586. }
  10587. var engine = scene.getEngine();
  10588. var defines = [];
  10589. var fallbacks = new BABYLON.EffectFallbacks();
  10590. if (scene.texturesEnabled) {
  10591. if (this.diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  10592. if (!this.diffuseTexture.isReady()) {
  10593. return false;
  10594. } else {
  10595. defines.push("#define DIFFUSE");
  10596. }
  10597. }
  10598. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  10599. if (!this.ambientTexture.isReady()) {
  10600. return false;
  10601. } else {
  10602. defines.push("#define AMBIENT");
  10603. }
  10604. }
  10605. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  10606. if (!this.opacityTexture.isReady()) {
  10607. return false;
  10608. } else {
  10609. defines.push("#define OPACITY");
  10610. if (this.opacityTexture.getAlphaFromRGB) {
  10611. defines.push("#define OPACITYRGB");
  10612. }
  10613. }
  10614. }
  10615. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  10616. if (!this.reflectionTexture.isReady()) {
  10617. return false;
  10618. } else {
  10619. defines.push("#define REFLECTION");
  10620. fallbacks.addFallback(0, "REFLECTION");
  10621. }
  10622. }
  10623. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  10624. if (!this.emissiveTexture.isReady()) {
  10625. return false;
  10626. } else {
  10627. defines.push("#define EMISSIVE");
  10628. }
  10629. }
  10630. if (this.specularTexture && BABYLON.StandardMaterial.SpecularTextureEnabled) {
  10631. if (!this.specularTexture.isReady()) {
  10632. return false;
  10633. } else {
  10634. defines.push("#define SPECULAR");
  10635. fallbacks.addFallback(0, "SPECULAR");
  10636. }
  10637. }
  10638. }
  10639. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled) {
  10640. if (!this.bumpTexture.isReady()) {
  10641. return false;
  10642. } else {
  10643. defines.push("#define BUMP");
  10644. fallbacks.addFallback(0, "BUMP");
  10645. }
  10646. }
  10647. if (this.useSpecularOverAlpha) {
  10648. defines.push("#define SPECULAROVERALPHA");
  10649. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  10650. }
  10651. if (scene.clipPlane) {
  10652. defines.push("#define CLIPPLANE");
  10653. }
  10654. if (engine.getAlphaTesting()) {
  10655. defines.push("#define ALPHATEST");
  10656. }
  10657. if (this._shouldUseAlphaFromDiffuseTexture()) {
  10658. defines.push("#define ALPHAFROMDIFFUSE");
  10659. }
  10660. if (scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  10661. defines.push("#define FOG");
  10662. fallbacks.addFallback(1, "FOG");
  10663. }
  10664. var shadowsActivated = false;
  10665. var lightIndex = 0;
  10666. if (scene.lightsEnabled) {
  10667. for (var index = 0; index < scene.lights.length; index++) {
  10668. var light = scene.lights[index];
  10669. if (!light.isEnabled()) {
  10670. continue;
  10671. }
  10672. if (light._excludedMeshesIds.length > 0) {
  10673. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  10674. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  10675. if (excludedMesh) {
  10676. light.excludedMeshes.push(excludedMesh);
  10677. }
  10678. }
  10679. light._excludedMeshesIds = [];
  10680. }
  10681. if (light._includedOnlyMeshesIds.length > 0) {
  10682. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  10683. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  10684. if (includedOnlyMesh) {
  10685. light.includedOnlyMeshes.push(includedOnlyMesh);
  10686. }
  10687. }
  10688. light._includedOnlyMeshesIds = [];
  10689. }
  10690. if (!light.canAffectMesh(mesh)) {
  10691. continue;
  10692. }
  10693. defines.push("#define LIGHT" + lightIndex);
  10694. if (lightIndex > 0) {
  10695. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  10696. }
  10697. var type;
  10698. if (light instanceof BABYLON.SpotLight) {
  10699. type = "#define SPOTLIGHT" + lightIndex;
  10700. } else if (light instanceof BABYLON.HemisphericLight) {
  10701. type = "#define HEMILIGHT" + lightIndex;
  10702. } else {
  10703. type = "#define POINTDIRLIGHT" + lightIndex;
  10704. }
  10705. defines.push(type);
  10706. if (lightIndex > 0) {
  10707. fallbacks.addFallback(lightIndex, type.replace("#define ", ""));
  10708. }
  10709. var shadowGenerator = light.getShadowGenerator();
  10710. if (mesh && mesh.receiveShadows && shadowGenerator) {
  10711. defines.push("#define SHADOW" + lightIndex);
  10712. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  10713. if (!shadowsActivated) {
  10714. defines.push("#define SHADOWS");
  10715. shadowsActivated = true;
  10716. }
  10717. if (shadowGenerator.useVarianceShadowMap) {
  10718. defines.push("#define SHADOWVSM" + lightIndex);
  10719. if (lightIndex > 0) {
  10720. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  10721. }
  10722. }
  10723. if (shadowGenerator.usePoissonSampling) {
  10724. defines.push("#define SHADOWPCF" + lightIndex);
  10725. if (lightIndex > 0) {
  10726. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  10727. }
  10728. }
  10729. }
  10730. lightIndex++;
  10731. if (lightIndex == maxSimultaneousLights)
  10732. break;
  10733. }
  10734. }
  10735. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled || this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled || this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  10736. var fresnelRank = 1;
  10737. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  10738. defines.push("#define DIFFUSEFRESNEL");
  10739. fallbacks.addFallback(fresnelRank, "DIFFUSEFRESNEL");
  10740. fresnelRank++;
  10741. }
  10742. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  10743. defines.push("#define OPACITYFRESNEL");
  10744. fallbacks.addFallback(fresnelRank, "OPACITYFRESNEL");
  10745. fresnelRank++;
  10746. }
  10747. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  10748. defines.push("#define REFLECTIONFRESNEL");
  10749. fallbacks.addFallback(fresnelRank, "REFLECTIONFRESNEL");
  10750. fresnelRank++;
  10751. }
  10752. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  10753. defines.push("#define EMISSIVEFRESNEL");
  10754. fallbacks.addFallback(fresnelRank, "EMISSIVEFRESNEL");
  10755. fresnelRank++;
  10756. }
  10757. defines.push("#define FRESNEL");
  10758. fallbacks.addFallback(fresnelRank - 1, "FRESNEL");
  10759. }
  10760. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  10761. if (mesh) {
  10762. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  10763. attribs.push(BABYLON.VertexBuffer.UVKind);
  10764. defines.push("#define UV1");
  10765. }
  10766. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  10767. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  10768. defines.push("#define UV2");
  10769. }
  10770. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  10771. attribs.push(BABYLON.VertexBuffer.ColorKind);
  10772. defines.push("#define VERTEXCOLOR");
  10773. }
  10774. if (mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  10775. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  10776. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  10777. defines.push("#define BONES");
  10778. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  10779. defines.push("#define BONES4");
  10780. fallbacks.addFallback(0, "BONES4");
  10781. }
  10782. if (useInstances) {
  10783. defines.push("#define INSTANCES");
  10784. attribs.push("world0");
  10785. attribs.push("world1");
  10786. attribs.push("world2");
  10787. attribs.push("world3");
  10788. }
  10789. }
  10790. var join = defines.join("\n");
  10791. if (this._cachedDefines != join) {
  10792. this._cachedDefines = join;
  10793. var shaderName = "default";
  10794. if (!scene.getEngine().getCaps().standardDerivatives) {
  10795. shaderName = "legacydefault";
  10796. }
  10797. this._effect = scene.getEngine().createEffect(shaderName, attribs, [
  10798. "world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  10799. "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0",
  10800. "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1",
  10801. "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2",
  10802. "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3",
  10803. "vFogInfos", "vFogColor",
  10804. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos",
  10805. "mBones",
  10806. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix",
  10807. "darkness0", "darkness1", "darkness2", "darkness3",
  10808. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor"
  10809. ], [
  10810. "diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler",
  10811. "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"
  10812. ], join, fallbacks, this.onCompiled, this.onError);
  10813. }
  10814. if (!this._effect.isReady()) {
  10815. return false;
  10816. }
  10817. this._renderId = scene.getRenderId();
  10818. this._wasPreviouslyReady = true;
  10819. return true;
  10820. };
  10821. StandardMaterial.prototype.unbind = function () {
  10822. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  10823. this._effect.setTexture("reflection2DSampler", null);
  10824. }
  10825. };
  10826. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  10827. this._effect.setMatrix("world", world);
  10828. };
  10829. StandardMaterial.prototype.bind = function (world, mesh) {
  10830. var scene = this.getScene();
  10831. this.bindOnlyWorldMatrix(world);
  10832. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  10833. if (mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  10834. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  10835. }
  10836. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  10837. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  10838. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  10839. }
  10840. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  10841. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  10842. }
  10843. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  10844. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  10845. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  10846. }
  10847. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  10848. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  10849. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  10850. }
  10851. if (this.diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  10852. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  10853. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  10854. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  10855. }
  10856. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  10857. this._effect.setTexture("ambientSampler", this.ambientTexture);
  10858. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  10859. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  10860. }
  10861. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  10862. this._effect.setTexture("opacitySampler", this.opacityTexture);
  10863. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  10864. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  10865. }
  10866. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  10867. if (this.reflectionTexture.isCube) {
  10868. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  10869. } else {
  10870. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  10871. }
  10872. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  10873. this._effect.setFloat3("vReflectionInfos", this.reflectionTexture.coordinatesMode, this.reflectionTexture.level, this.reflectionTexture.isCube ? 1 : 0);
  10874. }
  10875. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  10876. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  10877. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  10878. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  10879. }
  10880. if (this.specularTexture && BABYLON.StandardMaterial.SpecularTextureEnabled) {
  10881. this._effect.setTexture("specularSampler", this.specularTexture);
  10882. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  10883. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  10884. }
  10885. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled) {
  10886. this._effect.setTexture("bumpSampler", this.bumpTexture);
  10887. this._effect.setFloat2("vBumpInfos", this.bumpTexture.coordinatesIndex, this.bumpTexture.level);
  10888. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  10889. }
  10890. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  10891. this._effect.setVector3("vEyePosition", scene.activeCamera.position);
  10892. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  10893. this._effect.setColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  10894. this._effect.setColor4("vSpecularColor", this.specularColor, this.specularPower);
  10895. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  10896. if (scene.lightsEnabled) {
  10897. var lightIndex = 0;
  10898. for (var index = 0; index < scene.lights.length; index++) {
  10899. var light = scene.lights[index];
  10900. if (!light.isEnabled()) {
  10901. continue;
  10902. }
  10903. if (!light.canAffectMesh(mesh)) {
  10904. continue;
  10905. }
  10906. if (light instanceof BABYLON.PointLight) {
  10907. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  10908. } else if (light instanceof BABYLON.DirectionalLight) {
  10909. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  10910. } else if (light instanceof BABYLON.SpotLight) {
  10911. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  10912. } else if (light instanceof BABYLON.HemisphericLight) {
  10913. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  10914. }
  10915. light.diffuse.scaleToRef(light.intensity, this._scaledDiffuse);
  10916. light.specular.scaleToRef(light.intensity, this._scaledSpecular);
  10917. this._effect.setColor4("vLightDiffuse" + lightIndex, this._scaledDiffuse, light.range);
  10918. this._effect.setColor3("vLightSpecular" + lightIndex, this._scaledSpecular);
  10919. var shadowGenerator = light.getShadowGenerator();
  10920. if (mesh.receiveShadows && shadowGenerator) {
  10921. this._effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  10922. this._effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMap());
  10923. this._effect.setFloat("darkness" + lightIndex, shadowGenerator.getDarkness());
  10924. }
  10925. lightIndex++;
  10926. if (lightIndex == maxSimultaneousLights)
  10927. break;
  10928. }
  10929. }
  10930. if (scene.clipPlane) {
  10931. var clipPlane = scene.clipPlane;
  10932. this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  10933. }
  10934. if (scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  10935. this._effect.setMatrix("view", scene.getViewMatrix());
  10936. }
  10937. if (scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  10938. this._effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  10939. this._effect.setColor3("vFogColor", scene.fogColor);
  10940. }
  10941. };
  10942. StandardMaterial.prototype.getAnimatables = function () {
  10943. var results = [];
  10944. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  10945. results.push(this.diffuseTexture);
  10946. }
  10947. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  10948. results.push(this.ambientTexture);
  10949. }
  10950. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  10951. results.push(this.opacityTexture);
  10952. }
  10953. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  10954. results.push(this.reflectionTexture);
  10955. }
  10956. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  10957. results.push(this.emissiveTexture);
  10958. }
  10959. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  10960. results.push(this.specularTexture);
  10961. }
  10962. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  10963. results.push(this.bumpTexture);
  10964. }
  10965. return results;
  10966. };
  10967. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  10968. if (this.diffuseTexture) {
  10969. this.diffuseTexture.dispose();
  10970. }
  10971. if (this.ambientTexture) {
  10972. this.ambientTexture.dispose();
  10973. }
  10974. if (this.opacityTexture) {
  10975. this.opacityTexture.dispose();
  10976. }
  10977. if (this.reflectionTexture) {
  10978. this.reflectionTexture.dispose();
  10979. }
  10980. if (this.emissiveTexture) {
  10981. this.emissiveTexture.dispose();
  10982. }
  10983. if (this.specularTexture) {
  10984. this.specularTexture.dispose();
  10985. }
  10986. if (this.bumpTexture) {
  10987. this.bumpTexture.dispose();
  10988. }
  10989. _super.prototype.dispose.call(this, forceDisposeEffect);
  10990. };
  10991. StandardMaterial.prototype.clone = function (name) {
  10992. var newStandardMaterial = new BABYLON.StandardMaterial(name, this.getScene());
  10993. newStandardMaterial.checkReadyOnEveryCall = this.checkReadyOnEveryCall;
  10994. newStandardMaterial.alpha = this.alpha;
  10995. newStandardMaterial.wireframe = this.wireframe;
  10996. newStandardMaterial.backFaceCulling = this.backFaceCulling;
  10997. if (this.diffuseTexture && this.diffuseTexture.clone) {
  10998. newStandardMaterial.diffuseTexture = this.diffuseTexture.clone();
  10999. }
  11000. if (this.ambientTexture && this.ambientTexture.clone) {
  11001. newStandardMaterial.ambientTexture = this.ambientTexture.clone();
  11002. }
  11003. if (this.opacityTexture && this.opacityTexture.clone) {
  11004. newStandardMaterial.opacityTexture = this.opacityTexture.clone();
  11005. }
  11006. if (this.reflectionTexture && this.reflectionTexture.clone) {
  11007. newStandardMaterial.reflectionTexture = this.reflectionTexture.clone();
  11008. }
  11009. if (this.emissiveTexture && this.emissiveTexture.clone) {
  11010. newStandardMaterial.emissiveTexture = this.emissiveTexture.clone();
  11011. }
  11012. if (this.specularTexture && this.specularTexture.clone) {
  11013. newStandardMaterial.specularTexture = this.specularTexture.clone();
  11014. }
  11015. if (this.bumpTexture && this.bumpTexture.clone) {
  11016. newStandardMaterial.bumpTexture = this.bumpTexture.clone();
  11017. }
  11018. newStandardMaterial.ambientColor = this.ambientColor.clone();
  11019. newStandardMaterial.diffuseColor = this.diffuseColor.clone();
  11020. newStandardMaterial.specularColor = this.specularColor.clone();
  11021. newStandardMaterial.specularPower = this.specularPower;
  11022. newStandardMaterial.emissiveColor = this.emissiveColor.clone();
  11023. return newStandardMaterial;
  11024. };
  11025. StandardMaterial.DiffuseTextureEnabled = true;
  11026. StandardMaterial.AmbientTextureEnabled = true;
  11027. StandardMaterial.OpacityTextureEnabled = true;
  11028. StandardMaterial.ReflectionTextureEnabled = true;
  11029. StandardMaterial.EmissiveTextureEnabled = true;
  11030. StandardMaterial.SpecularTextureEnabled = true;
  11031. StandardMaterial.BumpTextureEnabled = true;
  11032. return StandardMaterial;
  11033. })(BABYLON.Material);
  11034. BABYLON.StandardMaterial = StandardMaterial;
  11035. })(BABYLON || (BABYLON = {}));
  11036. var __extends = this.__extends || function (d, b) {
  11037. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  11038. function __() { this.constructor = d; }
  11039. __.prototype = b.prototype;
  11040. d.prototype = new __();
  11041. };
  11042. var BABYLON;
  11043. (function (BABYLON) {
  11044. var MultiMaterial = (function (_super) {
  11045. __extends(MultiMaterial, _super);
  11046. function MultiMaterial(name, scene) {
  11047. _super.call(this, name, scene, true);
  11048. this.subMaterials = new Array();
  11049. scene.multiMaterials.push(this);
  11050. }
  11051. MultiMaterial.prototype.getSubMaterial = function (index) {
  11052. if (index < 0 || index >= this.subMaterials.length) {
  11053. return this.getScene().defaultMaterial;
  11054. }
  11055. return this.subMaterials[index];
  11056. };
  11057. MultiMaterial.prototype.isReady = function (mesh) {
  11058. for (var index = 0; index < this.subMaterials.length; index++) {
  11059. var subMaterial = this.subMaterials[index];
  11060. if (subMaterial) {
  11061. if (!this.subMaterials[index].isReady(mesh)) {
  11062. return false;
  11063. }
  11064. }
  11065. }
  11066. return true;
  11067. };
  11068. return MultiMaterial;
  11069. })(BABYLON.Material);
  11070. BABYLON.MultiMaterial = MultiMaterial;
  11071. })(BABYLON || (BABYLON = {}));
  11072. var BABYLON;
  11073. (function (BABYLON) {
  11074. var Database = (function () {
  11075. function Database(urlToScene, callbackManifestChecked) {
  11076. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  11077. this.callbackManifestChecked = callbackManifestChecked;
  11078. this.currentSceneUrl = BABYLON.Database.ReturnFullUrlLocation(urlToScene);
  11079. this.db = null;
  11080. this.enableSceneOffline = false;
  11081. this.enableTexturesOffline = false;
  11082. this.manifestVersionFound = 0;
  11083. this.mustUpdateRessources = false;
  11084. this.hasReachedQuota = false;
  11085. this.checkManifestFile();
  11086. }
  11087. Database.prototype.checkManifestFile = function () {
  11088. var _this = this;
  11089. function noManifestFile() {
  11090. BABYLON.Tools.Log("Valid manifest file not found. Scene & textures will be loaded directly from the web server.");
  11091. that.enableSceneOffline = false;
  11092. that.enableTexturesOffline = false;
  11093. that.callbackManifestChecked(false);
  11094. }
  11095. var that = this;
  11096. var manifestURL = this.currentSceneUrl + ".manifest";
  11097. var xhr = new XMLHttpRequest();
  11098. var manifestURLTimeStamped = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  11099. xhr.open("GET", manifestURLTimeStamped, true);
  11100. xhr.addEventListener("load", function () {
  11101. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  11102. try {
  11103. var manifestFile = JSON.parse(xhr.response);
  11104. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  11105. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  11106. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  11107. _this.manifestVersionFound = manifestFile.version;
  11108. }
  11109. if (_this.callbackManifestChecked) {
  11110. _this.callbackManifestChecked(true);
  11111. }
  11112. } catch (ex) {
  11113. noManifestFile();
  11114. }
  11115. } else {
  11116. noManifestFile();
  11117. }
  11118. }, false);
  11119. xhr.addEventListener("error", function (event) {
  11120. noManifestFile();
  11121. }, false);
  11122. try {
  11123. xhr.send();
  11124. } catch (ex) {
  11125. BABYLON.Tools.Error("Error on XHR send request.");
  11126. that.callbackManifestChecked(false);
  11127. }
  11128. };
  11129. Database.prototype.openAsync = function (successCallback, errorCallback) {
  11130. var _this = this;
  11131. function handleError() {
  11132. that.isSupported = false;
  11133. if (errorCallback)
  11134. errorCallback();
  11135. }
  11136. var that = this;
  11137. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  11138. this.isSupported = false;
  11139. if (errorCallback)
  11140. errorCallback();
  11141. } else {
  11142. if (!this.db) {
  11143. this.hasReachedQuota = false;
  11144. this.isSupported = true;
  11145. var request = this.idbFactory.open("babylonjs", 1);
  11146. request.onerror = function (event) {
  11147. handleError();
  11148. };
  11149. request.onblocked = function (event) {
  11150. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  11151. handleError();
  11152. };
  11153. request.onsuccess = function (event) {
  11154. _this.db = request.result;
  11155. successCallback();
  11156. };
  11157. request.onupgradeneeded = function (event) {
  11158. _this.db = (event.target).result;
  11159. try {
  11160. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  11161. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  11162. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  11163. } catch (ex) {
  11164. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  11165. handleError();
  11166. }
  11167. };
  11168. } else {
  11169. if (successCallback)
  11170. successCallback();
  11171. }
  11172. }
  11173. };
  11174. Database.prototype.loadImageFromDB = function (url, image) {
  11175. var _this = this;
  11176. var completeURL = BABYLON.Database.ReturnFullUrlLocation(url);
  11177. var saveAndLoadImage = function () {
  11178. if (!_this.hasReachedQuota && _this.db !== null) {
  11179. _this._saveImageIntoDBAsync(completeURL, image);
  11180. } else {
  11181. image.src = url;
  11182. }
  11183. };
  11184. if (!this.mustUpdateRessources) {
  11185. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  11186. } else {
  11187. saveAndLoadImage();
  11188. }
  11189. };
  11190. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  11191. if (this.isSupported && this.db !== null) {
  11192. var texture;
  11193. var transaction = this.db.transaction(["textures"]);
  11194. transaction.onabort = function (event) {
  11195. image.src = url;
  11196. };
  11197. transaction.oncomplete = function (event) {
  11198. var blobTextureURL;
  11199. if (texture) {
  11200. var URL = window.URL || window.webkitURL;
  11201. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  11202. image.onerror = function () {
  11203. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  11204. image.src = url;
  11205. };
  11206. image.src = blobTextureURL;
  11207. } else {
  11208. notInDBCallback();
  11209. }
  11210. };
  11211. var getRequest = transaction.objectStore("textures").get(url);
  11212. getRequest.onsuccess = function (event) {
  11213. texture = (event.target).result;
  11214. };
  11215. getRequest.onerror = function (event) {
  11216. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  11217. image.src = url;
  11218. };
  11219. } else {
  11220. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  11221. image.src = url;
  11222. }
  11223. };
  11224. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  11225. var _this = this;
  11226. if (this.isSupported) {
  11227. var generateBlobUrl = function () {
  11228. var blobTextureURL;
  11229. if (blob) {
  11230. var URL = window.URL || window.webkitURL;
  11231. try {
  11232. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  11233. } catch (ex) {
  11234. blobTextureURL = URL.createObjectURL(blob);
  11235. }
  11236. }
  11237. image.src = blobTextureURL;
  11238. };
  11239. if (BABYLON.Database.isUASupportingBlobStorage) {
  11240. var xhr = new XMLHttpRequest(), blob;
  11241. xhr.open("GET", url, true);
  11242. xhr.responseType = "blob";
  11243. xhr.addEventListener("load", function () {
  11244. if (xhr.status === 200) {
  11245. blob = xhr.response;
  11246. var transaction = _this.db.transaction(["textures"], "readwrite");
  11247. transaction.onabort = function (event) {
  11248. try {
  11249. if (event.srcElement.error.name === "QuotaExceededError") {
  11250. this.hasReachedQuota = true;
  11251. }
  11252. } catch (ex) {
  11253. }
  11254. generateBlobUrl();
  11255. };
  11256. transaction.oncomplete = function (event) {
  11257. generateBlobUrl();
  11258. };
  11259. var newTexture = { textureUrl: url, data: blob };
  11260. try {
  11261. var addRequest = transaction.objectStore("textures").put(newTexture);
  11262. addRequest.onsuccess = function (event) {
  11263. };
  11264. addRequest.onerror = function (event) {
  11265. generateBlobUrl();
  11266. };
  11267. } catch (ex) {
  11268. if (ex.code === 25) {
  11269. BABYLON.Database.isUASupportingBlobStorage = false;
  11270. }
  11271. image.src = url;
  11272. }
  11273. } else {
  11274. image.src = url;
  11275. }
  11276. }, false);
  11277. xhr.addEventListener("error", function (event) {
  11278. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  11279. image.src = url;
  11280. }, false);
  11281. xhr.send();
  11282. } else {
  11283. image.src = url;
  11284. }
  11285. } else {
  11286. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  11287. image.src = url;
  11288. }
  11289. };
  11290. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  11291. var _this = this;
  11292. var updateVersion = function (event) {
  11293. _this._saveVersionIntoDBAsync(url, versionLoaded);
  11294. };
  11295. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  11296. };
  11297. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  11298. var _this = this;
  11299. if (this.isSupported) {
  11300. var version;
  11301. try {
  11302. var transaction = this.db.transaction(["versions"]);
  11303. transaction.oncomplete = function (event) {
  11304. if (version) {
  11305. if (_this.manifestVersionFound > version.data) {
  11306. _this.mustUpdateRessources = true;
  11307. updateInDBCallback();
  11308. } else {
  11309. callback(version.data);
  11310. }
  11311. } else {
  11312. _this.mustUpdateRessources = true;
  11313. updateInDBCallback();
  11314. }
  11315. };
  11316. transaction.onabort = function (event) {
  11317. callback(-1);
  11318. };
  11319. var getRequest = transaction.objectStore("versions").get(url);
  11320. getRequest.onsuccess = function (event) {
  11321. version = (event.target).result;
  11322. };
  11323. getRequest.onerror = function (event) {
  11324. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  11325. callback(-1);
  11326. };
  11327. } catch (ex) {
  11328. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  11329. callback(-1);
  11330. }
  11331. } else {
  11332. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  11333. callback(-1);
  11334. }
  11335. };
  11336. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  11337. var _this = this;
  11338. if (this.isSupported && !this.hasReachedQuota) {
  11339. try {
  11340. var transaction = this.db.transaction(["versions"], "readwrite");
  11341. transaction.onabort = function (event) {
  11342. try {
  11343. if (event.srcElement.error.name === "QuotaExceededError") {
  11344. _this.hasReachedQuota = true;
  11345. }
  11346. } catch (ex) {
  11347. }
  11348. callback(-1);
  11349. };
  11350. transaction.oncomplete = function (event) {
  11351. callback(_this.manifestVersionFound);
  11352. };
  11353. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  11354. var addRequest = transaction.objectStore("versions").put(newVersion);
  11355. addRequest.onsuccess = function (event) {
  11356. };
  11357. addRequest.onerror = function (event) {
  11358. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  11359. };
  11360. } catch (ex) {
  11361. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  11362. callback(-1);
  11363. }
  11364. } else {
  11365. callback(-1);
  11366. }
  11367. };
  11368. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  11369. var _this = this;
  11370. var completeUrl = BABYLON.Database.ReturnFullUrlLocation(url);
  11371. var saveAndLoadFile = function (event) {
  11372. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  11373. };
  11374. this._checkVersionFromDB(completeUrl, function (version) {
  11375. if (version !== -1) {
  11376. if (!_this.mustUpdateRessources) {
  11377. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  11378. } else {
  11379. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  11380. }
  11381. } else {
  11382. errorCallback();
  11383. }
  11384. });
  11385. };
  11386. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  11387. if (this.isSupported) {
  11388. var targetStore;
  11389. if (url.indexOf(".babylon") !== -1) {
  11390. targetStore = "scenes";
  11391. } else {
  11392. targetStore = "textures";
  11393. }
  11394. var file;
  11395. var transaction = this.db.transaction([targetStore]);
  11396. transaction.oncomplete = function (event) {
  11397. if (file) {
  11398. callback(file.data);
  11399. } else {
  11400. notInDBCallback();
  11401. }
  11402. };
  11403. transaction.onabort = function (event) {
  11404. notInDBCallback();
  11405. };
  11406. var getRequest = transaction.objectStore(targetStore).get(url);
  11407. getRequest.onsuccess = function (event) {
  11408. file = (event.target).result;
  11409. };
  11410. getRequest.onerror = function (event) {
  11411. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  11412. notInDBCallback();
  11413. };
  11414. } else {
  11415. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  11416. callback();
  11417. }
  11418. };
  11419. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  11420. var _this = this;
  11421. if (this.isSupported) {
  11422. var targetStore;
  11423. if (url.indexOf(".babylon") !== -1) {
  11424. targetStore = "scenes";
  11425. } else {
  11426. targetStore = "textures";
  11427. }
  11428. var xhr = new XMLHttpRequest(), fileData;
  11429. xhr.open("GET", url, true);
  11430. if (useArrayBuffer) {
  11431. xhr.responseType = "arraybuffer";
  11432. }
  11433. xhr.onprogress = progressCallback;
  11434. xhr.addEventListener("load", function () {
  11435. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  11436. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  11437. if (!_this.hasReachedQuota) {
  11438. var transaction = _this.db.transaction([targetStore], "readwrite");
  11439. transaction.onabort = function (event) {
  11440. try {
  11441. if (event.srcElement.error.name === "QuotaExceededError") {
  11442. this.hasReachedQuota = true;
  11443. }
  11444. } catch (ex) {
  11445. }
  11446. callback(fileData);
  11447. };
  11448. transaction.oncomplete = function (event) {
  11449. callback(fileData);
  11450. };
  11451. var newFile;
  11452. if (targetStore === "scenes") {
  11453. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  11454. } else {
  11455. newFile = { textureUrl: url, data: fileData };
  11456. }
  11457. try {
  11458. var addRequest = transaction.objectStore(targetStore).put(newFile);
  11459. addRequest.onsuccess = function (event) {
  11460. };
  11461. addRequest.onerror = function (event) {
  11462. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  11463. };
  11464. } catch (ex) {
  11465. callback(fileData);
  11466. }
  11467. } else {
  11468. callback(fileData);
  11469. }
  11470. } else {
  11471. callback();
  11472. }
  11473. }, false);
  11474. xhr.addEventListener("error", function (event) {
  11475. BABYLON.Tools.Error("error on XHR request.");
  11476. callback();
  11477. }, false);
  11478. xhr.send();
  11479. } else {
  11480. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  11481. callback();
  11482. }
  11483. };
  11484. Database.isUASupportingBlobStorage = true;
  11485. Database.parseURL = function (url) {
  11486. var a = document.createElement('a');
  11487. a.href = url;
  11488. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  11489. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  11490. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  11491. return absLocation;
  11492. };
  11493. Database.ReturnFullUrlLocation = function (url) {
  11494. if (url.indexOf("http:/") === -1) {
  11495. return (BABYLON.Database.parseURL(window.location.href) + url);
  11496. } else {
  11497. return url;
  11498. }
  11499. };
  11500. return Database;
  11501. })();
  11502. BABYLON.Database = Database;
  11503. })(BABYLON || (BABYLON = {}));
  11504. var BABYLON;
  11505. (function (BABYLON) {
  11506. var SpriteManager = (function () {
  11507. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon) {
  11508. this.name = name;
  11509. this.cellSize = cellSize;
  11510. this.sprites = new Array();
  11511. this.renderingGroupId = 0;
  11512. this._vertexDeclaration = [3, 4, 4, 4];
  11513. this._vertexStrideSize = 15 * 4;
  11514. this._capacity = capacity;
  11515. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false);
  11516. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  11517. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  11518. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  11519. this._scene = scene;
  11520. this._scene.spriteManagers.push(this);
  11521. this._vertexDeclaration = [3, 4, 4, 4];
  11522. this._vertexStrideSize = 15 * 4;
  11523. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  11524. var indices = [];
  11525. var index = 0;
  11526. for (var count = 0; count < capacity; count++) {
  11527. indices.push(index);
  11528. indices.push(index + 1);
  11529. indices.push(index + 2);
  11530. indices.push(index);
  11531. indices.push(index + 2);
  11532. indices.push(index + 3);
  11533. index += 4;
  11534. }
  11535. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  11536. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  11537. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  11538. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  11539. }
  11540. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  11541. var arrayOffset = index * 15;
  11542. if (offsetX == 0)
  11543. offsetX = this._epsilon;
  11544. else if (offsetX == 1)
  11545. offsetX = 1 - this._epsilon;
  11546. if (offsetY == 0)
  11547. offsetY = this._epsilon;
  11548. else if (offsetY == 1)
  11549. offsetY = 1 - this._epsilon;
  11550. this._vertices[arrayOffset] = sprite.position.x;
  11551. this._vertices[arrayOffset + 1] = sprite.position.y;
  11552. this._vertices[arrayOffset + 2] = sprite.position.z;
  11553. this._vertices[arrayOffset + 3] = sprite.angle;
  11554. this._vertices[arrayOffset + 4] = sprite.size;
  11555. this._vertices[arrayOffset + 5] = offsetX;
  11556. this._vertices[arrayOffset + 6] = offsetY;
  11557. this._vertices[arrayOffset + 7] = sprite.invertU ? 1 : 0;
  11558. this._vertices[arrayOffset + 8] = sprite.invertV ? 1 : 0;
  11559. var offset = (sprite.cellIndex / rowSize) >> 0;
  11560. this._vertices[arrayOffset + 9] = sprite.cellIndex - offset * rowSize;
  11561. this._vertices[arrayOffset + 10] = offset;
  11562. this._vertices[arrayOffset + 11] = sprite.color.r;
  11563. this._vertices[arrayOffset + 12] = sprite.color.g;
  11564. this._vertices[arrayOffset + 13] = sprite.color.b;
  11565. this._vertices[arrayOffset + 14] = sprite.color.a;
  11566. };
  11567. SpriteManager.prototype.render = function () {
  11568. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  11569. return;
  11570. var engine = this._scene.getEngine();
  11571. var baseSize = this._spriteTexture.getBaseSize();
  11572. var deltaTime = BABYLON.Tools.GetDeltaTime();
  11573. var max = Math.min(this._capacity, this.sprites.length);
  11574. var rowSize = baseSize.width / this.cellSize;
  11575. var offset = 0;
  11576. for (var index = 0; index < max; index++) {
  11577. var sprite = this.sprites[index];
  11578. if (!sprite) {
  11579. continue;
  11580. }
  11581. sprite._animate(deltaTime);
  11582. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  11583. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  11584. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  11585. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  11586. }
  11587. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices, max * this._vertexStrideSize);
  11588. var effect = this._effectBase;
  11589. if (this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  11590. effect = this._effectFog;
  11591. }
  11592. engine.enableEffect(effect);
  11593. var viewMatrix = this._scene.getViewMatrix();
  11594. effect.setTexture("diffuseSampler", this._spriteTexture);
  11595. effect.setMatrix("view", viewMatrix);
  11596. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  11597. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  11598. if (this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  11599. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  11600. effect.setColor3("vFogColor", this._scene.fogColor);
  11601. }
  11602. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  11603. effect.setBool("alphaTest", true);
  11604. engine.setColorWrite(false);
  11605. engine.draw(true, 0, max * 6);
  11606. engine.setColorWrite(true);
  11607. effect.setBool("alphaTest", false);
  11608. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  11609. engine.draw(true, 0, max * 6);
  11610. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  11611. };
  11612. SpriteManager.prototype.dispose = function () {
  11613. if (this._vertexBuffer) {
  11614. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  11615. this._vertexBuffer = null;
  11616. }
  11617. if (this._indexBuffer) {
  11618. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  11619. this._indexBuffer = null;
  11620. }
  11621. if (this._spriteTexture) {
  11622. this._spriteTexture.dispose();
  11623. this._spriteTexture = null;
  11624. }
  11625. var index = this._scene.spriteManagers.indexOf(this);
  11626. this._scene.spriteManagers.splice(index, 1);
  11627. if (this.onDispose) {
  11628. this.onDispose();
  11629. }
  11630. };
  11631. return SpriteManager;
  11632. })();
  11633. BABYLON.SpriteManager = SpriteManager;
  11634. })(BABYLON || (BABYLON = {}));
  11635. var BABYLON;
  11636. (function (BABYLON) {
  11637. var Sprite = (function () {
  11638. function Sprite(name, manager) {
  11639. this.name = name;
  11640. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  11641. this.size = 1.0;
  11642. this.angle = 0;
  11643. this.cellIndex = 0;
  11644. this.invertU = 0;
  11645. this.invertV = 0;
  11646. this.animations = new Array();
  11647. this._animationStarted = false;
  11648. this._loopAnimation = false;
  11649. this._fromIndex = 0;
  11650. this._toIndex = 0;
  11651. this._delay = 0;
  11652. this._direction = 1;
  11653. this._frameCount = 0;
  11654. this._time = 0;
  11655. this._manager = manager;
  11656. this._manager.sprites.push(this);
  11657. this.position = BABYLON.Vector3.Zero();
  11658. }
  11659. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  11660. this._fromIndex = from;
  11661. this._toIndex = to;
  11662. this._loopAnimation = loop;
  11663. this._delay = delay;
  11664. this._animationStarted = true;
  11665. this._direction = from < to ? 1 : -1;
  11666. this.cellIndex = from;
  11667. this._time = 0;
  11668. };
  11669. Sprite.prototype.stopAnimation = function () {
  11670. this._animationStarted = false;
  11671. };
  11672. Sprite.prototype._animate = function (deltaTime) {
  11673. if (!this._animationStarted)
  11674. return;
  11675. this._time += deltaTime;
  11676. if (this._time > this._delay) {
  11677. this._time = this._time % this._delay;
  11678. this.cellIndex += this._direction;
  11679. if (this.cellIndex == this._toIndex) {
  11680. if (this._loopAnimation) {
  11681. this.cellIndex = this._fromIndex;
  11682. } else {
  11683. this._animationStarted = false;
  11684. if (this.disposeWhenFinishedAnimating) {
  11685. this.dispose();
  11686. }
  11687. }
  11688. }
  11689. }
  11690. };
  11691. Sprite.prototype.dispose = function () {
  11692. for (var i = 0; i < this._manager.sprites.length; i++) {
  11693. if (this._manager.sprites[i] == this) {
  11694. this._manager.sprites.splice(i, 1);
  11695. }
  11696. }
  11697. };
  11698. return Sprite;
  11699. })();
  11700. BABYLON.Sprite = Sprite;
  11701. })(BABYLON || (BABYLON = {}));
  11702. var BABYLON;
  11703. (function (BABYLON) {
  11704. var Layer = (function () {
  11705. function Layer(name, imgUrl, scene, isBackground, color) {
  11706. this.name = name;
  11707. this._vertexDeclaration = [2];
  11708. this._vertexStrideSize = 2 * 4;
  11709. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  11710. this.isBackground = isBackground === undefined ? true : isBackground;
  11711. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  11712. this._scene = scene;
  11713. this._scene.layers.push(this);
  11714. var vertices = [];
  11715. vertices.push(1, 1);
  11716. vertices.push(-1, 1);
  11717. vertices.push(-1, -1);
  11718. vertices.push(1, -1);
  11719. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  11720. var indices = [];
  11721. indices.push(0);
  11722. indices.push(1);
  11723. indices.push(2);
  11724. indices.push(0);
  11725. indices.push(2);
  11726. indices.push(3);
  11727. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  11728. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color"], ["textureSampler"], "");
  11729. }
  11730. Layer.prototype.render = function () {
  11731. if (!this._effect.isReady() || !this.texture || !this.texture.isReady())
  11732. return;
  11733. var engine = this._scene.getEngine();
  11734. engine.enableEffect(this._effect);
  11735. engine.setState(false);
  11736. this._effect.setTexture("textureSampler", this.texture);
  11737. this._effect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  11738. this._effect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  11739. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  11740. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  11741. engine.draw(true, 0, 6);
  11742. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  11743. };
  11744. Layer.prototype.dispose = function () {
  11745. if (this._vertexBuffer) {
  11746. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  11747. this._vertexBuffer = null;
  11748. }
  11749. if (this._indexBuffer) {
  11750. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  11751. this._indexBuffer = null;
  11752. }
  11753. if (this.texture) {
  11754. this.texture.dispose();
  11755. this.texture = null;
  11756. }
  11757. var index = this._scene.layers.indexOf(this);
  11758. this._scene.layers.splice(index, 1);
  11759. if (this.onDispose) {
  11760. this.onDispose();
  11761. }
  11762. };
  11763. return Layer;
  11764. })();
  11765. BABYLON.Layer = Layer;
  11766. })(BABYLON || (BABYLON = {}));
  11767. var BABYLON;
  11768. (function (BABYLON) {
  11769. var Particle = (function () {
  11770. function Particle() {
  11771. this.position = BABYLON.Vector3.Zero();
  11772. this.direction = BABYLON.Vector3.Zero();
  11773. this.color = new BABYLON.Color4(0, 0, 0, 0);
  11774. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  11775. this.lifeTime = 1.0;
  11776. this.age = 0;
  11777. this.size = 0;
  11778. this.angle = 0;
  11779. this.angularSpeed = 0;
  11780. }
  11781. return Particle;
  11782. })();
  11783. BABYLON.Particle = Particle;
  11784. })(BABYLON || (BABYLON = {}));
  11785. var BABYLON;
  11786. (function (BABYLON) {
  11787. var randomNumber = function (min, max) {
  11788. if (min == max) {
  11789. return (min);
  11790. }
  11791. var random = Math.random();
  11792. return ((random * (max - min)) + min);
  11793. };
  11794. var ParticleSystem = (function () {
  11795. function ParticleSystem(name, capacity, scene, customEffect) {
  11796. var _this = this;
  11797. this.name = name;
  11798. this.renderingGroupId = 0;
  11799. this.emitter = null;
  11800. this.emitRate = 10;
  11801. this.manualEmitCount = -1;
  11802. this.updateSpeed = 0.01;
  11803. this.targetStopDuration = 0;
  11804. this.disposeOnStop = false;
  11805. this.minEmitPower = 1;
  11806. this.maxEmitPower = 1;
  11807. this.minLifeTime = 1;
  11808. this.maxLifeTime = 1;
  11809. this.minSize = 1;
  11810. this.maxSize = 1;
  11811. this.minAngularSpeed = 0;
  11812. this.maxAngularSpeed = 0;
  11813. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  11814. this.forceDepthWrite = false;
  11815. this.gravity = BABYLON.Vector3.Zero();
  11816. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  11817. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  11818. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  11819. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  11820. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  11821. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  11822. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  11823. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  11824. this.particles = new Array();
  11825. this._vertexDeclaration = [3, 4, 4];
  11826. this._vertexStrideSize = 11 * 4;
  11827. this._stockParticles = new Array();
  11828. this._newPartsExcess = 0;
  11829. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  11830. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  11831. this._scaledDirection = BABYLON.Vector3.Zero();
  11832. this._scaledGravity = BABYLON.Vector3.Zero();
  11833. this._currentRenderId = -1;
  11834. this._started = false;
  11835. this._stopped = false;
  11836. this._actualFrame = 0;
  11837. this.id = name;
  11838. this._capacity = capacity;
  11839. this._scene = scene;
  11840. this._customEffect = customEffect;
  11841. scene.particleSystems.push(this);
  11842. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  11843. var indices = [];
  11844. var index = 0;
  11845. for (var count = 0; count < capacity; count++) {
  11846. indices.push(index);
  11847. indices.push(index + 1);
  11848. indices.push(index + 2);
  11849. indices.push(index);
  11850. indices.push(index + 2);
  11851. indices.push(index + 3);
  11852. index += 4;
  11853. }
  11854. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  11855. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  11856. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate) {
  11857. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  11858. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  11859. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  11860. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  11861. };
  11862. this.startPositionFunction = function (worldMatrix, positionToUpdate) {
  11863. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  11864. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  11865. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  11866. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  11867. };
  11868. }
  11869. ParticleSystem.prototype.getCapacity = function () {
  11870. return this._capacity;
  11871. };
  11872. ParticleSystem.prototype.isAlive = function () {
  11873. return this._alive;
  11874. };
  11875. ParticleSystem.prototype.isStarted = function () {
  11876. return this._started;
  11877. };
  11878. ParticleSystem.prototype.start = function () {
  11879. this._started = true;
  11880. this._stopped = false;
  11881. this._actualFrame = 0;
  11882. };
  11883. ParticleSystem.prototype.stop = function () {
  11884. this._stopped = true;
  11885. };
  11886. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  11887. var offset = index * 11;
  11888. this._vertices[offset] = particle.position.x;
  11889. this._vertices[offset + 1] = particle.position.y;
  11890. this._vertices[offset + 2] = particle.position.z;
  11891. this._vertices[offset + 3] = particle.color.r;
  11892. this._vertices[offset + 4] = particle.color.g;
  11893. this._vertices[offset + 5] = particle.color.b;
  11894. this._vertices[offset + 6] = particle.color.a;
  11895. this._vertices[offset + 7] = particle.angle;
  11896. this._vertices[offset + 8] = particle.size;
  11897. this._vertices[offset + 9] = offsetX;
  11898. this._vertices[offset + 10] = offsetY;
  11899. };
  11900. ParticleSystem.prototype._update = function (newParticles) {
  11901. this._alive = this.particles.length > 0;
  11902. for (var index = 0; index < this.particles.length; index++) {
  11903. var particle = this.particles[index];
  11904. particle.age += this._scaledUpdateSpeed;
  11905. if (particle.age >= particle.lifeTime) {
  11906. this._stockParticles.push(this.particles.splice(index, 1)[0]);
  11907. index--;
  11908. continue;
  11909. } else {
  11910. particle.colorStep.scaleToRef(this._scaledUpdateSpeed, this._scaledColorStep);
  11911. particle.color.addInPlace(this._scaledColorStep);
  11912. if (particle.color.a < 0)
  11913. particle.color.a = 0;
  11914. particle.angle += particle.angularSpeed * this._scaledUpdateSpeed;
  11915. particle.direction.scaleToRef(this._scaledUpdateSpeed, this._scaledDirection);
  11916. particle.position.addInPlace(this._scaledDirection);
  11917. this.gravity.scaleToRef(this._scaledUpdateSpeed, this._scaledGravity);
  11918. particle.direction.addInPlace(this._scaledGravity);
  11919. }
  11920. }
  11921. var worldMatrix;
  11922. if (this.emitter.position) {
  11923. worldMatrix = this.emitter.getWorldMatrix();
  11924. } else {
  11925. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  11926. }
  11927. for (index = 0; index < newParticles; index++) {
  11928. if (this.particles.length == this._capacity) {
  11929. break;
  11930. }
  11931. if (this._stockParticles.length !== 0) {
  11932. particle = this._stockParticles.pop();
  11933. particle.age = 0;
  11934. } else {
  11935. particle = new BABYLON.Particle();
  11936. }
  11937. this.particles.push(particle);
  11938. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  11939. this.startDirectionFunction(emitPower, worldMatrix, particle.direction);
  11940. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  11941. particle.size = randomNumber(this.minSize, this.maxSize);
  11942. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  11943. this.startPositionFunction(worldMatrix, particle.position);
  11944. var step = randomNumber(0, 1.0);
  11945. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  11946. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  11947. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  11948. }
  11949. };
  11950. ParticleSystem.prototype._getEffect = function () {
  11951. if (this._customEffect) {
  11952. return this._customEffect;
  11953. }
  11954. ;
  11955. var defines = [];
  11956. if (this._scene.clipPlane) {
  11957. defines.push("#define CLIPPLANE");
  11958. }
  11959. var join = defines.join("\n");
  11960. if (this._cachedDefines != join) {
  11961. this._cachedDefines = join;
  11962. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  11963. }
  11964. return this._effect;
  11965. };
  11966. ParticleSystem.prototype.animate = function () {
  11967. if (!this._started)
  11968. return;
  11969. var effect = this._getEffect();
  11970. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  11971. return;
  11972. if (this._currentRenderId === this._scene.getRenderId()) {
  11973. return;
  11974. }
  11975. this._currentRenderId = this._scene.getRenderId();
  11976. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  11977. var emitCout;
  11978. if (this.manualEmitCount > -1) {
  11979. emitCout = this.manualEmitCount;
  11980. this.manualEmitCount = 0;
  11981. } else {
  11982. emitCout = this.emitRate;
  11983. }
  11984. var newParticles = ((emitCout * this._scaledUpdateSpeed) >> 0);
  11985. this._newPartsExcess += emitCout * this._scaledUpdateSpeed - newParticles;
  11986. if (this._newPartsExcess > 1.0) {
  11987. newParticles += this._newPartsExcess >> 0;
  11988. this._newPartsExcess -= this._newPartsExcess >> 0;
  11989. }
  11990. this._alive = false;
  11991. if (!this._stopped) {
  11992. this._actualFrame += this._scaledUpdateSpeed;
  11993. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  11994. this.stop();
  11995. } else {
  11996. newParticles = 0;
  11997. }
  11998. this._update(newParticles);
  11999. if (this._stopped) {
  12000. if (!this._alive) {
  12001. this._started = false;
  12002. if (this.disposeOnStop) {
  12003. this._scene._toBeDisposed.push(this);
  12004. }
  12005. }
  12006. }
  12007. var offset = 0;
  12008. for (var index = 0; index < this.particles.length; index++) {
  12009. var particle = this.particles[index];
  12010. this._appendParticleVertex(offset++, particle, 0, 0);
  12011. this._appendParticleVertex(offset++, particle, 1, 0);
  12012. this._appendParticleVertex(offset++, particle, 1, 1);
  12013. this._appendParticleVertex(offset++, particle, 0, 1);
  12014. }
  12015. var engine = this._scene.getEngine();
  12016. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices, this.particles.length * this._vertexStrideSize);
  12017. };
  12018. ParticleSystem.prototype.render = function () {
  12019. var effect = this._getEffect();
  12020. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  12021. return 0;
  12022. var engine = this._scene.getEngine();
  12023. engine.enableEffect(effect);
  12024. var viewMatrix = this._scene.getViewMatrix();
  12025. effect.setTexture("diffuseSampler", this.particleTexture);
  12026. effect.setMatrix("view", viewMatrix);
  12027. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  12028. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  12029. if (this._scene.clipPlane) {
  12030. var clipPlane = this._scene.clipPlane;
  12031. var invView = viewMatrix.clone();
  12032. invView.invert();
  12033. effect.setMatrix("invView", invView);
  12034. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  12035. }
  12036. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  12037. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_ONEONE) {
  12038. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  12039. } else {
  12040. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  12041. }
  12042. if (this.forceDepthWrite) {
  12043. engine.setDepthWrite(true);
  12044. }
  12045. engine.draw(true, 0, this.particles.length * 6);
  12046. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  12047. return this.particles.length;
  12048. };
  12049. ParticleSystem.prototype.dispose = function () {
  12050. if (this._vertexBuffer) {
  12051. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  12052. this._vertexBuffer = null;
  12053. }
  12054. if (this._indexBuffer) {
  12055. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  12056. this._indexBuffer = null;
  12057. }
  12058. if (this.particleTexture) {
  12059. this.particleTexture.dispose();
  12060. this.particleTexture = null;
  12061. }
  12062. var index = this._scene.particleSystems.indexOf(this);
  12063. this._scene.particleSystems.splice(index, 1);
  12064. if (this.onDispose) {
  12065. this.onDispose();
  12066. }
  12067. };
  12068. ParticleSystem.prototype.clone = function (name, newEmitter) {
  12069. var result = new BABYLON.ParticleSystem(name, this._capacity, this._scene);
  12070. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  12071. if (newEmitter === undefined) {
  12072. newEmitter = this.emitter;
  12073. }
  12074. result.emitter = newEmitter;
  12075. if (this.particleTexture) {
  12076. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  12077. }
  12078. result.start();
  12079. return result;
  12080. };
  12081. ParticleSystem.BLENDMODE_ONEONE = 0;
  12082. ParticleSystem.BLENDMODE_STANDARD = 1;
  12083. return ParticleSystem;
  12084. })();
  12085. BABYLON.ParticleSystem = ParticleSystem;
  12086. })(BABYLON || (BABYLON = {}));
  12087. var BABYLON;
  12088. (function (BABYLON) {
  12089. var Animation = (function () {
  12090. function Animation(name, targetProperty, framePerSecond, dataType, loopMode) {
  12091. this.name = name;
  12092. this.targetProperty = targetProperty;
  12093. this.framePerSecond = framePerSecond;
  12094. this.dataType = dataType;
  12095. this.loopMode = loopMode;
  12096. this._offsetsCache = {};
  12097. this._highLimitsCache = {};
  12098. this._stopped = false;
  12099. this.targetPropertyPath = targetProperty.split(".");
  12100. this.dataType = dataType;
  12101. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  12102. }
  12103. Animation.prototype.isStopped = function () {
  12104. return this._stopped;
  12105. };
  12106. Animation.prototype.getKeys = function () {
  12107. return this._keys;
  12108. };
  12109. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  12110. return startValue + (endValue - startValue) * gradient;
  12111. };
  12112. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  12113. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  12114. };
  12115. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  12116. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  12117. };
  12118. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  12119. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  12120. };
  12121. Animation.prototype.clone = function () {
  12122. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  12123. clone.setKeys(this._keys);
  12124. return clone;
  12125. };
  12126. Animation.prototype.setKeys = function (values) {
  12127. this._keys = values.slice(0);
  12128. this._offsetsCache = {};
  12129. this._highLimitsCache = {};
  12130. };
  12131. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  12132. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  12133. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  12134. }
  12135. this.currentFrame = currentFrame;
  12136. for (var key = 0; key < this._keys.length; key++) {
  12137. if (this._keys[key + 1].frame >= currentFrame) {
  12138. var startValue = this._keys[key].value;
  12139. var endValue = this._keys[key + 1].value;
  12140. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  12141. switch (this.dataType) {
  12142. case Animation.ANIMATIONTYPE_FLOAT:
  12143. switch (loopMode) {
  12144. case Animation.ANIMATIONLOOPMODE_CYCLE:
  12145. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  12146. return this.floatInterpolateFunction(startValue, endValue, gradient);
  12147. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  12148. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  12149. }
  12150. break;
  12151. case Animation.ANIMATIONTYPE_QUATERNION:
  12152. var quaternion = null;
  12153. switch (loopMode) {
  12154. case Animation.ANIMATIONLOOPMODE_CYCLE:
  12155. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  12156. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  12157. break;
  12158. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  12159. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  12160. break;
  12161. }
  12162. return quaternion;
  12163. case Animation.ANIMATIONTYPE_VECTOR3:
  12164. switch (loopMode) {
  12165. case Animation.ANIMATIONLOOPMODE_CYCLE:
  12166. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  12167. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  12168. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  12169. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  12170. }
  12171. case Animation.ANIMATIONTYPE_COLOR3:
  12172. switch (loopMode) {
  12173. case Animation.ANIMATIONLOOPMODE_CYCLE:
  12174. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  12175. return this.color3InterpolateFunction(startValue, endValue, gradient);
  12176. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  12177. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  12178. }
  12179. case Animation.ANIMATIONTYPE_MATRIX:
  12180. switch (loopMode) {
  12181. case Animation.ANIMATIONLOOPMODE_CYCLE:
  12182. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  12183. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  12184. return startValue;
  12185. }
  12186. default:
  12187. break;
  12188. }
  12189. break;
  12190. }
  12191. }
  12192. return this._keys[this._keys.length - 1].value;
  12193. };
  12194. Animation.prototype.animate = function (delay, from, to, loop, speedRatio) {
  12195. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  12196. this._stopped = true;
  12197. return false;
  12198. }
  12199. var returnValue = true;
  12200. if (this._keys[0].frame != 0) {
  12201. var newKey = {
  12202. frame: 0,
  12203. value: this._keys[0].value
  12204. };
  12205. this._keys.splice(0, 0, newKey);
  12206. }
  12207. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  12208. from = this._keys[0].frame;
  12209. }
  12210. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  12211. to = this._keys[this._keys.length - 1].frame;
  12212. }
  12213. var range = to - from;
  12214. var offsetValue;
  12215. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  12216. if (ratio > range && !loop) {
  12217. returnValue = false;
  12218. highLimitValue = this._keys[this._keys.length - 1].value;
  12219. } else {
  12220. var highLimitValue = 0;
  12221. if (this.loopMode != Animation.ANIMATIONLOOPMODE_CYCLE) {
  12222. var keyOffset = to.toString() + from.toString();
  12223. if (!this._offsetsCache[keyOffset]) {
  12224. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  12225. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  12226. switch (this.dataType) {
  12227. case Animation.ANIMATIONTYPE_FLOAT:
  12228. this._offsetsCache[keyOffset] = toValue - fromValue;
  12229. break;
  12230. case Animation.ANIMATIONTYPE_QUATERNION:
  12231. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  12232. break;
  12233. case Animation.ANIMATIONTYPE_VECTOR3:
  12234. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  12235. case Animation.ANIMATIONTYPE_COLOR3:
  12236. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  12237. default:
  12238. break;
  12239. }
  12240. this._highLimitsCache[keyOffset] = toValue;
  12241. }
  12242. highLimitValue = this._highLimitsCache[keyOffset];
  12243. offsetValue = this._offsetsCache[keyOffset];
  12244. }
  12245. }
  12246. if (offsetValue === undefined) {
  12247. switch (this.dataType) {
  12248. case Animation.ANIMATIONTYPE_FLOAT:
  12249. offsetValue = 0;
  12250. break;
  12251. case Animation.ANIMATIONTYPE_QUATERNION:
  12252. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  12253. break;
  12254. case Animation.ANIMATIONTYPE_VECTOR3:
  12255. offsetValue = BABYLON.Vector3.Zero();
  12256. break;
  12257. case Animation.ANIMATIONTYPE_COLOR3:
  12258. offsetValue = BABYLON.Color3.Black();
  12259. }
  12260. }
  12261. var repeatCount = (ratio / range) >> 0;
  12262. var currentFrame = returnValue ? from + ratio % range : to;
  12263. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  12264. if (this.targetPropertyPath.length > 1) {
  12265. var property = this._target[this.targetPropertyPath[0]];
  12266. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  12267. property = property[this.targetPropertyPath[index]];
  12268. }
  12269. property[this.targetPropertyPath[this.targetPropertyPath.length - 1]] = currentValue;
  12270. } else {
  12271. this._target[this.targetPropertyPath[0]] = currentValue;
  12272. }
  12273. if (this._target.markAsDirty) {
  12274. this._target.markAsDirty(this.targetProperty);
  12275. }
  12276. if (!returnValue) {
  12277. this._stopped = true;
  12278. }
  12279. return returnValue;
  12280. };
  12281. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  12282. get: function () {
  12283. return Animation._ANIMATIONTYPE_FLOAT;
  12284. },
  12285. enumerable: true,
  12286. configurable: true
  12287. });
  12288. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  12289. get: function () {
  12290. return Animation._ANIMATIONTYPE_VECTOR3;
  12291. },
  12292. enumerable: true,
  12293. configurable: true
  12294. });
  12295. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  12296. get: function () {
  12297. return Animation._ANIMATIONTYPE_QUATERNION;
  12298. },
  12299. enumerable: true,
  12300. configurable: true
  12301. });
  12302. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  12303. get: function () {
  12304. return Animation._ANIMATIONTYPE_MATRIX;
  12305. },
  12306. enumerable: true,
  12307. configurable: true
  12308. });
  12309. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  12310. get: function () {
  12311. return Animation._ANIMATIONTYPE_COLOR3;
  12312. },
  12313. enumerable: true,
  12314. configurable: true
  12315. });
  12316. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  12317. get: function () {
  12318. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  12319. },
  12320. enumerable: true,
  12321. configurable: true
  12322. });
  12323. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  12324. get: function () {
  12325. return Animation._ANIMATIONLOOPMODE_CYCLE;
  12326. },
  12327. enumerable: true,
  12328. configurable: true
  12329. });
  12330. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  12331. get: function () {
  12332. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  12333. },
  12334. enumerable: true,
  12335. configurable: true
  12336. });
  12337. Animation._ANIMATIONTYPE_FLOAT = 0;
  12338. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  12339. Animation._ANIMATIONTYPE_QUATERNION = 2;
  12340. Animation._ANIMATIONTYPE_MATRIX = 3;
  12341. Animation._ANIMATIONTYPE_COLOR3 = 4;
  12342. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  12343. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  12344. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  12345. return Animation;
  12346. })();
  12347. BABYLON.Animation = Animation;
  12348. })(BABYLON || (BABYLON = {}));
  12349. var BABYLON;
  12350. (function (BABYLON) {
  12351. var Animatable = (function () {
  12352. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  12353. if (typeof fromFrame === "undefined") { fromFrame = 0; }
  12354. if (typeof toFrame === "undefined") { toFrame = 100; }
  12355. if (typeof loopAnimation === "undefined") { loopAnimation = false; }
  12356. if (typeof speedRatio === "undefined") { speedRatio = 1.0; }
  12357. this.target = target;
  12358. this.fromFrame = fromFrame;
  12359. this.toFrame = toFrame;
  12360. this.loopAnimation = loopAnimation;
  12361. this.speedRatio = speedRatio;
  12362. this.onAnimationEnd = onAnimationEnd;
  12363. this._animations = new Array();
  12364. this._paused = false;
  12365. this.animationStarted = false;
  12366. if (animations) {
  12367. this.appendAnimations(target, animations);
  12368. }
  12369. this._scene = scene;
  12370. scene._activeAnimatables.push(this);
  12371. }
  12372. Animatable.prototype.appendAnimations = function (target, animations) {
  12373. for (var index = 0; index < animations.length; index++) {
  12374. var animation = animations[index];
  12375. animation._target = target;
  12376. this._animations.push(animation);
  12377. }
  12378. };
  12379. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  12380. var animations = this._animations;
  12381. for (var index = 0; index < animations.length; index++) {
  12382. if (animations[index].targetProperty === property) {
  12383. return animations[index];
  12384. }
  12385. }
  12386. return null;
  12387. };
  12388. Animatable.prototype.pause = function () {
  12389. this._paused = true;
  12390. };
  12391. Animatable.prototype.restart = function () {
  12392. this._paused = false;
  12393. };
  12394. Animatable.prototype.stop = function () {
  12395. var index = this._scene._activeAnimatables.indexOf(this);
  12396. if (index > -1) {
  12397. this._scene._activeAnimatables.splice(index, 1);
  12398. }
  12399. if (this.onAnimationEnd) {
  12400. this.onAnimationEnd();
  12401. }
  12402. };
  12403. Animatable.prototype._animate = function (delay) {
  12404. if (this._paused) {
  12405. return true;
  12406. }
  12407. if (!this._localDelayOffset) {
  12408. this._localDelayOffset = delay;
  12409. }
  12410. var running = false;
  12411. var animations = this._animations;
  12412. for (var index = 0; index < animations.length; index++) {
  12413. var animation = animations[index];
  12414. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  12415. running = running || isRunning;
  12416. }
  12417. if (!running && this.onAnimationEnd) {
  12418. this.onAnimationEnd();
  12419. }
  12420. return running;
  12421. };
  12422. return Animatable;
  12423. })();
  12424. BABYLON.Animatable = Animatable;
  12425. })(BABYLON || (BABYLON = {}));
  12426. var BABYLON;
  12427. (function (BABYLON) {
  12428. var Octree = (function () {
  12429. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  12430. if (typeof maxDepth === "undefined") { maxDepth = 2; }
  12431. this.maxDepth = maxDepth;
  12432. this.dynamicContent = new Array();
  12433. this._maxBlockCapacity = maxBlockCapacity || 64;
  12434. this._selectionContent = new BABYLON.SmartArray(1024);
  12435. this._creationFunc = creationFunc;
  12436. }
  12437. Octree.prototype.update = function (worldMin, worldMax, entries) {
  12438. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  12439. };
  12440. Octree.prototype.addMesh = function (entry) {
  12441. for (var index = 0; index < this.blocks.length; index++) {
  12442. var block = this.blocks[index];
  12443. block.addEntry(entry);
  12444. }
  12445. };
  12446. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  12447. this._selectionContent.reset();
  12448. for (var index = 0; index < this.blocks.length; index++) {
  12449. var block = this.blocks[index];
  12450. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  12451. }
  12452. if (allowDuplicate) {
  12453. this._selectionContent.concat(this.dynamicContent);
  12454. } else {
  12455. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  12456. }
  12457. return this._selectionContent;
  12458. };
  12459. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  12460. this._selectionContent.reset();
  12461. for (var index = 0; index < this.blocks.length; index++) {
  12462. var block = this.blocks[index];
  12463. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  12464. }
  12465. if (allowDuplicate) {
  12466. this._selectionContent.concat(this.dynamicContent);
  12467. } else {
  12468. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  12469. }
  12470. return this._selectionContent;
  12471. };
  12472. Octree.prototype.intersectsRay = function (ray) {
  12473. this._selectionContent.reset();
  12474. for (var index = 0; index < this.blocks.length; index++) {
  12475. var block = this.blocks[index];
  12476. block.intersectsRay(ray, this._selectionContent);
  12477. }
  12478. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  12479. return this._selectionContent;
  12480. };
  12481. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  12482. target.blocks = new Array();
  12483. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  12484. for (var x = 0; x < 2; x++) {
  12485. for (var y = 0; y < 2; y++) {
  12486. for (var z = 0; z < 2; z++) {
  12487. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  12488. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  12489. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  12490. block.addEntries(entries);
  12491. target.blocks.push(block);
  12492. }
  12493. }
  12494. }
  12495. };
  12496. Octree.CreationFuncForMeshes = function (entry, block) {
  12497. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  12498. block.entries.push(entry);
  12499. }
  12500. };
  12501. Octree.CreationFuncForSubMeshes = function (entry, block) {
  12502. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  12503. block.entries.push(entry);
  12504. }
  12505. };
  12506. return Octree;
  12507. })();
  12508. BABYLON.Octree = Octree;
  12509. })(BABYLON || (BABYLON = {}));
  12510. var BABYLON;
  12511. (function (BABYLON) {
  12512. var OctreeBlock = (function () {
  12513. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  12514. this.entries = new Array();
  12515. this._boundingVectors = new Array();
  12516. this._capacity = capacity;
  12517. this._depth = depth;
  12518. this._maxDepth = maxDepth;
  12519. this._creationFunc = creationFunc;
  12520. this._minPoint = minPoint;
  12521. this._maxPoint = maxPoint;
  12522. this._boundingVectors.push(minPoint.clone());
  12523. this._boundingVectors.push(maxPoint.clone());
  12524. this._boundingVectors.push(minPoint.clone());
  12525. this._boundingVectors[2].x = maxPoint.x;
  12526. this._boundingVectors.push(minPoint.clone());
  12527. this._boundingVectors[3].y = maxPoint.y;
  12528. this._boundingVectors.push(minPoint.clone());
  12529. this._boundingVectors[4].z = maxPoint.z;
  12530. this._boundingVectors.push(maxPoint.clone());
  12531. this._boundingVectors[5].z = minPoint.z;
  12532. this._boundingVectors.push(maxPoint.clone());
  12533. this._boundingVectors[6].x = minPoint.x;
  12534. this._boundingVectors.push(maxPoint.clone());
  12535. this._boundingVectors[7].y = minPoint.y;
  12536. }
  12537. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  12538. get: function () {
  12539. return this._capacity;
  12540. },
  12541. enumerable: true,
  12542. configurable: true
  12543. });
  12544. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  12545. get: function () {
  12546. return this._minPoint;
  12547. },
  12548. enumerable: true,
  12549. configurable: true
  12550. });
  12551. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  12552. get: function () {
  12553. return this._maxPoint;
  12554. },
  12555. enumerable: true,
  12556. configurable: true
  12557. });
  12558. OctreeBlock.prototype.addEntry = function (entry) {
  12559. if (this.blocks) {
  12560. for (var index = 0; index < this.blocks.length; index++) {
  12561. var block = this.blocks[index];
  12562. block.addEntry(entry);
  12563. }
  12564. return;
  12565. }
  12566. this._creationFunc(entry, this);
  12567. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  12568. this.createInnerBlocks();
  12569. }
  12570. };
  12571. OctreeBlock.prototype.addEntries = function (entries) {
  12572. for (var index = 0; index < entries.length; index++) {
  12573. var mesh = entries[index];
  12574. this.addEntry(mesh);
  12575. }
  12576. };
  12577. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  12578. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  12579. if (this.blocks) {
  12580. for (var index = 0; index < this.blocks.length; index++) {
  12581. var block = this.blocks[index];
  12582. block.select(frustumPlanes, selection, allowDuplicate);
  12583. }
  12584. return;
  12585. }
  12586. if (allowDuplicate) {
  12587. selection.concat(this.entries);
  12588. } else {
  12589. selection.concatWithNoDuplicate(this.entries);
  12590. }
  12591. }
  12592. };
  12593. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  12594. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  12595. if (this.blocks) {
  12596. for (var index = 0; index < this.blocks.length; index++) {
  12597. var block = this.blocks[index];
  12598. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  12599. }
  12600. return;
  12601. }
  12602. if (allowDuplicate) {
  12603. selection.concat(this.entries);
  12604. } else {
  12605. selection.concatWithNoDuplicate(this.entries);
  12606. }
  12607. }
  12608. };
  12609. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  12610. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  12611. if (this.blocks) {
  12612. for (var index = 0; index < this.blocks.length; index++) {
  12613. var block = this.blocks[index];
  12614. block.intersectsRay(ray, selection);
  12615. }
  12616. return;
  12617. }
  12618. selection.concatWithNoDuplicate(this.entries);
  12619. }
  12620. };
  12621. OctreeBlock.prototype.createInnerBlocks = function () {
  12622. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  12623. };
  12624. return OctreeBlock;
  12625. })();
  12626. BABYLON.OctreeBlock = OctreeBlock;
  12627. })(BABYLON || (BABYLON = {}));
  12628. var BABYLON;
  12629. (function (BABYLON) {
  12630. var Bone = (function () {
  12631. function Bone(name, skeleton, parentBone, matrix) {
  12632. this.name = name;
  12633. this.children = new Array();
  12634. this.animations = new Array();
  12635. this._worldTransform = new BABYLON.Matrix();
  12636. this._absoluteTransform = new BABYLON.Matrix();
  12637. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  12638. this._skeleton = skeleton;
  12639. this._matrix = matrix;
  12640. this._baseMatrix = matrix;
  12641. skeleton.bones.push(this);
  12642. if (parentBone) {
  12643. this._parent = parentBone;
  12644. parentBone.children.push(this);
  12645. } else {
  12646. this._parent = null;
  12647. }
  12648. this._updateDifferenceMatrix();
  12649. }
  12650. Bone.prototype.getParent = function () {
  12651. return this._parent;
  12652. };
  12653. Bone.prototype.getLocalMatrix = function () {
  12654. return this._matrix;
  12655. };
  12656. Bone.prototype.getBaseMatrix = function () {
  12657. return this._baseMatrix;
  12658. };
  12659. Bone.prototype.getWorldMatrix = function () {
  12660. return this._worldTransform;
  12661. };
  12662. Bone.prototype.getInvertedAbsoluteTransform = function () {
  12663. return this._invertedAbsoluteTransform;
  12664. };
  12665. Bone.prototype.getAbsoluteMatrix = function () {
  12666. var matrix = this._matrix.clone();
  12667. var parent = this._parent;
  12668. while (parent) {
  12669. matrix = matrix.multiply(parent.getLocalMatrix());
  12670. parent = parent.getParent();
  12671. }
  12672. return matrix;
  12673. };
  12674. Bone.prototype.updateMatrix = function (matrix) {
  12675. this._matrix = matrix;
  12676. this._skeleton._markAsDirty();
  12677. this._updateDifferenceMatrix();
  12678. };
  12679. Bone.prototype._updateDifferenceMatrix = function () {
  12680. if (this._parent) {
  12681. this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  12682. } else {
  12683. this._absoluteTransform.copyFrom(this._matrix);
  12684. }
  12685. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  12686. for (var index = 0; index < this.children.length; index++) {
  12687. this.children[index]._updateDifferenceMatrix();
  12688. }
  12689. };
  12690. Bone.prototype.markAsDirty = function () {
  12691. this._skeleton._markAsDirty();
  12692. };
  12693. return Bone;
  12694. })();
  12695. BABYLON.Bone = Bone;
  12696. })(BABYLON || (BABYLON = {}));
  12697. var BABYLON;
  12698. (function (BABYLON) {
  12699. var Skeleton = (function () {
  12700. function Skeleton(name, id, scene) {
  12701. this.name = name;
  12702. this.id = id;
  12703. this.bones = new Array();
  12704. this._isDirty = true;
  12705. this._identity = BABYLON.Matrix.Identity();
  12706. this.bones = [];
  12707. this._scene = scene;
  12708. scene.skeletons.push(this);
  12709. }
  12710. Skeleton.prototype.getTransformMatrices = function () {
  12711. return this._transformMatrices;
  12712. };
  12713. Skeleton.prototype._markAsDirty = function () {
  12714. this._isDirty = true;
  12715. };
  12716. Skeleton.prototype.prepare = function () {
  12717. if (!this._isDirty) {
  12718. return;
  12719. }
  12720. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  12721. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  12722. }
  12723. for (var index = 0; index < this.bones.length; index++) {
  12724. var bone = this.bones[index];
  12725. var parentBone = bone.getParent();
  12726. if (parentBone) {
  12727. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  12728. } else {
  12729. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  12730. }
  12731. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), this._transformMatrices, index * 16);
  12732. }
  12733. this._identity.copyToArray(this._transformMatrices, this.bones.length * 16);
  12734. this._isDirty = false;
  12735. };
  12736. Skeleton.prototype.getAnimatables = function () {
  12737. if (!this._animatables || this._animatables.length != this.bones.length) {
  12738. this._animatables = [];
  12739. for (var index = 0; index < this.bones.length; index++) {
  12740. this._animatables.push(this.bones[index]);
  12741. }
  12742. }
  12743. return this._animatables;
  12744. };
  12745. Skeleton.prototype.clone = function (name, id) {
  12746. var result = new BABYLON.Skeleton(name, id || name, this._scene);
  12747. for (var index = 0; index < this.bones.length; index++) {
  12748. var source = this.bones[index];
  12749. var parentBone = null;
  12750. if (source.getParent()) {
  12751. var parentIndex = this.bones.indexOf(source.getParent());
  12752. parentBone = result.bones[parentIndex];
  12753. }
  12754. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix());
  12755. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  12756. }
  12757. return result;
  12758. };
  12759. return Skeleton;
  12760. })();
  12761. BABYLON.Skeleton = Skeleton;
  12762. })(BABYLON || (BABYLON = {}));
  12763. var BABYLON;
  12764. (function (BABYLON) {
  12765. var PostProcess = (function () {
  12766. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable) {
  12767. this.name = name;
  12768. this.width = -1;
  12769. this.height = -1;
  12770. this._reusable = false;
  12771. this._textures = new BABYLON.SmartArray(2);
  12772. this._currentRenderTextureInd = 0;
  12773. if (camera != null) {
  12774. this._camera = camera;
  12775. this._scene = camera.getScene();
  12776. camera.attachPostProcess(this);
  12777. this._engine = this._scene.getEngine();
  12778. } else {
  12779. this._engine = engine;
  12780. }
  12781. this._renderRatio = ratio;
  12782. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  12783. this._reusable = reusable || false;
  12784. samplers = samplers || [];
  12785. samplers.push("textureSampler");
  12786. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: fragmentUrl }, ["position"], parameters || [], samplers, "");
  12787. }
  12788. PostProcess.prototype.isReusable = function () {
  12789. return this._reusable;
  12790. };
  12791. PostProcess.prototype.activate = function (camera, sourceTexture) {
  12792. camera = camera || this._camera;
  12793. var scene = camera.getScene();
  12794. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  12795. var desiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  12796. var desiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  12797. desiredWidth = BABYLON.Tools.GetExponantOfTwo(desiredWidth, maxSize);
  12798. desiredHeight = BABYLON.Tools.GetExponantOfTwo(desiredHeight, maxSize);
  12799. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  12800. if (this._textures.length > 0) {
  12801. for (var i = 0; i < this._textures.length; i++) {
  12802. this._engine._releaseTexture(this._textures.data[i]);
  12803. }
  12804. this._textures.reset();
  12805. }
  12806. this.width = desiredWidth;
  12807. this.height = desiredHeight;
  12808. 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 }));
  12809. if (this._reusable) {
  12810. 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 }));
  12811. }
  12812. if (this.onSizeChanged) {
  12813. this.onSizeChanged();
  12814. }
  12815. }
  12816. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  12817. if (this.onActivate) {
  12818. this.onActivate(camera);
  12819. }
  12820. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  12821. if (this._reusable) {
  12822. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  12823. }
  12824. };
  12825. PostProcess.prototype.apply = function () {
  12826. if (!this._effect.isReady())
  12827. return null;
  12828. this._engine.enableEffect(this._effect);
  12829. this._engine.setState(false);
  12830. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  12831. this._engine.setDepthBuffer(false);
  12832. this._engine.setDepthWrite(false);
  12833. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  12834. if (this.onApply) {
  12835. this.onApply(this._effect);
  12836. }
  12837. return this._effect;
  12838. };
  12839. PostProcess.prototype.dispose = function (camera) {
  12840. camera = camera || this._camera;
  12841. if (this._textures.length > 0) {
  12842. for (var i = 0; i < this._textures.length; i++) {
  12843. this._engine._releaseTexture(this._textures.data[i]);
  12844. }
  12845. this._textures.reset();
  12846. }
  12847. camera.detachPostProcess(this);
  12848. var index = camera._postProcesses.indexOf(this);
  12849. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  12850. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1;
  12851. }
  12852. };
  12853. return PostProcess;
  12854. })();
  12855. BABYLON.PostProcess = PostProcess;
  12856. })(BABYLON || (BABYLON = {}));
  12857. var BABYLON;
  12858. (function (BABYLON) {
  12859. var PostProcessManager = (function () {
  12860. function PostProcessManager(scene) {
  12861. this._vertexDeclaration = [2];
  12862. this._vertexStrideSize = 2 * 4;
  12863. this._scene = scene;
  12864. var vertices = [];
  12865. vertices.push(1, 1);
  12866. vertices.push(-1, 1);
  12867. vertices.push(-1, -1);
  12868. vertices.push(1, -1);
  12869. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  12870. var indices = [];
  12871. indices.push(0);
  12872. indices.push(1);
  12873. indices.push(2);
  12874. indices.push(0);
  12875. indices.push(2);
  12876. indices.push(3);
  12877. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  12878. }
  12879. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  12880. var postProcesses = this._scene.activeCamera._postProcesses;
  12881. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  12882. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  12883. return false;
  12884. }
  12885. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  12886. return true;
  12887. };
  12888. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture) {
  12889. var postProcesses = this._scene.activeCamera._postProcesses;
  12890. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  12891. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  12892. return;
  12893. }
  12894. var engine = this._scene.getEngine();
  12895. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  12896. if (index < postProcessesTakenIndices.length - 1) {
  12897. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera);
  12898. } else {
  12899. if (targetTexture) {
  12900. engine.bindFramebuffer(targetTexture);
  12901. } else {
  12902. engine.restoreDefaultFramebuffer();
  12903. }
  12904. }
  12905. if (doNotPresent) {
  12906. break;
  12907. }
  12908. var pp = postProcesses[postProcessesTakenIndices[index]];
  12909. var effect = pp.apply();
  12910. if (effect) {
  12911. if (pp.onBeforeRender) {
  12912. pp.onBeforeRender(effect);
  12913. }
  12914. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  12915. engine.draw(true, 0, 6);
  12916. }
  12917. }
  12918. engine.setDepthBuffer(true);
  12919. engine.setDepthWrite(true);
  12920. };
  12921. PostProcessManager.prototype.dispose = function () {
  12922. if (this._vertexBuffer) {
  12923. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  12924. this._vertexBuffer = null;
  12925. }
  12926. if (this._indexBuffer) {
  12927. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  12928. this._indexBuffer = null;
  12929. }
  12930. };
  12931. return PostProcessManager;
  12932. })();
  12933. BABYLON.PostProcessManager = PostProcessManager;
  12934. })(BABYLON || (BABYLON = {}));
  12935. var __extends = this.__extends || function (d, b) {
  12936. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  12937. function __() { this.constructor = d; }
  12938. __.prototype = b.prototype;
  12939. d.prototype = new __();
  12940. };
  12941. var BABYLON;
  12942. (function (BABYLON) {
  12943. var PassPostProcess = (function (_super) {
  12944. __extends(PassPostProcess, _super);
  12945. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  12946. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  12947. }
  12948. return PassPostProcess;
  12949. })(BABYLON.PostProcess);
  12950. BABYLON.PassPostProcess = PassPostProcess;
  12951. })(BABYLON || (BABYLON = {}));
  12952. var __extends = this.__extends || function (d, b) {
  12953. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  12954. function __() { this.constructor = d; }
  12955. __.prototype = b.prototype;
  12956. d.prototype = new __();
  12957. };
  12958. var BABYLON;
  12959. (function (BABYLON) {
  12960. var BlurPostProcess = (function (_super) {
  12961. __extends(BlurPostProcess, _super);
  12962. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  12963. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  12964. var _this = this;
  12965. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  12966. this.direction = direction;
  12967. this.blurWidth = blurWidth;
  12968. this.onApply = function (effect) {
  12969. effect.setFloat2("screenSize", _this.width, _this.height);
  12970. effect.setVector2("direction", _this.direction);
  12971. effect.setFloat("blurWidth", _this.blurWidth);
  12972. };
  12973. }
  12974. return BlurPostProcess;
  12975. })(BABYLON.PostProcess);
  12976. BABYLON.BlurPostProcess = BlurPostProcess;
  12977. })(BABYLON || (BABYLON = {}));
  12978. var __extends = this.__extends || function (d, b) {
  12979. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  12980. function __() { this.constructor = d; }
  12981. __.prototype = b.prototype;
  12982. d.prototype = new __();
  12983. };
  12984. var BABYLON;
  12985. (function (BABYLON) {
  12986. var FilterPostProcess = (function (_super) {
  12987. __extends(FilterPostProcess, _super);
  12988. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  12989. var _this = this;
  12990. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  12991. this.kernelMatrix = kernelMatrix;
  12992. this.onApply = function (effect) {
  12993. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  12994. };
  12995. }
  12996. return FilterPostProcess;
  12997. })(BABYLON.PostProcess);
  12998. BABYLON.FilterPostProcess = FilterPostProcess;
  12999. })(BABYLON || (BABYLON = {}));
  13000. var __extends = this.__extends || function (d, b) {
  13001. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  13002. function __() { this.constructor = d; }
  13003. __.prototype = b.prototype;
  13004. d.prototype = new __();
  13005. };
  13006. var BABYLON;
  13007. (function (BABYLON) {
  13008. var RefractionPostProcess = (function (_super) {
  13009. __extends(RefractionPostProcess, _super);
  13010. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  13011. var _this = this;
  13012. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  13013. this.color = color;
  13014. this.depth = depth;
  13015. this.colorLevel = colorLevel;
  13016. this.onActivate = function (cam) {
  13017. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  13018. };
  13019. this.onApply = function (effect) {
  13020. effect.setColor3("baseColor", _this.color);
  13021. effect.setFloat("depth", _this.depth);
  13022. effect.setFloat("colorLevel", _this.colorLevel);
  13023. effect.setTexture("refractionSampler", _this._refRexture);
  13024. };
  13025. }
  13026. RefractionPostProcess.prototype.dispose = function (camera) {
  13027. if (this._refRexture) {
  13028. this._refRexture.dispose();
  13029. }
  13030. _super.prototype.dispose.call(this, camera);
  13031. };
  13032. return RefractionPostProcess;
  13033. })(BABYLON.PostProcess);
  13034. BABYLON.RefractionPostProcess = RefractionPostProcess;
  13035. })(BABYLON || (BABYLON = {}));
  13036. var __extends = this.__extends || function (d, b) {
  13037. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  13038. function __() { this.constructor = d; }
  13039. __.prototype = b.prototype;
  13040. d.prototype = new __();
  13041. };
  13042. var BABYLON;
  13043. (function (BABYLON) {
  13044. var BlackAndWhitePostProcess = (function (_super) {
  13045. __extends(BlackAndWhitePostProcess, _super);
  13046. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  13047. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  13048. }
  13049. return BlackAndWhitePostProcess;
  13050. })(BABYLON.PostProcess);
  13051. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  13052. })(BABYLON || (BABYLON = {}));
  13053. var __extends = this.__extends || function (d, b) {
  13054. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  13055. function __() { this.constructor = d; }
  13056. __.prototype = b.prototype;
  13057. d.prototype = new __();
  13058. };
  13059. var BABYLON;
  13060. (function (BABYLON) {
  13061. var ConvolutionPostProcess = (function (_super) {
  13062. __extends(ConvolutionPostProcess, _super);
  13063. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  13064. var _this = this;
  13065. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  13066. this.kernel = kernel;
  13067. this.onApply = function (effect) {
  13068. effect.setFloat2("screenSize", _this.width, _this.height);
  13069. effect.setArray("kernel", _this.kernel);
  13070. };
  13071. }
  13072. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  13073. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  13074. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  13075. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  13076. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  13077. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  13078. return ConvolutionPostProcess;
  13079. })(BABYLON.PostProcess);
  13080. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  13081. })(BABYLON || (BABYLON = {}));
  13082. var __extends = this.__extends || function (d, b) {
  13083. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  13084. function __() { this.constructor = d; }
  13085. __.prototype = b.prototype;
  13086. d.prototype = new __();
  13087. };
  13088. var BABYLON;
  13089. (function (BABYLON) {
  13090. var FxaaPostProcess = (function (_super) {
  13091. __extends(FxaaPostProcess, _super);
  13092. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  13093. var _this = this;
  13094. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  13095. this.onSizeChanged = function () {
  13096. _this.texelWidth = 1.0 / _this.width;
  13097. _this.texelHeight = 1.0 / _this.height;
  13098. };
  13099. this.onApply = function (effect) {
  13100. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  13101. };
  13102. }
  13103. return FxaaPostProcess;
  13104. })(BABYLON.PostProcess);
  13105. BABYLON.FxaaPostProcess = FxaaPostProcess;
  13106. })(BABYLON || (BABYLON = {}));
  13107. var BABYLON;
  13108. (function (BABYLON) {
  13109. var LensFlare = (function () {
  13110. function LensFlare(size, position, color, imgUrl, system) {
  13111. this.size = size;
  13112. this.position = position;
  13113. this.dispose = function () {
  13114. if (this.texture) {
  13115. this.texture.dispose();
  13116. }
  13117. var index = this._system.lensFlares.indexOf(this);
  13118. this._system.lensFlares.splice(index, 1);
  13119. };
  13120. this.color = color || new BABYLON.Color3(1, 1, 1);
  13121. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  13122. this._system = system;
  13123. system.lensFlares.push(this);
  13124. }
  13125. return LensFlare;
  13126. })();
  13127. BABYLON.LensFlare = LensFlare;
  13128. })(BABYLON || (BABYLON = {}));
  13129. var BABYLON;
  13130. (function (BABYLON) {
  13131. var LensFlareSystem = (function () {
  13132. function LensFlareSystem(name, emitter, scene) {
  13133. this.name = name;
  13134. this.lensFlares = new Array();
  13135. this.borderLimit = 300;
  13136. this._vertexDeclaration = [2];
  13137. this._vertexStrideSize = 2 * 4;
  13138. this._isEnabled = true;
  13139. this._scene = scene;
  13140. this._emitter = emitter;
  13141. scene.lensFlareSystems.push(this);
  13142. this.meshesSelectionPredicate = function (m) {
  13143. return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0);
  13144. };
  13145. var vertices = [];
  13146. vertices.push(1, 1);
  13147. vertices.push(-1, 1);
  13148. vertices.push(-1, -1);
  13149. vertices.push(1, -1);
  13150. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  13151. var indices = [];
  13152. indices.push(0);
  13153. indices.push(1);
  13154. indices.push(2);
  13155. indices.push(0);
  13156. indices.push(2);
  13157. indices.push(3);
  13158. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  13159. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  13160. }
  13161. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  13162. get: function () {
  13163. return this._isEnabled;
  13164. },
  13165. set: function (value) {
  13166. this._isEnabled = value;
  13167. },
  13168. enumerable: true,
  13169. configurable: true
  13170. });
  13171. LensFlareSystem.prototype.getScene = function () {
  13172. return this._scene;
  13173. };
  13174. LensFlareSystem.prototype.getEmitter = function () {
  13175. return this._emitter;
  13176. };
  13177. LensFlareSystem.prototype.getEmitterPosition = function () {
  13178. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  13179. };
  13180. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  13181. var position = this.getEmitterPosition();
  13182. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  13183. this._positionX = position.x;
  13184. this._positionY = position.y;
  13185. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  13186. if (position.z > 0) {
  13187. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  13188. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  13189. return true;
  13190. }
  13191. }
  13192. return false;
  13193. };
  13194. LensFlareSystem.prototype._isVisible = function () {
  13195. if (!this._isEnabled) {
  13196. return false;
  13197. }
  13198. var emitterPosition = this.getEmitterPosition();
  13199. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  13200. var distance = direction.length();
  13201. direction.normalize();
  13202. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  13203. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  13204. return !pickInfo.hit || pickInfo.distance > distance;
  13205. };
  13206. LensFlareSystem.prototype.render = function () {
  13207. if (!this._effect.isReady())
  13208. return false;
  13209. var engine = this._scene.getEngine();
  13210. var viewport = this._scene.activeCamera.viewport;
  13211. var globalViewport = viewport.toGlobal(engine);
  13212. if (!this.computeEffectivePosition(globalViewport)) {
  13213. return false;
  13214. }
  13215. if (!this._isVisible()) {
  13216. return false;
  13217. }
  13218. var awayX;
  13219. var awayY;
  13220. if (this._positionX < this.borderLimit + globalViewport.x) {
  13221. awayX = this.borderLimit + globalViewport.x - this._positionX;
  13222. } else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  13223. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  13224. } else {
  13225. awayX = 0;
  13226. }
  13227. if (this._positionY < this.borderLimit + globalViewport.y) {
  13228. awayY = this.borderLimit + globalViewport.y - this._positionY;
  13229. } else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  13230. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  13231. } else {
  13232. awayY = 0;
  13233. }
  13234. var away = (awayX > awayY) ? awayX : awayY;
  13235. if (away > this.borderLimit) {
  13236. away = this.borderLimit;
  13237. }
  13238. var intensity = 1.0 - (away / this.borderLimit);
  13239. if (intensity < 0) {
  13240. return false;
  13241. }
  13242. if (intensity > 1.0) {
  13243. intensity = 1.0;
  13244. }
  13245. var centerX = globalViewport.x + globalViewport.width / 2;
  13246. var centerY = globalViewport.y + globalViewport.height / 2;
  13247. var distX = centerX - this._positionX;
  13248. var distY = centerY - this._positionY;
  13249. engine.enableEffect(this._effect);
  13250. engine.setState(false);
  13251. engine.setDepthBuffer(false);
  13252. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  13253. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  13254. for (var index = 0; index < this.lensFlares.length; index++) {
  13255. var flare = this.lensFlares[index];
  13256. var x = centerX - (distX * flare.position);
  13257. var y = centerY - (distY * flare.position);
  13258. var cw = flare.size;
  13259. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera);
  13260. var cx = 2 * (x / globalViewport.width) - 1.0;
  13261. var cy = 1.0 - 2 * (y / globalViewport.height);
  13262. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  13263. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  13264. this._effect.setTexture("textureSampler", flare.texture);
  13265. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  13266. engine.draw(true, 0, 6);
  13267. }
  13268. engine.setDepthBuffer(true);
  13269. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  13270. return true;
  13271. };
  13272. LensFlareSystem.prototype.dispose = function () {
  13273. if (this._vertexBuffer) {
  13274. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  13275. this._vertexBuffer = null;
  13276. }
  13277. if (this._indexBuffer) {
  13278. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  13279. this._indexBuffer = null;
  13280. }
  13281. while (this.lensFlares.length) {
  13282. this.lensFlares[0].dispose();
  13283. }
  13284. var index = this._scene.lensFlareSystems.indexOf(this);
  13285. this._scene.lensFlareSystems.splice(index, 1);
  13286. };
  13287. return LensFlareSystem;
  13288. })();
  13289. BABYLON.LensFlareSystem = LensFlareSystem;
  13290. })(BABYLON || (BABYLON = {}));
  13291. var BABYLON;
  13292. (function (BABYLON) {
  13293. var IntersectionInfo = (function () {
  13294. function IntersectionInfo(bu, bv, distance) {
  13295. this.bu = bu;
  13296. this.bv = bv;
  13297. this.distance = distance;
  13298. this.faceId = 0;
  13299. }
  13300. return IntersectionInfo;
  13301. })();
  13302. BABYLON.IntersectionInfo = IntersectionInfo;
  13303. var PickingInfo = (function () {
  13304. function PickingInfo() {
  13305. this.hit = false;
  13306. this.distance = 0;
  13307. this.pickedPoint = null;
  13308. this.pickedMesh = null;
  13309. this.bu = 0;
  13310. this.bv = 0;
  13311. this.faceId = -1;
  13312. }
  13313. PickingInfo.prototype.getNormal = function () {
  13314. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  13315. return null;
  13316. }
  13317. var indices = this.pickedMesh.getIndices();
  13318. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  13319. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  13320. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  13321. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  13322. normal0 = normal0.scale(this.bu);
  13323. normal1 = normal1.scale(this.bv);
  13324. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  13325. return new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  13326. };
  13327. PickingInfo.prototype.getTextureCoordinates = function () {
  13328. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  13329. return null;
  13330. }
  13331. var indices = this.pickedMesh.getIndices();
  13332. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  13333. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  13334. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  13335. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  13336. uv0 = uv0.scale(this.bu);
  13337. uv1 = uv1.scale(this.bv);
  13338. uv2 = uv2.scale(1.0 - this.bu - this.bv);
  13339. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  13340. };
  13341. return PickingInfo;
  13342. })();
  13343. BABYLON.PickingInfo = PickingInfo;
  13344. })(BABYLON || (BABYLON = {}));
  13345. var BABYLON;
  13346. (function (BABYLON) {
  13347. var FilesInput = (function () {
  13348. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  13349. this.engine = p_engine;
  13350. this.canvas = p_canvas;
  13351. this.currentScene = p_scene;
  13352. this.sceneLoadedCallback = p_sceneLoadedCallback;
  13353. this.progressCallback = p_progressCallback;
  13354. this.additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  13355. this.textureLoadingCallback = p_textureLoadingCallback;
  13356. this.startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  13357. }
  13358. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  13359. var _this = this;
  13360. if (p_elementToMonitor) {
  13361. this.elementToMonitor = p_elementToMonitor;
  13362. this.elementToMonitor.addEventListener("dragenter", function (e) {
  13363. _this.drag(e);
  13364. }, false);
  13365. this.elementToMonitor.addEventListener("dragover", function (e) {
  13366. _this.drag(e);
  13367. }, false);
  13368. this.elementToMonitor.addEventListener("drop", function (e) {
  13369. _this.drop(e);
  13370. }, false);
  13371. }
  13372. };
  13373. FilesInput.prototype.renderFunction = function () {
  13374. if (this.additionnalRenderLoopLogicCallback) {
  13375. this.additionnalRenderLoopLogicCallback();
  13376. }
  13377. if (this.currentScene) {
  13378. if (this.textureLoadingCallback) {
  13379. var remaining = this.currentScene.getWaitingItemsCount();
  13380. if (remaining > 0) {
  13381. this.textureLoadingCallback(remaining);
  13382. }
  13383. }
  13384. this.currentScene.render();
  13385. }
  13386. };
  13387. FilesInput.prototype.drag = function (e) {
  13388. e.stopPropagation();
  13389. e.preventDefault();
  13390. };
  13391. FilesInput.prototype.drop = function (eventDrop) {
  13392. eventDrop.stopPropagation();
  13393. eventDrop.preventDefault();
  13394. this.loadFiles(eventDrop);
  13395. };
  13396. FilesInput.prototype.loadFiles = function (event) {
  13397. var _this = this;
  13398. var that = this;
  13399. if (this.startingProcessingFilesCallback)
  13400. this.startingProcessingFilesCallback();
  13401. var sceneFileToLoad;
  13402. var filesToLoad;
  13403. if (event && event.dataTransfer && event.dataTransfer.files) {
  13404. filesToLoad = event.dataTransfer.files;
  13405. }
  13406. if (event && event.target && event.target.files) {
  13407. filesToLoad = event.target.files;
  13408. }
  13409. if (filesToLoad && filesToLoad.length > 0) {
  13410. for (var i = 0; i < filesToLoad.length; i++) {
  13411. switch (filesToLoad[i].type) {
  13412. case "image/jpeg":
  13413. case "image/png":
  13414. BABYLON.FilesInput.FilesTextures[filesToLoad[i].name] = filesToLoad[i];
  13415. break;
  13416. case "image/targa":
  13417. case "image/vnd.ms-dds":
  13418. BABYLON.FilesInput.FilesToLoad[filesToLoad[i].name] = filesToLoad[i];
  13419. break;
  13420. default:
  13421. 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) {
  13422. sceneFileToLoad = filesToLoad[i];
  13423. }
  13424. break;
  13425. }
  13426. }
  13427. if (sceneFileToLoad) {
  13428. if (this.currentScene) {
  13429. this.engine.stopRenderLoop();
  13430. this.currentScene.dispose();
  13431. }
  13432. BABYLON.SceneLoader.Load("file:", sceneFileToLoad, this.engine, function (newScene) {
  13433. that.currentScene = newScene;
  13434. that.currentScene.executeWhenReady(function () {
  13435. if (that.currentScene.activeCamera) {
  13436. that.currentScene.activeCamera.attachControl(that.canvas);
  13437. }
  13438. if (that.sceneLoadedCallback) {
  13439. that.sceneLoadedCallback(sceneFileToLoad, that.currentScene);
  13440. }
  13441. that.engine.runRenderLoop(function () {
  13442. that.renderFunction();
  13443. });
  13444. });
  13445. }, function (progress) {
  13446. if (_this.progressCallback) {
  13447. _this.progressCallback(progress);
  13448. }
  13449. });
  13450. } else {
  13451. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  13452. }
  13453. }
  13454. };
  13455. FilesInput.FilesTextures = new Array();
  13456. FilesInput.FilesToLoad = new Array();
  13457. return FilesInput;
  13458. })();
  13459. BABYLON.FilesInput = FilesInput;
  13460. })(BABYLON || (BABYLON = {}));
  13461. var BABYLON;
  13462. (function (BABYLON) {
  13463. var OimoJSPlugin = (function () {
  13464. function OimoJSPlugin() {
  13465. this._registeredMeshes = [];
  13466. /**
  13467. * Update the body position according to the mesh position
  13468. * @param mesh
  13469. */
  13470. this.updateBodyPosition = function (mesh) {
  13471. for (var index = 0; index < this._registeredMeshes.length; index++) {
  13472. var registeredMesh = this._registeredMeshes[index];
  13473. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  13474. var body = registeredMesh.body.body;
  13475. mesh.computeWorldMatrix(true);
  13476. var center = mesh.getBoundingInfo().boundingBox.center;
  13477. body.setPosition(center.x, center.y, center.z);
  13478. body.setOrientation(mesh.rotation.x, mesh.rotation.y, mesh.rotation.z);
  13479. return;
  13480. }
  13481. if (registeredMesh.mesh.parent === mesh) {
  13482. mesh.computeWorldMatrix(true);
  13483. registeredMesh.mesh.computeWorldMatrix(true);
  13484. var absolutePosition = registeredMesh.mesh.getAbsolutePosition();
  13485. var absoluteRotation = mesh.rotation;
  13486. body = registeredMesh.body.body;
  13487. body.setPosition(absolutePosition.x, absolutePosition.y, absolutePosition.z);
  13488. body.setOrientation(absoluteRotation.x, absoluteRotation.y, absoluteRotation.z);
  13489. return;
  13490. }
  13491. }
  13492. };
  13493. }
  13494. OimoJSPlugin.prototype._checkWithEpsilon = function (value) {
  13495. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  13496. };
  13497. OimoJSPlugin.prototype.initialize = function (iterations) {
  13498. this._world = new OIMO.World();
  13499. this._world.clear();
  13500. };
  13501. OimoJSPlugin.prototype.setGravity = function (gravity) {
  13502. this._world.gravity = gravity;
  13503. };
  13504. OimoJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  13505. var body = null;
  13506. this.unregisterMesh(mesh);
  13507. mesh.computeWorldMatrix(true);
  13508. switch (impostor) {
  13509. case BABYLON.PhysicsEngine.SphereImpostor:
  13510. var bbox = mesh.getBoundingInfo().boundingBox;
  13511. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  13512. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  13513. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  13514. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  13515. var deltaPosition = mesh.position.subtract(bbox.center);
  13516. body = new OIMO.Body({
  13517. type: 'sphere',
  13518. size: [size],
  13519. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  13520. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  13521. move: options.mass != 0,
  13522. config: [options.mass, options.friction, options.restitution],
  13523. world: this._world
  13524. });
  13525. this._registeredMeshes.push({
  13526. mesh: mesh,
  13527. body: body,
  13528. delta: deltaPosition
  13529. });
  13530. break;
  13531. case BABYLON.PhysicsEngine.PlaneImpostor:
  13532. case BABYLON.PhysicsEngine.BoxImpostor:
  13533. bbox = mesh.getBoundingInfo().boundingBox;
  13534. var min = bbox.minimumWorld;
  13535. var max = bbox.maximumWorld;
  13536. var box = max.subtract(min);
  13537. var sizeX = this._checkWithEpsilon(box.x);
  13538. var sizeY = this._checkWithEpsilon(box.y);
  13539. var sizeZ = this._checkWithEpsilon(box.z);
  13540. var deltaPosition = mesh.position.subtract(bbox.center);
  13541. body = new OIMO.Body({
  13542. type: 'box',
  13543. size: [sizeX, sizeY, sizeZ],
  13544. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  13545. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  13546. move: options.mass != 0,
  13547. config: [options.mass, options.friction, options.restitution],
  13548. world: this._world
  13549. });
  13550. this._registeredMeshes.push({
  13551. mesh: mesh,
  13552. body: body,
  13553. delta: deltaPosition
  13554. });
  13555. break;
  13556. }
  13557. return body;
  13558. };
  13559. OimoJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  13560. var types = [], sizes = [], positions = [], rotations = [];
  13561. var initialMesh = parts[0].mesh;
  13562. for (var index = 0; index < parts.length; index++) {
  13563. var part = parts[index];
  13564. var bodyParameters = this._createBodyAsCompound(part, options, initialMesh);
  13565. types.push(bodyParameters.type);
  13566. sizes.push.apply(sizes, bodyParameters.size);
  13567. positions.push.apply(positions, bodyParameters.pos);
  13568. rotations.push.apply(rotations, bodyParameters.rot);
  13569. }
  13570. var body = new OIMO.Body({
  13571. type: types,
  13572. size: sizes,
  13573. pos: positions,
  13574. rot: rotations,
  13575. move: options.mass != 0,
  13576. config: [options.mass, options.friction, options.restitution],
  13577. world: this._world
  13578. });
  13579. this._registeredMeshes.push({
  13580. mesh: initialMesh,
  13581. body: body
  13582. });
  13583. return body;
  13584. };
  13585. OimoJSPlugin.prototype._createBodyAsCompound = function (part, options, initialMesh) {
  13586. var bodyParameters = null;
  13587. var mesh = part.mesh;
  13588. switch (part.impostor) {
  13589. case BABYLON.PhysicsEngine.SphereImpostor:
  13590. var bbox = mesh.getBoundingInfo().boundingBox;
  13591. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  13592. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  13593. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  13594. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  13595. bodyParameters = {
  13596. type: 'sphere',
  13597. /* bug with oimo : sphere needs 3 sizes in this case */
  13598. size: [size, -1, -1],
  13599. pos: [mesh.position.x, mesh.position.y, mesh.position.z],
  13600. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  13601. };
  13602. break;
  13603. case BABYLON.PhysicsEngine.PlaneImpostor:
  13604. case BABYLON.PhysicsEngine.BoxImpostor:
  13605. bbox = mesh.getBoundingInfo().boundingBox;
  13606. var min = bbox.minimumWorld;
  13607. var max = bbox.maximumWorld;
  13608. var box = max.subtract(min);
  13609. var sizeX = this._checkWithEpsilon(box.x);
  13610. var sizeY = this._checkWithEpsilon(box.y);
  13611. var sizeZ = this._checkWithEpsilon(box.z);
  13612. var relativePosition = mesh.position;
  13613. bodyParameters = {
  13614. type: 'box',
  13615. size: [sizeX, sizeY, sizeZ],
  13616. pos: [relativePosition.x, relativePosition.y, relativePosition.z],
  13617. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  13618. };
  13619. break;
  13620. }
  13621. return bodyParameters;
  13622. };
  13623. OimoJSPlugin.prototype.unregisterMesh = function (mesh) {
  13624. for (var index = 0; index < this._registeredMeshes.length; index++) {
  13625. var registeredMesh = this._registeredMeshes[index];
  13626. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  13627. if (registeredMesh.body) {
  13628. this._world.removeRigidBody(registeredMesh.body.body);
  13629. this._unbindBody(registeredMesh.body);
  13630. }
  13631. this._registeredMeshes.splice(index, 1);
  13632. return;
  13633. }
  13634. }
  13635. };
  13636. OimoJSPlugin.prototype._unbindBody = function (body) {
  13637. for (var index = 0; index < this._registeredMeshes.length; index++) {
  13638. var registeredMesh = this._registeredMeshes[index];
  13639. if (registeredMesh.body === body) {
  13640. registeredMesh.body = null;
  13641. }
  13642. }
  13643. };
  13644. OimoJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  13645. for (var index = 0; index < this._registeredMeshes.length; index++) {
  13646. var registeredMesh = this._registeredMeshes[index];
  13647. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  13648. var mass = registeredMesh.body.body.massInfo.mass;
  13649. registeredMesh.body.body.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  13650. return;
  13651. }
  13652. }
  13653. };
  13654. OimoJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  13655. var body1 = null, body2 = null;
  13656. for (var index = 0; index < this._registeredMeshes.length; index++) {
  13657. var registeredMesh = this._registeredMeshes[index];
  13658. if (registeredMesh.mesh === mesh1) {
  13659. body1 = registeredMesh.body.body;
  13660. } else if (registeredMesh.mesh === mesh2) {
  13661. body2 = registeredMesh.body.body;
  13662. }
  13663. }
  13664. if (!body1 || !body2) {
  13665. return false;
  13666. }
  13667. if (!options) {
  13668. options = {};
  13669. }
  13670. new OIMO.Link({
  13671. type: options.type,
  13672. body1: body1,
  13673. body2: body2,
  13674. min: options.min,
  13675. max: options.max,
  13676. axe1: options.axe1,
  13677. axe2: options.axe2,
  13678. pos1: [pivot1.x, pivot1.y, pivot1.z],
  13679. pos2: [pivot2.x, pivot2.y, pivot2.z],
  13680. collision: options.collision,
  13681. spring: options.spring,
  13682. world: this._world
  13683. });
  13684. return true;
  13685. };
  13686. OimoJSPlugin.prototype.dispose = function () {
  13687. this._world.clear();
  13688. while (this._registeredMeshes.length) {
  13689. this.unregisterMesh(this._registeredMeshes[0].mesh);
  13690. }
  13691. };
  13692. OimoJSPlugin.prototype.isSupported = function () {
  13693. return OIMO !== undefined;
  13694. };
  13695. OimoJSPlugin.prototype._getLastShape = function (body) {
  13696. var lastShape = body.shapes;
  13697. while (lastShape.next) {
  13698. lastShape = lastShape.next;
  13699. }
  13700. return lastShape;
  13701. };
  13702. OimoJSPlugin.prototype.runOneStep = function (time) {
  13703. this._world.step();
  13704. var i = this._registeredMeshes.length;
  13705. var m;
  13706. while (i--) {
  13707. var body = this._registeredMeshes[i].body.body;
  13708. var mesh = this._registeredMeshes[i].mesh;
  13709. var delta = this._registeredMeshes[i].delta;
  13710. if (!body.sleeping) {
  13711. if (body.shapes.next) {
  13712. var parentShape = this._getLastShape(body);
  13713. mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  13714. mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  13715. mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  13716. var mtx = BABYLON.Matrix.FromArray(body.getMatrix());
  13717. if (!mesh.rotationQuaternion) {
  13718. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  13719. }
  13720. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  13721. } else {
  13722. m = body.getMatrix();
  13723. mtx = BABYLON.Matrix.FromArray(m);
  13724. var bodyX = mtx.m[12], bodyY = mtx.m[13], bodyZ = mtx.m[14];
  13725. if (!delta) {
  13726. mesh.position.x = bodyX;
  13727. mesh.position.y = bodyY;
  13728. mesh.position.z = bodyZ;
  13729. } else {
  13730. mesh.position.x = bodyX + delta.x;
  13731. mesh.position.y = bodyY + delta.y;
  13732. mesh.position.z = bodyZ + delta.z;
  13733. }
  13734. if (!mesh.rotationQuaternion) {
  13735. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  13736. }
  13737. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  13738. }
  13739. }
  13740. }
  13741. };
  13742. return OimoJSPlugin;
  13743. })();
  13744. BABYLON.OimoJSPlugin = OimoJSPlugin;
  13745. })(BABYLON || (BABYLON = {}));
  13746. var BABYLON;
  13747. (function (BABYLON) {
  13748. var PhysicsEngine = (function () {
  13749. function PhysicsEngine(plugin) {
  13750. this._currentPlugin = plugin || new BABYLON.OimoJSPlugin();
  13751. }
  13752. PhysicsEngine.prototype._initialize = function (gravity) {
  13753. this._currentPlugin.initialize();
  13754. this._setGravity(gravity);
  13755. };
  13756. PhysicsEngine.prototype._runOneStep = function (delta) {
  13757. if (delta > 0.1) {
  13758. delta = 0.1;
  13759. } else if (delta <= 0) {
  13760. delta = 1.0 / 60.0;
  13761. }
  13762. this._currentPlugin.runOneStep(delta);
  13763. };
  13764. PhysicsEngine.prototype._setGravity = function (gravity) {
  13765. this.gravity = gravity || new BABYLON.Vector3(0, -9.82, 0);
  13766. this._currentPlugin.setGravity(this.gravity);
  13767. };
  13768. PhysicsEngine.prototype._registerMesh = function (mesh, impostor, options) {
  13769. return this._currentPlugin.registerMesh(mesh, impostor, options);
  13770. };
  13771. PhysicsEngine.prototype._registerMeshesAsCompound = function (parts, options) {
  13772. return this._currentPlugin.registerMeshesAsCompound(parts, options);
  13773. };
  13774. PhysicsEngine.prototype._unregisterMesh = function (mesh) {
  13775. this._currentPlugin.unregisterMesh(mesh);
  13776. };
  13777. PhysicsEngine.prototype._applyImpulse = function (mesh, force, contactPoint) {
  13778. this._currentPlugin.applyImpulse(mesh, force, contactPoint);
  13779. };
  13780. PhysicsEngine.prototype._createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  13781. return this._currentPlugin.createLink(mesh1, mesh2, pivot1, pivot2, options);
  13782. };
  13783. PhysicsEngine.prototype._updateBodyPosition = function (mesh) {
  13784. this._currentPlugin.updateBodyPosition(mesh);
  13785. };
  13786. PhysicsEngine.prototype.dispose = function () {
  13787. this._currentPlugin.dispose();
  13788. };
  13789. PhysicsEngine.prototype.isSupported = function () {
  13790. return this._currentPlugin.isSupported();
  13791. };
  13792. PhysicsEngine.NoImpostor = 0;
  13793. PhysicsEngine.SphereImpostor = 1;
  13794. PhysicsEngine.BoxImpostor = 2;
  13795. PhysicsEngine.PlaneImpostor = 3;
  13796. PhysicsEngine.MeshImpostor = 4;
  13797. PhysicsEngine.CapsuleImpostor = 5;
  13798. PhysicsEngine.ConeImpostor = 6;
  13799. PhysicsEngine.CylinderImpostor = 7;
  13800. PhysicsEngine.ConvexHullImpostor = 8;
  13801. PhysicsEngine.Epsilon = 0.001;
  13802. return PhysicsEngine;
  13803. })();
  13804. BABYLON.PhysicsEngine = PhysicsEngine;
  13805. })(BABYLON || (BABYLON = {}));
  13806. var BABYLON;
  13807. (function (BABYLON) {
  13808. var serializeLight = function (light) {
  13809. var serializationObject = {};
  13810. serializationObject.name = light.name;
  13811. serializationObject.id = light.id;
  13812. serializationObject.tags = BABYLON.Tags.GetTags(light);
  13813. if (light instanceof BABYLON.PointLight) {
  13814. serializationObject.type = 0;
  13815. serializationObject.position = light.position.asArray();
  13816. } else if (light instanceof BABYLON.DirectionalLight) {
  13817. serializationObject.type = 1;
  13818. var directionalLight = light;
  13819. serializationObject.position = directionalLight.position.asArray();
  13820. serializationObject.direction = directionalLight.direction.asArray();
  13821. } else if (light instanceof BABYLON.SpotLight) {
  13822. serializationObject.type = 2;
  13823. var spotLight = light;
  13824. serializationObject.position = spotLight.position.asArray();
  13825. serializationObject.direction = spotLight.position.asArray();
  13826. serializationObject.angle = spotLight.angle;
  13827. serializationObject.exponent = spotLight.exponent;
  13828. } else if (light instanceof BABYLON.HemisphericLight) {
  13829. serializationObject.type = 3;
  13830. var hemisphericLight = light;
  13831. serializationObject.direction = hemisphericLight.direction.asArray();
  13832. serializationObject.groundColor = hemisphericLight.groundColor.asArray();
  13833. }
  13834. if (light.intensity) {
  13835. serializationObject.intensity = light.intensity;
  13836. }
  13837. serializationObject.range = light.range;
  13838. serializationObject.diffuse = light.diffuse.asArray();
  13839. serializationObject.specular = light.specular.asArray();
  13840. return serializationObject;
  13841. };
  13842. var serializeFresnelParameter = function (fresnelParameter) {
  13843. var serializationObject = {};
  13844. serializationObject.isEnabled = fresnelParameter.isEnabled;
  13845. serializationObject.leftColor = fresnelParameter.leftColor;
  13846. serializationObject.rightColor = fresnelParameter.rightColor;
  13847. serializationObject.bias = fresnelParameter.bias;
  13848. serializationObject.power = fresnelParameter.power;
  13849. return serializationObject;
  13850. };
  13851. var serializeCamera = function (camera) {
  13852. var serializationObject = {};
  13853. serializationObject.name = camera.name;
  13854. serializationObject.tags = BABYLON.Tags.GetTags(camera);
  13855. serializationObject.id = camera.id;
  13856. serializationObject.position = camera.position.asArray();
  13857. if (camera.parent) {
  13858. serializationObject.parentId = camera.parent.id;
  13859. }
  13860. serializationObject.rotation = camera.rotation.asArray();
  13861. if (camera.lockedTarget && camera.lockedTarget.id) {
  13862. serializationObject.lockedTargetId = camera.lockedTarget.id;
  13863. }
  13864. serializationObject.fov = camera.fov;
  13865. serializationObject.minZ = camera.minZ;
  13866. serializationObject.maxZ = camera.maxZ;
  13867. serializationObject.speed = camera.speed;
  13868. serializationObject.inertia = camera.inertia;
  13869. serializationObject.checkCollisions = camera.checkCollisions;
  13870. serializationObject.applyGravity = camera.applyGravity;
  13871. if (camera.ellipsoid) {
  13872. serializationObject.ellipsoid = camera.ellipsoid.asArray();
  13873. }
  13874. appendAnimations(camera, serializationObject);
  13875. serializationObject.layerMask = camera.layerMask;
  13876. return serializationObject;
  13877. };
  13878. var appendAnimations = function (source, destination) {
  13879. if (source.animations) {
  13880. destination.animations = [];
  13881. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  13882. var animation = source.animations[animationIndex];
  13883. destination.animations.push(serializeAnimation(animation));
  13884. }
  13885. }
  13886. };
  13887. var serializeAnimation = function (animation) {
  13888. var serializationObject = {};
  13889. serializationObject.name = animation.name;
  13890. serializationObject.property = animation.targetProperty;
  13891. serializationObject.framePerSecond = animation.framePerSecond;
  13892. serializationObject.dataType = animation.dataType;
  13893. serializationObject.loopBehavior = animation.loopMode;
  13894. var dataType = animation.dataType;
  13895. serializationObject.keys = [];
  13896. var keys = animation.getKeys();
  13897. for (var index = 0; index < keys.length; index++) {
  13898. var animationKey = keys[index];
  13899. var key = {};
  13900. key.frame = animationKey.frame;
  13901. switch (dataType) {
  13902. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  13903. key.values = [animationKey.value];
  13904. break;
  13905. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  13906. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  13907. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  13908. key.values = animationKey.value.asArray();
  13909. break;
  13910. }
  13911. serializationObject.keys.push(key);
  13912. }
  13913. return serializationObject;
  13914. };
  13915. var serializeMultiMaterial = function (material) {
  13916. var serializationObject = {};
  13917. serializationObject.name = material.name;
  13918. serializationObject.id = material.id;
  13919. serializationObject.tags = BABYLON.Tags.GetTags(material);
  13920. serializationObject.materials = [];
  13921. for (var matIndex = 0; matIndex < material.subMaterials.length; matIndex++) {
  13922. var subMat = material.subMaterials[matIndex];
  13923. if (subMat) {
  13924. serializationObject.materials.push(subMat.id);
  13925. } else {
  13926. serializationObject.materials.push(null);
  13927. }
  13928. }
  13929. return serializationObject;
  13930. };
  13931. var serializeMaterial = function (material) {
  13932. var serializationObject = {};
  13933. serializationObject.name = material.name;
  13934. serializationObject.ambient = material.ambientColor.asArray();
  13935. serializationObject.diffuse = material.diffuseColor.asArray();
  13936. serializationObject.specular = material.specularColor.asArray();
  13937. serializationObject.specularPower = material.specularPower;
  13938. serializationObject.emissive = material.emissiveColor.asArray();
  13939. serializationObject.alpha = material.alpha;
  13940. serializationObject.id = material.id;
  13941. serializationObject.tags = BABYLON.Tags.GetTags(material);
  13942. serializationObject.backFaceCulling = material.backFaceCulling;
  13943. if (material.diffuseTexture) {
  13944. serializationObject.diffuseTexture = serializeTexture(material.diffuseTexture);
  13945. }
  13946. if (material.diffuseFresnelParameters) {
  13947. serializationObject.diffuseFresnelParameters = serializeFresnelParameter(material.diffuseFresnelParameters);
  13948. }
  13949. if (material.ambientTexture) {
  13950. serializationObject.ambientTexture = serializeTexture(material.ambientTexture);
  13951. }
  13952. if (material.opacityTexture) {
  13953. serializationObject.opacityTexture = serializeTexture(material.opacityTexture);
  13954. }
  13955. if (material.opacityFresnelParameters) {
  13956. serializationObject.opacityFresnelParameters = serializeFresnelParameter(material.opacityFresnelParameters);
  13957. }
  13958. if (material.reflectionTexture) {
  13959. serializationObject.reflectionTexture = serializeTexture(material.reflectionTexture);
  13960. }
  13961. if (material.reflectionFresnelParameters) {
  13962. serializationObject.reflectionFresnelParameters = serializeFresnelParameter(material.reflectionFresnelParameters);
  13963. }
  13964. if (material.emissiveTexture) {
  13965. serializationObject.emissiveTexture = serializeTexture(material.emissiveTexture);
  13966. }
  13967. if (material.emissiveFresnelParameters) {
  13968. serializationObject.emissiveFresnelParameters = serializeFresnelParameter(material.emissiveFresnelParameters);
  13969. }
  13970. if (material.specularTexture) {
  13971. serializationObject.specularTexture = serializeTexture(material.specularTexture);
  13972. }
  13973. if (material.bumpTexture) {
  13974. serializationObject.bumpTexture = serializeTexture(material.bumpTexture);
  13975. }
  13976. return serializationObject;
  13977. };
  13978. var serializeTexture = function (texture) {
  13979. var serializationObject = {};
  13980. if (!texture.name) {
  13981. return null;
  13982. }
  13983. if (texture instanceof BABYLON.CubeTexture) {
  13984. serializationObject.name = texture.name;
  13985. serializationObject.hasAlpha = texture.hasAlpha;
  13986. serializationObject.level = texture.level;
  13987. serializationObject.coordinatesMode = texture.coordinatesMode;
  13988. return serializationObject;
  13989. }
  13990. if (texture instanceof BABYLON.MirrorTexture) {
  13991. var mirrorTexture = texture;
  13992. serializationObject.renderTargetSize = mirrorTexture.getRenderSize();
  13993. serializationObject.renderList = [];
  13994. for (var index = 0; index < mirrorTexture.renderList.length; index++) {
  13995. serializationObject.renderList.push(mirrorTexture.renderList[index].id);
  13996. }
  13997. serializationObject.mirrorPlane = mirrorTexture.mirrorPlane.asArray();
  13998. } else if (texture instanceof BABYLON.RenderTargetTexture) {
  13999. var renderTargetTexture = texture;
  14000. serializationObject.renderTargetSize = renderTargetTexture.getRenderSize();
  14001. serializationObject.renderList = [];
  14002. for (index = 0; index < renderTargetTexture.renderList.length; index++) {
  14003. serializationObject.renderList.push(renderTargetTexture.renderList[index].id);
  14004. }
  14005. }
  14006. var regularTexture = texture;
  14007. serializationObject.name = texture.name;
  14008. serializationObject.hasAlpha = texture.hasAlpha;
  14009. serializationObject.level = texture.level;
  14010. serializationObject.coordinatesIndex = texture.coordinatesIndex;
  14011. serializationObject.coordinatesMode = texture.coordinatesMode;
  14012. serializationObject.uOffset = regularTexture.uOffset;
  14013. serializationObject.vOffset = regularTexture.vOffset;
  14014. serializationObject.uScale = regularTexture.uScale;
  14015. serializationObject.vScale = regularTexture.vScale;
  14016. serializationObject.uAng = regularTexture.uAng;
  14017. serializationObject.vAng = regularTexture.vAng;
  14018. serializationObject.wAng = regularTexture.wAng;
  14019. serializationObject.wrapU = texture.wrapU;
  14020. serializationObject.wrapV = texture.wrapV;
  14021. appendAnimations(texture, serializationObject);
  14022. return serializationObject;
  14023. };
  14024. var serializeSkeleton = function (skeleton) {
  14025. var serializationObject = {};
  14026. serializationObject.name = skeleton.name;
  14027. serializationObject.id = skeleton.id;
  14028. serializationObject.bones = [];
  14029. for (var index = 0; index < skeleton.bones.length; index++) {
  14030. var bone = skeleton.bones[index];
  14031. var serializedBone = {
  14032. parentBoneIndex: bone.getParent() ? skeleton.bones.indexOf(bone.getParent()) : -1,
  14033. name: bone.name,
  14034. matrix: bone.getLocalMatrix().toArray()
  14035. };
  14036. serializationObject.bones.push(serializedBone);
  14037. if (bone.animations && bone.animations.length > 0) {
  14038. serializedBone.animation = serializeAnimation(bone.animations[0]);
  14039. }
  14040. }
  14041. return serializationObject;
  14042. };
  14043. var serializeParticleSystem = function (particleSystem) {
  14044. var serializationObject = {};
  14045. serializationObject.emitterId = particleSystem.emitter.id;
  14046. serializationObject.capacity = particleSystem.getCapacity();
  14047. if (particleSystem.particleTexture) {
  14048. serializationObject.textureName = particleSystem.particleTexture.name;
  14049. }
  14050. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  14051. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  14052. serializationObject.minSize = particleSystem.minSize;
  14053. serializationObject.maxSize = particleSystem.maxSize;
  14054. serializationObject.minLifeTime = particleSystem.minLifeTime;
  14055. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  14056. serializationObject.emitRate = particleSystem.emitRate;
  14057. serializationObject.minEmitBox = particleSystem.minEmitBox.asArray();
  14058. serializationObject.maxEmitBox = particleSystem.maxEmitBox.asArray();
  14059. serializationObject.gravity = particleSystem.gravity.asArray();
  14060. serializationObject.direction1 = particleSystem.direction1.asArray();
  14061. serializationObject.direction2 = particleSystem.direction2.asArray();
  14062. serializationObject.color1 = particleSystem.color1.asArray();
  14063. serializationObject.color2 = particleSystem.color2.asArray();
  14064. serializationObject.colorDead = particleSystem.colorDead.asArray();
  14065. serializationObject.updateSpeed = particleSystem.updateSpeed;
  14066. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  14067. serializationObject.textureMask = particleSystem.textureMask.asArray();
  14068. serializationObject.blendMode = particleSystem.blendMode;
  14069. return serializationObject;
  14070. };
  14071. var serializeLensFlareSystem = function (lensFlareSystem) {
  14072. var serializationObject = {};
  14073. serializationObject.emitterId = lensFlareSystem.getEmitter().id;
  14074. serializationObject.borderLimit = lensFlareSystem.borderLimit;
  14075. serializationObject.flares = [];
  14076. for (var index = 0; index < lensFlareSystem.lensFlares.length; index++) {
  14077. var flare = lensFlareSystem.lensFlares[index];
  14078. serializationObject.flares.push({
  14079. size: flare.size,
  14080. position: flare.position,
  14081. color: flare.color.asArray(),
  14082. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  14083. });
  14084. }
  14085. return serializationObject;
  14086. };
  14087. var serializeShadowGenerator = function (light) {
  14088. var serializationObject = {};
  14089. var shadowGenerator = light.getShadowGenerator();
  14090. serializationObject.lightId = light.id;
  14091. serializationObject.mapSize = shadowGenerator.getShadowMap().getRenderSize();
  14092. serializationObject.useVarianceShadowMap = shadowGenerator.useVarianceShadowMap;
  14093. serializationObject.usePoissonSampling = shadowGenerator.usePoissonSampling;
  14094. serializationObject.renderList = [];
  14095. for (var meshIndex = 0; meshIndex < shadowGenerator.getShadowMap().renderList.length; meshIndex++) {
  14096. var mesh = shadowGenerator.getShadowMap().renderList[meshIndex];
  14097. serializationObject.renderList.push(mesh.id);
  14098. }
  14099. return serializationObject;
  14100. };
  14101. var serializedGeometries = [];
  14102. var serializeGeometry = function (geometry, serializationGeometries) {
  14103. if (serializedGeometries[geometry.id]) {
  14104. return;
  14105. }
  14106. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  14107. serializationGeometries.boxes.push(serializeBox(geometry));
  14108. } else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  14109. serializationGeometries.spheres.push(serializeSphere(geometry));
  14110. } else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  14111. serializationGeometries.cylinders.push(serializeCylinder(geometry));
  14112. } else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  14113. serializationGeometries.toruses.push(serializeTorus(geometry));
  14114. } else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  14115. serializationGeometries.grounds.push(serializeGround(geometry));
  14116. } else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  14117. serializationGeometries.planes.push(serializePlane(geometry));
  14118. } else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  14119. serializationGeometries.torusKnots.push(serializeTorusKnot(geometry));
  14120. } else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  14121. throw new Error("Unknow primitive type");
  14122. } else {
  14123. serializationGeometries.vertexData.push(serializeVertexData(geometry));
  14124. }
  14125. serializedGeometries[geometry.id] = true;
  14126. };
  14127. var serializeGeometryBase = function (geometry) {
  14128. var serializationObject = {};
  14129. serializationObject.id = geometry.id;
  14130. if (BABYLON.Tags.HasTags(geometry)) {
  14131. serializationObject.tags = BABYLON.Tags.GetTags(geometry);
  14132. }
  14133. return serializationObject;
  14134. };
  14135. var serializeVertexData = function (vertexData) {
  14136. var serializationObject = serializeGeometryBase(vertexData);
  14137. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  14138. serializationObject.positions = vertexData.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14139. }
  14140. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  14141. serializationObject.normals = vertexData.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14142. }
  14143. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  14144. serializationObject.uvs = vertexData.getVerticesData(BABYLON.VertexBuffer.UVKind);
  14145. }
  14146. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  14147. serializationObject.uvs2 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  14148. }
  14149. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  14150. serializationObject.colors = vertexData.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  14151. }
  14152. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  14153. serializationObject.matricesIndices = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  14154. serializationObject.matricesIndices._isExpanded = true;
  14155. }
  14156. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  14157. serializationObject.matricesWeights = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  14158. }
  14159. serializationObject.indices = vertexData.getIndices();
  14160. return serializationObject;
  14161. };
  14162. var serializePrimitive = function (primitive) {
  14163. var serializationObject = serializeGeometryBase(primitive);
  14164. serializationObject.canBeRegenerated = primitive.canBeRegenerated();
  14165. return serializationObject;
  14166. };
  14167. var serializeBox = function (box) {
  14168. var serializationObject = serializePrimitive(box);
  14169. serializationObject.size = box.size;
  14170. return serializationObject;
  14171. };
  14172. var serializeSphere = function (sphere) {
  14173. var serializationObject = serializePrimitive(sphere);
  14174. serializationObject.segments = sphere.segments;
  14175. serializationObject.diameter = sphere.diameter;
  14176. return serializationObject;
  14177. };
  14178. var serializeCylinder = function (cylinder) {
  14179. var serializationObject = serializePrimitive(cylinder);
  14180. serializationObject.height = cylinder.height;
  14181. serializationObject.diameterTop = cylinder.diameterTop;
  14182. serializationObject.diameterBottom = cylinder.diameterBottom;
  14183. serializationObject.tessellation = cylinder.tessellation;
  14184. return serializationObject;
  14185. };
  14186. var serializeTorus = function (torus) {
  14187. var serializationObject = serializePrimitive(torus);
  14188. serializationObject.diameter = torus.diameter;
  14189. serializationObject.thickness = torus.thickness;
  14190. serializationObject.tessellation = torus.tessellation;
  14191. return serializationObject;
  14192. };
  14193. var serializeGround = function (ground) {
  14194. var serializationObject = serializePrimitive(ground);
  14195. serializationObject.width = ground.width;
  14196. serializationObject.height = ground.height;
  14197. serializationObject.subdivisions = ground.subdivisions;
  14198. return serializationObject;
  14199. };
  14200. var serializePlane = function (plane) {
  14201. var serializationObject = serializePrimitive(plane);
  14202. serializationObject.size = plane.size;
  14203. return serializationObject;
  14204. };
  14205. var serializeTorusKnot = function (torusKnot) {
  14206. var serializationObject = serializePrimitive(torusKnot);
  14207. serializationObject.radius = torusKnot.radius;
  14208. serializationObject.tube = torusKnot.tube;
  14209. serializationObject.radialSegments = torusKnot.radialSegments;
  14210. serializationObject.tubularSegments = torusKnot.tubularSegments;
  14211. serializationObject.p = torusKnot.p;
  14212. serializationObject.q = torusKnot.q;
  14213. return serializationObject;
  14214. };
  14215. var serializeMesh = function (mesh, serializationScene) {
  14216. var serializationObject = {};
  14217. serializationObject.name = mesh.name;
  14218. serializationObject.id = mesh.id;
  14219. if (BABYLON.Tags.HasTags(mesh)) {
  14220. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  14221. }
  14222. serializationObject.position = mesh.position.asArray();
  14223. if (mesh.rotationQuaternion) {
  14224. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  14225. } else if (mesh.rotation) {
  14226. serializationObject.rotation = mesh.rotation.asArray();
  14227. }
  14228. serializationObject.scaling = mesh.scaling.asArray();
  14229. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  14230. serializationObject.isEnabled = mesh.isEnabled();
  14231. serializationObject.isVisible = mesh.isVisible;
  14232. serializationObject.infiniteDistance = mesh.infiniteDistance;
  14233. serializationObject.pickable = mesh.isPickable;
  14234. serializationObject.receiveShadows = mesh.receiveShadows;
  14235. serializationObject.billboardMode = mesh.billboardMode;
  14236. serializationObject.visibility = mesh.visibility;
  14237. serializationObject.checkCollisions = mesh.checkCollisions;
  14238. if (mesh.parent) {
  14239. serializationObject.parentId = mesh.parent.id;
  14240. }
  14241. var geometry = mesh._geometry;
  14242. if (geometry) {
  14243. var geometryId = geometry.id;
  14244. serializationObject.geometryId = geometryId;
  14245. if (!mesh.getScene().getGeometryByID(geometryId)) {
  14246. serializeGeometry(geometry, serializationScene.geometries);
  14247. }
  14248. serializationObject.subMeshes = [];
  14249. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  14250. var subMesh = mesh.subMeshes[subIndex];
  14251. serializationObject.subMeshes.push({
  14252. materialIndex: subMesh.materialIndex,
  14253. verticesStart: subMesh.verticesStart,
  14254. verticesCount: subMesh.verticesCount,
  14255. indexStart: subMesh.indexStart,
  14256. indexCount: subMesh.indexCount
  14257. });
  14258. }
  14259. }
  14260. if (mesh.material) {
  14261. serializationObject.materialId = mesh.material.id;
  14262. } else {
  14263. mesh.material = null;
  14264. }
  14265. if (mesh.skeleton) {
  14266. serializationObject.skeletonId = mesh.skeleton.id;
  14267. }
  14268. if (mesh.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  14269. serializationObject.physicsMass = mesh.getPhysicsMass();
  14270. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  14271. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  14272. switch (mesh.getPhysicsImpostor()) {
  14273. case BABYLON.PhysicsEngine.BoxImpostor:
  14274. serializationObject.physicsImpostor = 1;
  14275. break;
  14276. case BABYLON.PhysicsEngine.SphereImpostor:
  14277. serializationObject.physicsImpostor = 2;
  14278. break;
  14279. }
  14280. }
  14281. serializationObject.instances = [];
  14282. for (var index = 0; index < mesh.instances.length; index++) {
  14283. var instance = mesh.instances[index];
  14284. var serializationInstance = {
  14285. name: instance.name,
  14286. position: instance.position,
  14287. rotation: instance.rotation,
  14288. rotationQuaternion: instance.rotationQuaternion,
  14289. scaling: instance.scaling
  14290. };
  14291. serializationObject.instances.push(serializationInstance);
  14292. appendAnimations(instance, serializationInstance);
  14293. }
  14294. appendAnimations(mesh, serializationObject);
  14295. serializationObject.layerMask = mesh.layerMask;
  14296. return serializationObject;
  14297. };
  14298. var SceneSerializer = (function () {
  14299. function SceneSerializer() {
  14300. }
  14301. SceneSerializer.Serialize = function (scene) {
  14302. var serializationObject = {};
  14303. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  14304. serializationObject.autoClear = scene.autoClear;
  14305. serializationObject.clearColor = scene.clearColor.asArray();
  14306. serializationObject.ambientColor = scene.ambientColor.asArray();
  14307. serializationObject.gravity = scene.gravity.asArray();
  14308. if (scene.fogMode && scene.fogMode !== 0) {
  14309. serializationObject.fogMode = scene.fogMode;
  14310. serializationObject.fogColor = scene.fogColor.asArray();
  14311. serializationObject.fogStart = scene.fogStart;
  14312. serializationObject.fogEnd = scene.fogEnd;
  14313. serializationObject.fogDensity = scene.fogDensity;
  14314. }
  14315. serializationObject.lights = [];
  14316. for (var index = 0; index < scene.lights.length; index++) {
  14317. var light = scene.lights[index];
  14318. serializationObject.lights.push(serializeLight(light));
  14319. }
  14320. serializationObject.cameras = [];
  14321. for (index = 0; index < scene.cameras.length; index++) {
  14322. var camera = scene.cameras[index];
  14323. if (camera instanceof BABYLON.FreeCamera) {
  14324. serializationObject.cameras.push(serializeCamera(camera));
  14325. }
  14326. }
  14327. if (scene.activeCamera) {
  14328. serializationObject.activeCameraID = scene.activeCamera.id;
  14329. }
  14330. serializationObject.materials = [];
  14331. serializationObject.multiMaterials = [];
  14332. for (index = 0; index < scene.materials.length; index++) {
  14333. var material = scene.materials[index];
  14334. if (material instanceof BABYLON.StandardMaterial) {
  14335. serializationObject.materials.push(serializeMaterial(material));
  14336. } else if (material instanceof BABYLON.MultiMaterial) {
  14337. serializationObject.multiMaterials.push(serializeMultiMaterial(material));
  14338. }
  14339. }
  14340. serializationObject.skeletons = [];
  14341. for (index = 0; index < scene.skeletons.length; index++) {
  14342. serializationObject.skeletons.push(serializeSkeleton(scene.skeletons[index]));
  14343. }
  14344. serializationObject.geometries = {};
  14345. serializationObject.geometries.boxes = [];
  14346. serializationObject.geometries.spheres = [];
  14347. serializationObject.geometries.cylinders = [];
  14348. serializationObject.geometries.toruses = [];
  14349. serializationObject.geometries.grounds = [];
  14350. serializationObject.geometries.planes = [];
  14351. serializationObject.geometries.torusKnots = [];
  14352. serializationObject.geometries.vertexData = [];
  14353. serializedGeometries = [];
  14354. var geometries = scene.getGeometries();
  14355. for (var index = 0; index < geometries.length; index++) {
  14356. var geometry = geometries[index];
  14357. if (geometry.isReady()) {
  14358. serializeGeometry(geometry, serializationObject.geometries);
  14359. }
  14360. }
  14361. serializationObject.meshes = [];
  14362. for (index = 0; index < scene.meshes.length; index++) {
  14363. var abstractMesh = scene.meshes[index];
  14364. if (abstractMesh instanceof BABYLON.Mesh) {
  14365. var mesh = abstractMesh;
  14366. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  14367. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  14368. }
  14369. }
  14370. }
  14371. serializationObject.particleSystems = [];
  14372. for (index = 0; index < scene.particleSystems.length; index++) {
  14373. serializationObject.particleSystems.push(serializeParticleSystem(scene.particleSystems[index]));
  14374. }
  14375. serializationObject.lensFlareSystems = [];
  14376. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  14377. serializationObject.lensFlareSystems.push(serializeLensFlareSystem(scene.lensFlareSystems[index]));
  14378. }
  14379. serializationObject.shadowGenerators = [];
  14380. for (index = 0; index < scene.lights.length; index++) {
  14381. light = scene.lights[index];
  14382. if (light.getShadowGenerator()) {
  14383. serializationObject.shadowGenerators.push(serializeShadowGenerator(light));
  14384. }
  14385. }
  14386. return serializationObject;
  14387. };
  14388. return SceneSerializer;
  14389. })();
  14390. BABYLON.SceneSerializer = SceneSerializer;
  14391. })(BABYLON || (BABYLON = {}));
  14392. var BABYLON;
  14393. (function (BABYLON) {
  14394. var SceneLoader = (function () {
  14395. function SceneLoader() {
  14396. }
  14397. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  14398. get: function () {
  14399. return SceneLoader._ForceFullSceneLoadingForIncremental;
  14400. },
  14401. set: function (value) {
  14402. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  14403. },
  14404. enumerable: true,
  14405. configurable: true
  14406. });
  14407. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  14408. get: function () {
  14409. return SceneLoader._ShowLoadingScreen;
  14410. },
  14411. set: function (value) {
  14412. SceneLoader._ShowLoadingScreen = value;
  14413. },
  14414. enumerable: true,
  14415. configurable: true
  14416. });
  14417. SceneLoader._getPluginForFilename = function (sceneFilename) {
  14418. var dotPosition = sceneFilename.lastIndexOf(".");
  14419. var extension = sceneFilename.substring(dotPosition).toLowerCase();
  14420. for (var index = 0; index < this._registeredPlugins.length; index++) {
  14421. var plugin = this._registeredPlugins[index];
  14422. if (plugin.extensions.indexOf(extension) !== -1) {
  14423. return plugin;
  14424. }
  14425. }
  14426. return this._registeredPlugins[this._registeredPlugins.length - 1];
  14427. };
  14428. SceneLoader.RegisterPlugin = function (plugin) {
  14429. plugin.extensions = plugin.extensions.toLowerCase();
  14430. SceneLoader._registeredPlugins.push(plugin);
  14431. };
  14432. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  14433. var _this = this;
  14434. var manifestChecked = function (success) {
  14435. scene.database = database;
  14436. var plugin = _this._getPluginForFilename(sceneFilename);
  14437. var importMeshFromData = function (data) {
  14438. var meshes = [];
  14439. var particleSystems = [];
  14440. var skeletons = [];
  14441. try {
  14442. if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  14443. if (onerror) {
  14444. onerror(scene);
  14445. }
  14446. return;
  14447. }
  14448. } catch (e) {
  14449. if (onerror) {
  14450. onerror(scene);
  14451. }
  14452. return;
  14453. }
  14454. if (onsuccess) {
  14455. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  14456. onsuccess(meshes, particleSystems, skeletons);
  14457. }
  14458. };
  14459. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  14460. importMeshFromData(sceneFilename.substr(5));
  14461. return;
  14462. }
  14463. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  14464. importMeshFromData(data);
  14465. }, progressCallBack, database);
  14466. };
  14467. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  14468. };
  14469. /**
  14470. * Load a scene
  14471. * @param rootUrl a string that defines the root url for scene and resources
  14472. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  14473. * @param engine is the instance of BABYLON.Engine to use to create the scene
  14474. */
  14475. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  14476. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  14477. };
  14478. /**
  14479. * Append a scene
  14480. * @param rootUrl a string that defines the root url for scene and resources
  14481. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  14482. * @param scene is the instance of BABYLON.Scene to append to
  14483. */
  14484. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  14485. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  14486. var database;
  14487. if (SceneLoader.ShowLoadingScreen) {
  14488. scene.getEngine().displayLoadingUI();
  14489. }
  14490. var loadSceneFromData = function (data) {
  14491. scene.database = database;
  14492. if (!plugin.load(scene, data, rootUrl)) {
  14493. if (onerror) {
  14494. onerror(scene);
  14495. }
  14496. scene.getEngine().hideLoadingUI();
  14497. return;
  14498. }
  14499. if (onsuccess) {
  14500. onsuccess(scene);
  14501. }
  14502. if (SceneLoader.ShowLoadingScreen) {
  14503. scene.executeWhenReady(function () {
  14504. scene.getEngine().hideLoadingUI();
  14505. });
  14506. }
  14507. };
  14508. var manifestChecked = function (success) {
  14509. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  14510. };
  14511. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  14512. loadSceneFromData(sceneFilename.substr(5));
  14513. return;
  14514. }
  14515. if (rootUrl.indexOf("file:") === -1) {
  14516. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  14517. } else {
  14518. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  14519. }
  14520. };
  14521. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  14522. SceneLoader._ShowLoadingScreen = true;
  14523. SceneLoader._registeredPlugins = new Array();
  14524. return SceneLoader;
  14525. })();
  14526. BABYLON.SceneLoader = SceneLoader;
  14527. ;
  14528. })(BABYLON || (BABYLON = {}));
  14529. var BABYLON;
  14530. (function (BABYLON) {
  14531. (function (Internals) {
  14532. var loadCubeTexture = function (rootUrl, parsedTexture, scene) {
  14533. var texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene);
  14534. texture.name = parsedTexture.name;
  14535. texture.hasAlpha = parsedTexture.hasAlpha;
  14536. texture.level = parsedTexture.level;
  14537. texture.coordinatesMode = parsedTexture.coordinatesMode;
  14538. return texture;
  14539. };
  14540. var loadTexture = function (rootUrl, parsedTexture, scene) {
  14541. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  14542. return null;
  14543. }
  14544. if (parsedTexture.isCube) {
  14545. return loadCubeTexture(rootUrl, parsedTexture, scene);
  14546. }
  14547. var texture;
  14548. if (parsedTexture.mirrorPlane) {
  14549. texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  14550. texture._waitingRenderList = parsedTexture.renderList;
  14551. texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  14552. } else if (parsedTexture.isRenderTarget) {
  14553. texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  14554. texture._waitingRenderList = parsedTexture.renderList;
  14555. } else {
  14556. texture = new BABYLON.Texture(rootUrl + parsedTexture.name, scene);
  14557. }
  14558. texture.name = parsedTexture.name;
  14559. texture.hasAlpha = parsedTexture.hasAlpha;
  14560. texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
  14561. texture.level = parsedTexture.level;
  14562. texture.coordinatesIndex = parsedTexture.coordinatesIndex;
  14563. texture.coordinatesMode = parsedTexture.coordinatesMode;
  14564. texture.uOffset = parsedTexture.uOffset;
  14565. texture.vOffset = parsedTexture.vOffset;
  14566. texture.uScale = parsedTexture.uScale;
  14567. texture.vScale = parsedTexture.vScale;
  14568. texture.uAng = parsedTexture.uAng;
  14569. texture.vAng = parsedTexture.vAng;
  14570. texture.wAng = parsedTexture.wAng;
  14571. texture.wrapU = parsedTexture.wrapU;
  14572. texture.wrapV = parsedTexture.wrapV;
  14573. if (parsedTexture.animations) {
  14574. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  14575. var parsedAnimation = parsedTexture.animations[animationIndex];
  14576. texture.animations.push(parseAnimation(parsedAnimation));
  14577. }
  14578. }
  14579. return texture;
  14580. };
  14581. var parseSkeleton = function (parsedSkeleton, scene) {
  14582. var skeleton = new BABYLON.Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  14583. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  14584. var parsedBone = parsedSkeleton.bones[index];
  14585. var parentBone = null;
  14586. if (parsedBone.parentBoneIndex > -1) {
  14587. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  14588. }
  14589. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix));
  14590. if (parsedBone.animation) {
  14591. bone.animations.push(parseAnimation(parsedBone.animation));
  14592. }
  14593. }
  14594. return skeleton;
  14595. };
  14596. var parseFresnelParameters = function (parsedFresnelParameters) {
  14597. var fresnelParameters = new BABYLON.FresnelParameters();
  14598. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  14599. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  14600. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  14601. fresnelParameters.bias = parsedFresnelParameters.bias;
  14602. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  14603. return fresnelParameters;
  14604. };
  14605. var parseMaterial = function (parsedMaterial, scene, rootUrl) {
  14606. var material;
  14607. material = new BABYLON.StandardMaterial(parsedMaterial.name, scene);
  14608. material.ambientColor = BABYLON.Color3.FromArray(parsedMaterial.ambient);
  14609. material.diffuseColor = BABYLON.Color3.FromArray(parsedMaterial.diffuse);
  14610. material.specularColor = BABYLON.Color3.FromArray(parsedMaterial.specular);
  14611. material.specularPower = parsedMaterial.specularPower;
  14612. material.emissiveColor = BABYLON.Color3.FromArray(parsedMaterial.emissive);
  14613. material.alpha = parsedMaterial.alpha;
  14614. material.id = parsedMaterial.id;
  14615. BABYLON.Tags.AddTagsTo(material, parsedMaterial.tags);
  14616. material.backFaceCulling = parsedMaterial.backFaceCulling;
  14617. material.wireframe = parsedMaterial.wireframe;
  14618. if (parsedMaterial.diffuseTexture) {
  14619. material.diffuseTexture = loadTexture(rootUrl, parsedMaterial.diffuseTexture, scene);
  14620. }
  14621. if (parsedMaterial.diffuseFresnelParameters) {
  14622. material.diffuseFresnelParameters = parseFresnelParameters(parsedMaterial.diffuseFresnelParameters);
  14623. }
  14624. if (parsedMaterial.ambientTexture) {
  14625. material.ambientTexture = loadTexture(rootUrl, parsedMaterial.ambientTexture, scene);
  14626. }
  14627. if (parsedMaterial.opacityTexture) {
  14628. material.opacityTexture = loadTexture(rootUrl, parsedMaterial.opacityTexture, scene);
  14629. }
  14630. if (parsedMaterial.opacityFresnelParameters) {
  14631. material.opacityFresnelParameters = parseFresnelParameters(parsedMaterial.opacityFresnelParameters);
  14632. }
  14633. if (parsedMaterial.reflectionTexture) {
  14634. material.reflectionTexture = loadTexture(rootUrl, parsedMaterial.reflectionTexture, scene);
  14635. }
  14636. if (parsedMaterial.reflectionFresnelParameters) {
  14637. material.reflectionFresnelParameters = parseFresnelParameters(parsedMaterial.reflectionFresnelParameters);
  14638. }
  14639. if (parsedMaterial.emissiveTexture) {
  14640. material.emissiveTexture = loadTexture(rootUrl, parsedMaterial.emissiveTexture, scene);
  14641. }
  14642. if (parsedMaterial.emissiveFresnelParameters) {
  14643. material.emissiveFresnelParameters = parseFresnelParameters(parsedMaterial.emissiveFresnelParameters);
  14644. }
  14645. if (parsedMaterial.specularTexture) {
  14646. material.specularTexture = loadTexture(rootUrl, parsedMaterial.specularTexture, scene);
  14647. }
  14648. if (parsedMaterial.bumpTexture) {
  14649. material.bumpTexture = loadTexture(rootUrl, parsedMaterial.bumpTexture, scene);
  14650. }
  14651. return material;
  14652. };
  14653. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  14654. for (var index = 0; index < parsedData.materials.length; index++) {
  14655. var parsedMaterial = parsedData.materials[index];
  14656. if (parsedMaterial.id === id) {
  14657. return parseMaterial(parsedMaterial, scene, rootUrl);
  14658. }
  14659. }
  14660. return null;
  14661. };
  14662. var parseMultiMaterial = function (parsedMultiMaterial, scene) {
  14663. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  14664. multiMaterial.id = parsedMultiMaterial.id;
  14665. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  14666. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  14667. var subMatId = parsedMultiMaterial.materials[matIndex];
  14668. if (subMatId) {
  14669. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  14670. } else {
  14671. multiMaterial.subMaterials.push(null);
  14672. }
  14673. }
  14674. return multiMaterial;
  14675. };
  14676. var parseLensFlareSystem = function (parsedLensFlareSystem, scene, rootUrl) {
  14677. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  14678. var lensFlareSystem = new BABYLON.LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  14679. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  14680. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  14681. var parsedFlare = parsedLensFlareSystem.flares[index];
  14682. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  14683. }
  14684. return lensFlareSystem;
  14685. };
  14686. var parseParticleSystem = function (parsedParticleSystem, scene, rootUrl) {
  14687. var emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  14688. var particleSystem = new BABYLON.ParticleSystem("particles#" + emitter.name, parsedParticleSystem.capacity, scene);
  14689. if (parsedParticleSystem.textureName) {
  14690. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  14691. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  14692. }
  14693. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  14694. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  14695. particleSystem.minSize = parsedParticleSystem.minSize;
  14696. particleSystem.maxSize = parsedParticleSystem.maxSize;
  14697. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  14698. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  14699. particleSystem.emitter = emitter;
  14700. particleSystem.emitRate = parsedParticleSystem.emitRate;
  14701. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  14702. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  14703. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  14704. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  14705. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  14706. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  14707. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  14708. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  14709. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  14710. particleSystem.targetStopDuration = parsedParticleSystem.targetStopFrame;
  14711. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  14712. particleSystem.blendMode = parsedParticleSystem.blendMode;
  14713. particleSystem.start();
  14714. return particleSystem;
  14715. };
  14716. var parseShadowGenerator = function (parsedShadowGenerator, scene) {
  14717. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  14718. var shadowGenerator = new BABYLON.ShadowGenerator(parsedShadowGenerator.mapSize, light);
  14719. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  14720. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  14721. shadowGenerator.getShadowMap().renderList.push(mesh);
  14722. }
  14723. if (parsedShadowGenerator.usePoissonSampling) {
  14724. shadowGenerator.usePoissonSampling = true;
  14725. } else {
  14726. shadowGenerator.useVarianceShadowMap = parsedShadowGenerator.useVarianceShadowMap;
  14727. }
  14728. return shadowGenerator;
  14729. };
  14730. var parseAnimation = function (parsedAnimation) {
  14731. var animation = new BABYLON.Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  14732. var dataType = parsedAnimation.dataType;
  14733. var keys = [];
  14734. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  14735. var key = parsedAnimation.keys[index];
  14736. var data;
  14737. switch (dataType) {
  14738. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  14739. data = key.values[0];
  14740. break;
  14741. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  14742. data = BABYLON.Quaternion.FromArray(key.values);
  14743. break;
  14744. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  14745. data = BABYLON.Matrix.FromArray(key.values);
  14746. break;
  14747. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  14748. default:
  14749. data = BABYLON.Vector3.FromArray(key.values);
  14750. break;
  14751. }
  14752. keys.push({
  14753. frame: key.frame,
  14754. value: data
  14755. });
  14756. }
  14757. animation.setKeys(keys);
  14758. return animation;
  14759. };
  14760. var parseLight = function (parsedLight, scene) {
  14761. var light;
  14762. switch (parsedLight.type) {
  14763. case 0:
  14764. light = new BABYLON.PointLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), scene);
  14765. break;
  14766. case 1:
  14767. light = new BABYLON.DirectionalLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  14768. light.position = BABYLON.Vector3.FromArray(parsedLight.position);
  14769. break;
  14770. case 2:
  14771. light = new BABYLON.SpotLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), BABYLON.Vector3.FromArray(parsedLight.direction), parsedLight.angle, parsedLight.exponent, scene);
  14772. break;
  14773. case 3:
  14774. light = new BABYLON.HemisphericLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  14775. light.groundColor = BABYLON.Color3.FromArray(parsedLight.groundColor);
  14776. break;
  14777. }
  14778. light.id = parsedLight.id;
  14779. BABYLON.Tags.AddTagsTo(light, parsedLight.tags);
  14780. if (parsedLight.intensity !== undefined) {
  14781. light.intensity = parsedLight.intensity;
  14782. }
  14783. if (parsedLight.range) {
  14784. light.range = parsedLight.range;
  14785. }
  14786. light.diffuse = BABYLON.Color3.FromArray(parsedLight.diffuse);
  14787. light.specular = BABYLON.Color3.FromArray(parsedLight.specular);
  14788. if (parsedLight.excludedMeshesIds) {
  14789. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  14790. }
  14791. if (parsedLight.includedOnlyMeshesIds) {
  14792. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  14793. }
  14794. if (parsedLight.animations) {
  14795. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  14796. var parsedAnimation = parsedLight.animations[animationIndex];
  14797. light.animations.push(parseAnimation(parsedAnimation));
  14798. }
  14799. }
  14800. if (parsedLight.autoAnimate) {
  14801. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, 1.0);
  14802. }
  14803. };
  14804. var parseCamera = function (parsedCamera, scene) {
  14805. var camera;
  14806. var position = BABYLON.Vector3.FromArray(parsedCamera.position);
  14807. var lockedTargetMesh = (parsedCamera.lockedTargetId) ? scene.getLastMeshByID(parsedCamera.lockedTargetId) : null;
  14808. if (parsedCamera.type === "AnaglyphArcRotateCamera" || parsedCamera.type === "ArcRotateCamera") {
  14809. var alpha = parsedCamera.alpha;
  14810. var beta = parsedCamera.beta;
  14811. var radius = parsedCamera.radius;
  14812. if (parsedCamera.type === "AnaglyphArcRotateCamera") {
  14813. var eye_space = parsedCamera.eye_space;
  14814. camera = new BABYLON.AnaglyphArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, eye_space, scene);
  14815. } else {
  14816. camera = new BABYLON.ArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, scene);
  14817. }
  14818. } else if (parsedCamera.type === "AnaglyphFreeCamera") {
  14819. var eye_space = parsedCamera.eye_space;
  14820. camera = new BABYLON.AnaglyphFreeCamera(parsedCamera.name, position, eye_space, scene);
  14821. } else if (parsedCamera.type === "DeviceOrientationCamera") {
  14822. camera = new BABYLON.DeviceOrientationCamera(parsedCamera.name, position, scene);
  14823. } else if (parsedCamera.type === "FollowCamera") {
  14824. camera = new BABYLON.FollowCamera(parsedCamera.name, position, scene);
  14825. camera.heightOffset = parsedCamera.heightOffset;
  14826. camera.radius = parsedCamera.radius;
  14827. camera.rotationOffset = parsedCamera.rotationOffset;
  14828. if (lockedTargetMesh)
  14829. camera.target = lockedTargetMesh;
  14830. } else if (parsedCamera.type === "GamepadCamera") {
  14831. camera = new BABYLON.GamepadCamera(parsedCamera.name, position, scene);
  14832. } else if (parsedCamera.type === "OculusCamera") {
  14833. camera = new BABYLON.OculusCamera(parsedCamera.name, position, scene);
  14834. } else if (parsedCamera.type === "TouchCamera") {
  14835. camera = new BABYLON.TouchCamera(parsedCamera.name, position, scene);
  14836. } else if (parsedCamera.type === "VirtualJoysticksCamera") {
  14837. camera = new BABYLON.VirtualJoysticksCamera(parsedCamera.name, position, scene);
  14838. } else if (parsedCamera.type === "WebVRCamera") {
  14839. camera = new BABYLON.WebVRCamera(parsedCamera.name, position, scene);
  14840. } else if (parsedCamera.type === "VRDeviceOrientationCamera") {
  14841. camera = new BABYLON.VRDeviceOrientationCamera(parsedCamera.name, position, scene);
  14842. } else {
  14843. camera = new BABYLON.FreeCamera(parsedCamera.name, position, scene);
  14844. }
  14845. if (lockedTargetMesh && camera instanceof BABYLON.FreeCamera) {
  14846. camera.lockedTarget = lockedTargetMesh;
  14847. }
  14848. camera.id = parsedCamera.id;
  14849. BABYLON.Tags.AddTagsTo(camera, parsedCamera.tags);
  14850. if (parsedCamera.parentId) {
  14851. camera._waitingParentId = parsedCamera.parentId;
  14852. }
  14853. if (parsedCamera.target) {
  14854. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  14855. } else {
  14856. camera.rotation = BABYLON.Vector3.FromArray(parsedCamera.rotation);
  14857. }
  14858. camera.fov = parsedCamera.fov;
  14859. camera.minZ = parsedCamera.minZ;
  14860. camera.maxZ = parsedCamera.maxZ;
  14861. camera.speed = parsedCamera.speed;
  14862. camera.inertia = parsedCamera.inertia;
  14863. camera.checkCollisions = parsedCamera.checkCollisions;
  14864. camera.applyGravity = parsedCamera.applyGravity;
  14865. if (parsedCamera.ellipsoid) {
  14866. camera.ellipsoid = BABYLON.Vector3.FromArray(parsedCamera.ellipsoid);
  14867. }
  14868. if (parsedCamera.animations) {
  14869. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  14870. var parsedAnimation = parsedCamera.animations[animationIndex];
  14871. camera.animations.push(parseAnimation(parsedAnimation));
  14872. }
  14873. }
  14874. if (parsedCamera.autoAnimate) {
  14875. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, 1.0);
  14876. }
  14877. if (parsedCamera.layerMask && (!isNaN(parsedCamera.layerMask))) {
  14878. camera.layerMask = Math.abs(parseInt(parsedCamera.layerMask));
  14879. } else {
  14880. camera.layerMask = 0xFFFFFFFF;
  14881. }
  14882. return camera;
  14883. };
  14884. var parseGeometry = function (parsedGeometry, scene) {
  14885. var id = parsedGeometry.id;
  14886. return scene.getGeometryByID(id);
  14887. };
  14888. var parseBox = function (parsedBox, scene) {
  14889. if (parseGeometry(parsedBox, scene)) {
  14890. return null;
  14891. }
  14892. var box = new BABYLON.Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  14893. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  14894. scene.pushGeometry(box, true);
  14895. return box;
  14896. };
  14897. var parseSphere = function (parsedSphere, scene) {
  14898. if (parseGeometry(parsedSphere, scene)) {
  14899. return null;
  14900. }
  14901. var sphere = new BABYLON.Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  14902. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  14903. scene.pushGeometry(sphere, true);
  14904. return sphere;
  14905. };
  14906. var parseCylinder = function (parsedCylinder, scene) {
  14907. if (parseGeometry(parsedCylinder, scene)) {
  14908. return null;
  14909. }
  14910. var cylinder = new BABYLON.Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  14911. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  14912. scene.pushGeometry(cylinder, true);
  14913. return cylinder;
  14914. };
  14915. var parseTorus = function (parsedTorus, scene) {
  14916. if (parseGeometry(parsedTorus, scene)) {
  14917. return null;
  14918. }
  14919. var torus = new BABYLON.Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  14920. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  14921. scene.pushGeometry(torus, true);
  14922. return torus;
  14923. };
  14924. var parseGround = function (parsedGround, scene) {
  14925. if (parseGeometry(parsedGround, scene)) {
  14926. return null;
  14927. }
  14928. var ground = new BABYLON.Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  14929. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  14930. scene.pushGeometry(ground, true);
  14931. return ground;
  14932. };
  14933. var parsePlane = function (parsedPlane, scene) {
  14934. if (parseGeometry(parsedPlane, scene)) {
  14935. return null;
  14936. }
  14937. var plane = new BABYLON.Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  14938. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  14939. scene.pushGeometry(plane, true);
  14940. return plane;
  14941. };
  14942. var parseTorusKnot = function (parsedTorusKnot, scene) {
  14943. if (parseGeometry(parsedTorusKnot, scene)) {
  14944. return null;
  14945. }
  14946. 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);
  14947. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  14948. scene.pushGeometry(torusKnot, true);
  14949. return torusKnot;
  14950. };
  14951. var parseVertexData = function (parsedVertexData, scene, rootUrl) {
  14952. if (parseGeometry(parsedVertexData, scene)) {
  14953. return null;
  14954. }
  14955. var geometry = new BABYLON.Geometry(parsedVertexData.id, scene);
  14956. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  14957. if (parsedVertexData.delayLoadingFile) {
  14958. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  14959. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  14960. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  14961. geometry._delayInfo = [];
  14962. if (parsedVertexData.hasUVs) {
  14963. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  14964. }
  14965. if (parsedVertexData.hasUVs2) {
  14966. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  14967. }
  14968. if (parsedVertexData.hasColors) {
  14969. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  14970. }
  14971. if (parsedVertexData.hasMatricesIndices) {
  14972. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  14973. }
  14974. if (parsedVertexData.hasMatricesWeights) {
  14975. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  14976. }
  14977. geometry._delayLoadingFunction = importVertexData;
  14978. } else {
  14979. importVertexData(parsedVertexData, geometry);
  14980. }
  14981. scene.pushGeometry(geometry, true);
  14982. return geometry;
  14983. };
  14984. var parseMesh = function (parsedMesh, scene, rootUrl) {
  14985. var mesh = new BABYLON.Mesh(parsedMesh.name, scene);
  14986. mesh.id = parsedMesh.id;
  14987. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  14988. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  14989. if (parsedMesh.rotationQuaternion) {
  14990. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  14991. } else if (parsedMesh.rotation) {
  14992. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  14993. }
  14994. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  14995. if (parsedMesh.localMatrix) {
  14996. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  14997. } else if (parsedMesh.pivotMatrix) {
  14998. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  14999. }
  15000. mesh.setEnabled(parsedMesh.isEnabled);
  15001. mesh.isVisible = parsedMesh.isVisible;
  15002. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  15003. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  15004. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  15005. if (parsedMesh.pickable !== undefined) {
  15006. mesh.isPickable = parsedMesh.pickable;
  15007. }
  15008. mesh.receiveShadows = parsedMesh.receiveShadows;
  15009. mesh.billboardMode = parsedMesh.billboardMode;
  15010. if (parsedMesh.visibility !== undefined) {
  15011. mesh.visibility = parsedMesh.visibility;
  15012. }
  15013. mesh.checkCollisions = parsedMesh.checkCollisions;
  15014. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  15015. if (parsedMesh.parentId) {
  15016. mesh._waitingParentId = parsedMesh.parentId;
  15017. }
  15018. if (parsedMesh.delayLoadingFile) {
  15019. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  15020. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  15021. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  15022. if (parsedMesh._binaryInfo) {
  15023. mesh._binaryInfo = parsedMesh._binaryInfo;
  15024. }
  15025. mesh._delayInfo = [];
  15026. if (parsedMesh.hasUVs) {
  15027. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  15028. }
  15029. if (parsedMesh.hasUVs2) {
  15030. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  15031. }
  15032. if (parsedMesh.hasColors) {
  15033. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  15034. }
  15035. if (parsedMesh.hasMatricesIndices) {
  15036. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  15037. }
  15038. if (parsedMesh.hasMatricesWeights) {
  15039. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  15040. }
  15041. mesh._delayLoadingFunction = importGeometry;
  15042. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  15043. mesh._checkDelayState();
  15044. }
  15045. } else {
  15046. importGeometry(parsedMesh, mesh);
  15047. }
  15048. if (parsedMesh.materialId) {
  15049. mesh.setMaterialByID(parsedMesh.materialId);
  15050. } else {
  15051. mesh.material = null;
  15052. }
  15053. if (parsedMesh.skeletonId > -1) {
  15054. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  15055. }
  15056. if (parsedMesh.physicsImpostor) {
  15057. if (!scene.isPhysicsEnabled()) {
  15058. scene.enablePhysics();
  15059. }
  15060. mesh.setPhysicsState({ impostor: parsedMesh.physicsImpostor, mass: parsedMesh.physicsMass, friction: parsedMesh.physicsFriction, restitution: parsedMesh.physicsRestitution });
  15061. }
  15062. if (parsedMesh.animations) {
  15063. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  15064. var parsedAnimation = parsedMesh.animations[animationIndex];
  15065. mesh.animations.push(parseAnimation(parsedAnimation));
  15066. }
  15067. }
  15068. if (parsedMesh.autoAnimate) {
  15069. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, 1.0);
  15070. }
  15071. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  15072. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  15073. } else {
  15074. mesh.layerMask = 0xFFFFFFFF;
  15075. }
  15076. if (parsedMesh.instances) {
  15077. for (var index = 0; index < parsedMesh.instances.length; index++) {
  15078. var parsedInstance = parsedMesh.instances[index];
  15079. var instance = mesh.createInstance(parsedInstance.name);
  15080. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  15081. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  15082. if (parsedInstance.rotationQuaternion) {
  15083. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  15084. } else if (parsedInstance.rotation) {
  15085. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  15086. }
  15087. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  15088. instance.checkCollisions = mesh.checkCollisions;
  15089. if (parsedMesh.animations) {
  15090. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  15091. parsedAnimation = parsedMesh.animations[animationIndex];
  15092. instance.animations.push(parseAnimation(parsedAnimation));
  15093. }
  15094. }
  15095. }
  15096. }
  15097. return mesh;
  15098. };
  15099. var isDescendantOf = function (mesh, names, hierarchyIds) {
  15100. names = (names instanceof Array) ? names : [names];
  15101. for (var i in names) {
  15102. if (mesh.name === names[i]) {
  15103. hierarchyIds.push(mesh.id);
  15104. return true;
  15105. }
  15106. }
  15107. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  15108. hierarchyIds.push(mesh.id);
  15109. return true;
  15110. }
  15111. return false;
  15112. };
  15113. var importVertexData = function (parsedVertexData, geometry) {
  15114. var vertexData = new BABYLON.VertexData();
  15115. var positions = parsedVertexData.positions;
  15116. if (positions) {
  15117. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  15118. }
  15119. var normals = parsedVertexData.normals;
  15120. if (normals) {
  15121. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  15122. }
  15123. var uvs = parsedVertexData.uvs;
  15124. if (uvs) {
  15125. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  15126. }
  15127. var uv2s = parsedVertexData.uv2s;
  15128. if (uv2s) {
  15129. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  15130. }
  15131. var colors = parsedVertexData.colors;
  15132. if (colors) {
  15133. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  15134. }
  15135. var matricesIndices = parsedVertexData.matricesIndices;
  15136. if (matricesIndices) {
  15137. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  15138. }
  15139. var matricesWeights = parsedVertexData.matricesWeights;
  15140. if (matricesWeights) {
  15141. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  15142. }
  15143. var indices = parsedVertexData.indices;
  15144. if (indices) {
  15145. vertexData.indices = indices;
  15146. }
  15147. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  15148. };
  15149. var importGeometry = function (parsedGeometry, mesh) {
  15150. var scene = mesh.getScene();
  15151. var geometryId = parsedGeometry.geometryId;
  15152. if (geometryId) {
  15153. var geometry = scene.getGeometryByID(geometryId);
  15154. if (geometry) {
  15155. geometry.applyToMesh(mesh);
  15156. }
  15157. } else if (parsedGeometry instanceof ArrayBuffer) {
  15158. var binaryInfo = mesh._binaryInfo;
  15159. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  15160. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  15161. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  15162. }
  15163. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  15164. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  15165. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  15166. }
  15167. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  15168. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  15169. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  15170. }
  15171. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  15172. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  15173. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  15174. }
  15175. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  15176. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  15177. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false);
  15178. }
  15179. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  15180. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  15181. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  15182. }
  15183. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  15184. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  15185. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  15186. }
  15187. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  15188. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  15189. mesh.setIndices(indicesData);
  15190. }
  15191. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  15192. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  15193. mesh.subMeshes = [];
  15194. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  15195. var materialIndex = subMeshesData[(i * 5) + 0];
  15196. var verticesStart = subMeshesData[(i * 5) + 1];
  15197. var verticesCount = subMeshesData[(i * 5) + 2];
  15198. var indexStart = subMeshesData[(i * 5) + 3];
  15199. var indexCount = subMeshesData[(i * 5) + 4];
  15200. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  15201. }
  15202. }
  15203. return;
  15204. } else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  15205. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  15206. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  15207. if (parsedGeometry.uvs) {
  15208. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  15209. }
  15210. if (parsedGeometry.uvs2) {
  15211. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  15212. }
  15213. if (parsedGeometry.colors) {
  15214. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, parsedGeometry.colors, false);
  15215. }
  15216. if (parsedGeometry.matricesIndices) {
  15217. if (!parsedGeometry.matricesIndices._isExpanded) {
  15218. var floatIndices = [];
  15219. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  15220. var matricesIndex = parsedGeometry.matricesIndices[i];
  15221. floatIndices.push(matricesIndex & 0x000000FF);
  15222. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  15223. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  15224. floatIndices.push(matricesIndex >> 24);
  15225. }
  15226. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  15227. } else {
  15228. delete parsedGeometry.matricesIndices._isExpanded;
  15229. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  15230. }
  15231. }
  15232. if (parsedGeometry.matricesWeights) {
  15233. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  15234. }
  15235. mesh.setIndices(parsedGeometry.indices);
  15236. }
  15237. if (parsedGeometry.subMeshes) {
  15238. mesh.subMeshes = [];
  15239. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  15240. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  15241. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  15242. }
  15243. }
  15244. if (mesh._shouldGenerateFlatShading) {
  15245. mesh.convertToFlatShadedMesh();
  15246. delete mesh._shouldGenerateFlatShading;
  15247. }
  15248. mesh.computeWorldMatrix(true);
  15249. if (scene._selectionOctree) {
  15250. scene._selectionOctree.addMesh(mesh);
  15251. }
  15252. };
  15253. BABYLON.SceneLoader.RegisterPlugin({
  15254. extensions: ".babylon",
  15255. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  15256. var parsedData = JSON.parse(data);
  15257. var loadedSkeletonsIds = [];
  15258. var loadedMaterialsIds = [];
  15259. var hierarchyIds = [];
  15260. for (var index = 0; index < parsedData.meshes.length; index++) {
  15261. var parsedMesh = parsedData.meshes[index];
  15262. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  15263. if (meshesNames instanceof Array) {
  15264. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  15265. }
  15266. if (parsedMesh.materialId) {
  15267. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  15268. if (!materialFound) {
  15269. for (var multimatIndex = 0; multimatIndex < parsedData.multiMaterials.length; multimatIndex++) {
  15270. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  15271. if (parsedMultiMaterial.id == parsedMesh.materialId) {
  15272. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  15273. var subMatId = parsedMultiMaterial.materials[matIndex];
  15274. loadedMaterialsIds.push(subMatId);
  15275. parseMaterialById(subMatId, parsedData, scene, rootUrl);
  15276. }
  15277. loadedMaterialsIds.push(parsedMultiMaterial.id);
  15278. parseMultiMaterial(parsedMultiMaterial, scene);
  15279. materialFound = true;
  15280. break;
  15281. }
  15282. }
  15283. }
  15284. if (!materialFound) {
  15285. loadedMaterialsIds.push(parsedMesh.materialId);
  15286. parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  15287. }
  15288. }
  15289. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  15290. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  15291. if (!skeletonAlreadyLoaded) {
  15292. for (var skeletonIndex = 0; skeletonIndex < parsedData.skeletons.length; skeletonIndex++) {
  15293. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  15294. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  15295. skeletons.push(parseSkeleton(parsedSkeleton, scene));
  15296. loadedSkeletonsIds.push(parsedSkeleton.id);
  15297. }
  15298. }
  15299. }
  15300. }
  15301. var mesh = parseMesh(parsedMesh, scene, rootUrl);
  15302. meshes.push(mesh);
  15303. }
  15304. }
  15305. for (index = 0; index < scene.meshes.length; index++) {
  15306. var currentMesh = scene.meshes[index];
  15307. if (currentMesh._waitingParentId) {
  15308. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  15309. currentMesh._waitingParentId = undefined;
  15310. }
  15311. }
  15312. if (parsedData.particleSystems) {
  15313. for (index = 0; index < parsedData.particleSystems.length; index++) {
  15314. var parsedParticleSystem = parsedData.particleSystems[index];
  15315. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  15316. particleSystems.push(parseParticleSystem(parsedParticleSystem, scene, rootUrl));
  15317. }
  15318. }
  15319. }
  15320. return true;
  15321. },
  15322. load: function (scene, data, rootUrl) {
  15323. var parsedData = JSON.parse(data);
  15324. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  15325. scene.autoClear = parsedData.autoClear;
  15326. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  15327. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  15328. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  15329. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  15330. scene.fogMode = parsedData.fogMode;
  15331. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  15332. scene.fogStart = parsedData.fogStart;
  15333. scene.fogEnd = parsedData.fogEnd;
  15334. scene.fogDensity = parsedData.fogDensity;
  15335. }
  15336. for (var index = 0; index < parsedData.lights.length; index++) {
  15337. var parsedLight = parsedData.lights[index];
  15338. parseLight(parsedLight, scene);
  15339. }
  15340. if (parsedData.materials) {
  15341. for (index = 0; index < parsedData.materials.length; index++) {
  15342. var parsedMaterial = parsedData.materials[index];
  15343. parseMaterial(parsedMaterial, scene, rootUrl);
  15344. }
  15345. }
  15346. if (parsedData.multiMaterials) {
  15347. for (index = 0; index < parsedData.multiMaterials.length; index++) {
  15348. var parsedMultiMaterial = parsedData.multiMaterials[index];
  15349. parseMultiMaterial(parsedMultiMaterial, scene);
  15350. }
  15351. }
  15352. if (parsedData.skeletons) {
  15353. for (index = 0; index < parsedData.skeletons.length; index++) {
  15354. var parsedSkeleton = parsedData.skeletons[index];
  15355. parseSkeleton(parsedSkeleton, scene);
  15356. }
  15357. }
  15358. var geometries = parsedData.geometries;
  15359. if (geometries) {
  15360. var boxes = geometries.boxes;
  15361. if (boxes) {
  15362. for (index = 0; index < boxes.length; index++) {
  15363. var parsedBox = boxes[index];
  15364. parseBox(parsedBox, scene);
  15365. }
  15366. }
  15367. var spheres = geometries.spheres;
  15368. if (spheres) {
  15369. for (index = 0; index < spheres.length; index++) {
  15370. var parsedSphere = spheres[index];
  15371. parseSphere(parsedSphere, scene);
  15372. }
  15373. }
  15374. var cylinders = geometries.cylinders;
  15375. if (cylinders) {
  15376. for (index = 0; index < cylinders.length; index++) {
  15377. var parsedCylinder = cylinders[index];
  15378. parseCylinder(parsedCylinder, scene);
  15379. }
  15380. }
  15381. var toruses = geometries.toruses;
  15382. if (toruses) {
  15383. for (index = 0; index < toruses.length; index++) {
  15384. var parsedTorus = toruses[index];
  15385. parseTorus(parsedTorus, scene);
  15386. }
  15387. }
  15388. var grounds = geometries.grounds;
  15389. if (grounds) {
  15390. for (index = 0; index < grounds.length; index++) {
  15391. var parsedGround = grounds[index];
  15392. parseGround(parsedGround, scene);
  15393. }
  15394. }
  15395. var planes = geometries.planes;
  15396. if (planes) {
  15397. for (index = 0; index < planes.length; index++) {
  15398. var parsedPlane = planes[index];
  15399. parsePlane(parsedPlane, scene);
  15400. }
  15401. }
  15402. var torusKnots = geometries.torusKnots;
  15403. if (torusKnots) {
  15404. for (index = 0; index < torusKnots.length; index++) {
  15405. var parsedTorusKnot = torusKnots[index];
  15406. parseTorusKnot(parsedTorusKnot, scene);
  15407. }
  15408. }
  15409. var vertexData = geometries.vertexData;
  15410. if (vertexData) {
  15411. for (index = 0; index < vertexData.length; index++) {
  15412. var parsedVertexData = vertexData[index];
  15413. parseVertexData(parsedVertexData, scene, rootUrl);
  15414. }
  15415. }
  15416. }
  15417. for (index = 0; index < parsedData.meshes.length; index++) {
  15418. var parsedMesh = parsedData.meshes[index];
  15419. parseMesh(parsedMesh, scene, rootUrl);
  15420. }
  15421. for (index = 0; index < parsedData.cameras.length; index++) {
  15422. var parsedCamera = parsedData.cameras[index];
  15423. parseCamera(parsedCamera, scene);
  15424. }
  15425. if (parsedData.activeCameraID) {
  15426. scene.setActiveCameraByID(parsedData.activeCameraID);
  15427. }
  15428. for (index = 0; index < scene.cameras.length; index++) {
  15429. var camera = scene.cameras[index];
  15430. if (camera._waitingParentId) {
  15431. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  15432. camera._waitingParentId = undefined;
  15433. }
  15434. }
  15435. for (index = 0; index < scene.meshes.length; index++) {
  15436. var mesh = scene.meshes[index];
  15437. if (mesh._waitingParentId) {
  15438. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  15439. mesh._waitingParentId = undefined;
  15440. }
  15441. }
  15442. if (parsedData.particleSystems) {
  15443. for (index = 0; index < parsedData.particleSystems.length; index++) {
  15444. var parsedParticleSystem = parsedData.particleSystems[index];
  15445. parseParticleSystem(parsedParticleSystem, scene, rootUrl);
  15446. }
  15447. }
  15448. if (parsedData.lensFlareSystems) {
  15449. for (index = 0; index < parsedData.lensFlareSystems.length; index++) {
  15450. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  15451. parseLensFlareSystem(parsedLensFlareSystem, scene, rootUrl);
  15452. }
  15453. }
  15454. if (parsedData.shadowGenerators) {
  15455. for (index = 0; index < parsedData.shadowGenerators.length; index++) {
  15456. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  15457. parseShadowGenerator(parsedShadowGenerator, scene);
  15458. }
  15459. }
  15460. return true;
  15461. }
  15462. });
  15463. })(BABYLON.Internals || (BABYLON.Internals = {}));
  15464. var Internals = BABYLON.Internals;
  15465. })(BABYLON || (BABYLON = {}));
  15466. var BABYLON;
  15467. (function (BABYLON) {
  15468. var currentCSGMeshId = 0;
  15469. var Vertex = (function () {
  15470. function Vertex(pos, normal, uv) {
  15471. this.pos = pos;
  15472. this.normal = normal;
  15473. this.uv = uv;
  15474. }
  15475. Vertex.prototype.clone = function () {
  15476. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  15477. };
  15478. Vertex.prototype.flip = function () {
  15479. this.normal = this.normal.scale(-1);
  15480. };
  15481. Vertex.prototype.interpolate = function (other, t) {
  15482. 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));
  15483. };
  15484. return Vertex;
  15485. })();
  15486. var Plane = (function () {
  15487. function Plane(normal, w) {
  15488. this.normal = normal;
  15489. this.w = w;
  15490. }
  15491. Plane.FromPoints = function (a, b, c) {
  15492. var v0 = c.subtract(a);
  15493. var v1 = b.subtract(a);
  15494. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  15495. return null;
  15496. }
  15497. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  15498. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  15499. };
  15500. Plane.prototype.clone = function () {
  15501. return new Plane(this.normal.clone(), this.w);
  15502. };
  15503. Plane.prototype.flip = function () {
  15504. this.normal.scaleInPlace(-1);
  15505. this.w = -this.w;
  15506. };
  15507. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  15508. var COPLANAR = 0;
  15509. var FRONT = 1;
  15510. var BACK = 2;
  15511. var SPANNING = 3;
  15512. var polygonType = 0;
  15513. var types = [];
  15514. for (var i = 0; i < polygon.vertices.length; i++) {
  15515. var t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  15516. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  15517. polygonType |= type;
  15518. types.push(type);
  15519. }
  15520. switch (polygonType) {
  15521. case COPLANAR:
  15522. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  15523. break;
  15524. case FRONT:
  15525. front.push(polygon);
  15526. break;
  15527. case BACK:
  15528. back.push(polygon);
  15529. break;
  15530. case SPANNING:
  15531. var f = [], b = [];
  15532. for (i = 0; i < polygon.vertices.length; i++) {
  15533. var j = (i + 1) % polygon.vertices.length;
  15534. var ti = types[i], tj = types[j];
  15535. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  15536. if (ti != BACK)
  15537. f.push(vi);
  15538. if (ti != FRONT)
  15539. b.push(ti != BACK ? vi.clone() : vi);
  15540. if ((ti | tj) == SPANNING) {
  15541. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  15542. var v = vi.interpolate(vj, t);
  15543. f.push(v);
  15544. b.push(v.clone());
  15545. }
  15546. }
  15547. if (f.length >= 3) {
  15548. var poly = new Polygon(f, polygon.shared);
  15549. if (poly.plane)
  15550. front.push(poly);
  15551. }
  15552. if (b.length >= 3) {
  15553. poly = new Polygon(b, polygon.shared);
  15554. if (poly.plane)
  15555. back.push(poly);
  15556. }
  15557. break;
  15558. }
  15559. };
  15560. Plane.EPSILON = 1e-5;
  15561. return Plane;
  15562. })();
  15563. var Polygon = (function () {
  15564. function Polygon(vertices, shared) {
  15565. this.vertices = vertices;
  15566. this.shared = shared;
  15567. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  15568. }
  15569. Polygon.prototype.clone = function () {
  15570. var vertices = this.vertices.map(function (v) {
  15571. return v.clone();
  15572. });
  15573. return new Polygon(vertices, this.shared);
  15574. };
  15575. Polygon.prototype.flip = function () {
  15576. this.vertices.reverse().map(function (v) {
  15577. v.flip();
  15578. });
  15579. this.plane.flip();
  15580. };
  15581. return Polygon;
  15582. })();
  15583. var Node = (function () {
  15584. function Node(polygons) {
  15585. this.plane = null;
  15586. this.front = null;
  15587. this.back = null;
  15588. this.polygons = [];
  15589. if (polygons) {
  15590. this.build(polygons);
  15591. }
  15592. }
  15593. Node.prototype.clone = function () {
  15594. var node = new Node();
  15595. node.plane = this.plane && this.plane.clone();
  15596. node.front = this.front && this.front.clone();
  15597. node.back = this.back && this.back.clone();
  15598. node.polygons = this.polygons.map(function (p) {
  15599. return p.clone();
  15600. });
  15601. return node;
  15602. };
  15603. Node.prototype.invert = function () {
  15604. for (var i = 0; i < this.polygons.length; i++) {
  15605. this.polygons[i].flip();
  15606. }
  15607. if (this.plane) {
  15608. this.plane.flip();
  15609. }
  15610. if (this.front) {
  15611. this.front.invert();
  15612. }
  15613. if (this.back) {
  15614. this.back.invert();
  15615. }
  15616. var temp = this.front;
  15617. this.front = this.back;
  15618. this.back = temp;
  15619. };
  15620. Node.prototype.clipPolygons = function (polygons) {
  15621. if (!this.plane)
  15622. return polygons.slice();
  15623. var front = [], back = [];
  15624. for (var i = 0; i < polygons.length; i++) {
  15625. this.plane.splitPolygon(polygons[i], front, back, front, back);
  15626. }
  15627. if (this.front) {
  15628. front = this.front.clipPolygons(front);
  15629. }
  15630. if (this.back) {
  15631. back = this.back.clipPolygons(back);
  15632. } else {
  15633. back = [];
  15634. }
  15635. return front.concat(back);
  15636. };
  15637. Node.prototype.clipTo = function (bsp) {
  15638. this.polygons = bsp.clipPolygons(this.polygons);
  15639. if (this.front)
  15640. this.front.clipTo(bsp);
  15641. if (this.back)
  15642. this.back.clipTo(bsp);
  15643. };
  15644. Node.prototype.allPolygons = function () {
  15645. var polygons = this.polygons.slice();
  15646. if (this.front)
  15647. polygons = polygons.concat(this.front.allPolygons());
  15648. if (this.back)
  15649. polygons = polygons.concat(this.back.allPolygons());
  15650. return polygons;
  15651. };
  15652. Node.prototype.build = function (polygons) {
  15653. if (!polygons.length)
  15654. return;
  15655. if (!this.plane)
  15656. this.plane = polygons[0].plane.clone();
  15657. var front = [], back = [];
  15658. for (var i = 0; i < polygons.length; i++) {
  15659. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  15660. }
  15661. if (front.length) {
  15662. if (!this.front)
  15663. this.front = new Node();
  15664. this.front.build(front);
  15665. }
  15666. if (back.length) {
  15667. if (!this.back)
  15668. this.back = new Node();
  15669. this.back.build(back);
  15670. }
  15671. };
  15672. return Node;
  15673. })();
  15674. var CSG = (function () {
  15675. function CSG() {
  15676. this.polygons = new Array();
  15677. }
  15678. CSG.FromMesh = function (mesh) {
  15679. var vertex, normal, uv, position, polygon, polygons = [], vertices;
  15680. if (mesh instanceof BABYLON.Mesh) {
  15681. mesh.computeWorldMatrix(true);
  15682. var matrix = mesh.getWorldMatrix();
  15683. var meshPosition = mesh.position.clone();
  15684. var meshRotation = mesh.rotation.clone();
  15685. var meshScaling = mesh.scaling.clone();
  15686. } else {
  15687. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  15688. }
  15689. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  15690. var subMeshes = mesh.subMeshes;
  15691. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  15692. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  15693. vertices = [];
  15694. for (var j = 0; j < 3; j++) {
  15695. normal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  15696. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  15697. position = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  15698. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, position);
  15699. BABYLON.Vector3.TransformNormalToRef(normal, matrix, normal);
  15700. vertex = new Vertex(position, normal, uv);
  15701. vertices.push(vertex);
  15702. }
  15703. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  15704. if (polygon.plane)
  15705. polygons.push(polygon);
  15706. }
  15707. }
  15708. var csg = CSG.FromPolygons(polygons);
  15709. csg.matrix = matrix;
  15710. csg.position = meshPosition;
  15711. csg.rotation = meshRotation;
  15712. csg.scaling = meshScaling;
  15713. currentCSGMeshId++;
  15714. return csg;
  15715. };
  15716. CSG.FromPolygons = function (polygons) {
  15717. var csg = new BABYLON.CSG();
  15718. csg.polygons = polygons;
  15719. return csg;
  15720. };
  15721. CSG.prototype.clone = function () {
  15722. var csg = new BABYLON.CSG();
  15723. csg.polygons = this.polygons.map(function (p) {
  15724. return p.clone();
  15725. });
  15726. csg.copyTransformAttributes(this);
  15727. return csg;
  15728. };
  15729. CSG.prototype.toPolygons = function () {
  15730. return this.polygons;
  15731. };
  15732. CSG.prototype.union = function (csg) {
  15733. var a = new Node(this.clone().polygons);
  15734. var b = new Node(csg.clone().polygons);
  15735. a.clipTo(b);
  15736. b.clipTo(a);
  15737. b.invert();
  15738. b.clipTo(a);
  15739. b.invert();
  15740. a.build(b.allPolygons());
  15741. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  15742. };
  15743. CSG.prototype.unionInPlace = function (csg) {
  15744. var a = new Node(this.polygons);
  15745. var b = new Node(csg.polygons);
  15746. a.clipTo(b);
  15747. b.clipTo(a);
  15748. b.invert();
  15749. b.clipTo(a);
  15750. b.invert();
  15751. a.build(b.allPolygons());
  15752. this.polygons = a.allPolygons();
  15753. };
  15754. CSG.prototype.subtract = function (csg) {
  15755. var a = new Node(this.clone().polygons);
  15756. var b = new Node(csg.clone().polygons);
  15757. a.invert();
  15758. a.clipTo(b);
  15759. b.clipTo(a);
  15760. b.invert();
  15761. b.clipTo(a);
  15762. b.invert();
  15763. a.build(b.allPolygons());
  15764. a.invert();
  15765. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  15766. };
  15767. CSG.prototype.subtractInPlace = function (csg) {
  15768. var a = new Node(this.polygons);
  15769. var b = new Node(csg.polygons);
  15770. a.invert();
  15771. a.clipTo(b);
  15772. b.clipTo(a);
  15773. b.invert();
  15774. b.clipTo(a);
  15775. b.invert();
  15776. a.build(b.allPolygons());
  15777. a.invert();
  15778. this.polygons = a.allPolygons();
  15779. };
  15780. CSG.prototype.intersect = function (csg) {
  15781. var a = new Node(this.clone().polygons);
  15782. var b = new Node(csg.clone().polygons);
  15783. a.invert();
  15784. b.clipTo(a);
  15785. b.invert();
  15786. a.clipTo(b);
  15787. b.clipTo(a);
  15788. a.build(b.allPolygons());
  15789. a.invert();
  15790. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  15791. };
  15792. CSG.prototype.intersectInPlace = function (csg) {
  15793. var a = new Node(this.polygons);
  15794. var b = new Node(csg.polygons);
  15795. a.invert();
  15796. b.clipTo(a);
  15797. b.invert();
  15798. a.clipTo(b);
  15799. b.clipTo(a);
  15800. a.build(b.allPolygons());
  15801. a.invert();
  15802. this.polygons = a.allPolygons();
  15803. };
  15804. CSG.prototype.inverse = function () {
  15805. var csg = this.clone();
  15806. csg.inverseInPlace();
  15807. return csg;
  15808. };
  15809. CSG.prototype.inverseInPlace = function () {
  15810. this.polygons.map(function (p) {
  15811. p.flip();
  15812. });
  15813. };
  15814. CSG.prototype.copyTransformAttributes = function (csg) {
  15815. this.matrix = csg.matrix;
  15816. this.position = csg.position;
  15817. this.rotation = csg.rotation;
  15818. this.scaling = csg.scaling;
  15819. return this;
  15820. };
  15821. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  15822. var matrix = this.matrix.clone();
  15823. matrix.invert();
  15824. 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;
  15825. if (keepSubMeshes) {
  15826. polygons.sort(function (a, b) {
  15827. if (a.shared.meshId === b.shared.meshId) {
  15828. return a.shared.subMeshId - b.shared.subMeshId;
  15829. } else {
  15830. return a.shared.meshId - b.shared.meshId;
  15831. }
  15832. });
  15833. }
  15834. for (var i = 0, il = polygons.length; i < il; i++) {
  15835. polygon = polygons[i];
  15836. if (!subMesh_dict[polygon.shared.meshId]) {
  15837. subMesh_dict[polygon.shared.meshId] = {};
  15838. }
  15839. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  15840. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  15841. indexStart: +Infinity,
  15842. indexEnd: -Infinity,
  15843. materialIndex: polygon.shared.materialIndex
  15844. };
  15845. }
  15846. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  15847. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  15848. polygonIndices[0] = 0;
  15849. polygonIndices[1] = j - 1;
  15850. polygonIndices[2] = j;
  15851. for (var k = 0; k < 3; k++) {
  15852. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  15853. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  15854. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  15855. BABYLON.Vector3.TransformCoordinatesToRef(vertex, matrix, vertex);
  15856. BABYLON.Vector3.TransformNormalToRef(normal, matrix, normal);
  15857. vertex_idx = vertice_dict[vertex.x + ',' + vertex.y + ',' + vertex.z];
  15858. if (!(typeof vertex_idx !== 'undefined' && normals[vertex_idx * 3] === normal.x && normals[vertex_idx * 3 + 1] === normal.y && normals[vertex_idx * 3 + 2] === normal.z && uvs[vertex_idx * 2] === uv.x && uvs[vertex_idx * 2 + 1] === uv.y)) {
  15859. vertices.push(vertex.x, vertex.y, vertex.z);
  15860. uvs.push(uv.x, uv.y);
  15861. normals.push(normal.x, normal.y, normal.z);
  15862. vertex_idx = vertice_dict[vertex.x + ',' + vertex.y + ',' + vertex.z] = (vertices.length / 3) - 1;
  15863. }
  15864. indices.push(vertex_idx);
  15865. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  15866. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  15867. currentIndex++;
  15868. }
  15869. }
  15870. }
  15871. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  15872. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  15873. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  15874. mesh.setIndices(indices);
  15875. if (keepSubMeshes) {
  15876. var materialIndexOffset = 0, materialMaxIndex;
  15877. mesh.subMeshes.length = 0;
  15878. for (var m in subMesh_dict) {
  15879. materialMaxIndex = -1;
  15880. for (var sm in subMesh_dict[m]) {
  15881. subMesh_obj = subMesh_dict[m][sm];
  15882. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  15883. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  15884. }
  15885. materialIndexOffset += ++materialMaxIndex;
  15886. }
  15887. }
  15888. return mesh;
  15889. };
  15890. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  15891. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  15892. mesh.material = material;
  15893. mesh.position.copyFrom(this.position);
  15894. mesh.rotation.copyFrom(this.rotation);
  15895. mesh.scaling.copyFrom(this.scaling);
  15896. mesh.computeWorldMatrix(true);
  15897. return mesh;
  15898. };
  15899. return CSG;
  15900. })();
  15901. BABYLON.CSG = CSG;
  15902. })(BABYLON || (BABYLON = {}));
  15903. var __extends = this.__extends || function (d, b) {
  15904. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  15905. function __() { this.constructor = d; }
  15906. __.prototype = b.prototype;
  15907. d.prototype = new __();
  15908. };
  15909. var BABYLON;
  15910. (function (BABYLON) {
  15911. var OculusDistortionCorrectionPostProcess = (function (_super) {
  15912. __extends(OculusDistortionCorrectionPostProcess, _super);
  15913. function OculusDistortionCorrectionPostProcess(name, camera, isRightEye, cameraSettings) {
  15914. var _this = this;
  15915. _super.call(this, name, "oculusDistortionCorrection", [
  15916. 'LensCenter',
  15917. 'Scale',
  15918. 'ScaleIn',
  15919. 'HmdWarpParam'
  15920. ], null, cameraSettings.PostProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  15921. this._isRightEye = isRightEye;
  15922. this._distortionFactors = cameraSettings.DistortionK;
  15923. this._postProcessScaleFactor = cameraSettings.PostProcessScaleFactor;
  15924. this._lensCenterOffset = cameraSettings.LensCenterOffset;
  15925. this.onSizeChanged = function () {
  15926. _this.aspectRatio = _this.width * .5 / _this.height;
  15927. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  15928. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  15929. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  15930. };
  15931. this.onApply = function (effect) {
  15932. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  15933. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  15934. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  15935. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  15936. };
  15937. }
  15938. return OculusDistortionCorrectionPostProcess;
  15939. })(BABYLON.PostProcess);
  15940. BABYLON.OculusDistortionCorrectionPostProcess = OculusDistortionCorrectionPostProcess;
  15941. })(BABYLON || (BABYLON = {}));
  15942. var BABYLON;
  15943. (function (BABYLON) {
  15944. (function (JoystickAxis) {
  15945. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  15946. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  15947. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  15948. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  15949. var JoystickAxis = BABYLON.JoystickAxis;
  15950. var VirtualJoystick = (function () {
  15951. function VirtualJoystick(leftJoystick) {
  15952. var _this = this;
  15953. if (leftJoystick) {
  15954. this._leftJoystick = true;
  15955. } else {
  15956. this._leftJoystick = false;
  15957. }
  15958. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  15959. VirtualJoystick._globalJoystickIndex++;
  15960. this._axisTargetedByLeftAndRight = 0 /* X */;
  15961. this._axisTargetedByUpAndDown = 1 /* Y */;
  15962. this.reverseLeftRight = false;
  15963. this.reverseUpDown = false;
  15964. this._touches = new BABYLON.VirtualJoystick.Collection();
  15965. this.deltaPosition = BABYLON.Vector3.Zero();
  15966. this._joystickSensibility = 25;
  15967. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  15968. this._rotationSpeed = 25;
  15969. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  15970. this._rotateOnAxisRelativeToMesh = false;
  15971. if (!VirtualJoystick.vjCanvas) {
  15972. window.addEventListener("resize", function () {
  15973. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  15974. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  15975. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  15976. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  15977. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  15978. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  15979. }, false);
  15980. VirtualJoystick.vjCanvas = document.createElement("canvas");
  15981. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  15982. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  15983. VirtualJoystick.vjCanvas.width = window.innerWidth;
  15984. VirtualJoystick.vjCanvas.height = window.innerHeight;
  15985. VirtualJoystick.vjCanvas.style.width = "100%";
  15986. VirtualJoystick.vjCanvas.style.height = "100%";
  15987. VirtualJoystick.vjCanvas.style.position = "absolute";
  15988. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  15989. VirtualJoystick.vjCanvas.style.top = "0px";
  15990. VirtualJoystick.vjCanvas.style.left = "0px";
  15991. VirtualJoystick.vjCanvas.style.zIndex = "5";
  15992. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  15993. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  15994. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  15995. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  15996. document.body.appendChild(VirtualJoystick.vjCanvas);
  15997. }
  15998. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  15999. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  16000. this.pressed = false;
  16001. this._joystickColor = "cyan";
  16002. this._joystickPointerID = -1;
  16003. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  16004. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  16005. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  16006. VirtualJoystick.vjCanvas.addEventListener('pointerdown', function (evt) {
  16007. _this._onPointerDown(evt);
  16008. }, false);
  16009. VirtualJoystick.vjCanvas.addEventListener('pointermove', function (evt) {
  16010. _this._onPointerMove(evt);
  16011. }, false);
  16012. VirtualJoystick.vjCanvas.addEventListener('pointerup', function (evt) {
  16013. _this._onPointerUp(evt);
  16014. }, false);
  16015. VirtualJoystick.vjCanvas.addEventListener('pointerout', function (evt) {
  16016. _this._onPointerUp(evt);
  16017. }, false);
  16018. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  16019. evt.preventDefault();
  16020. }, false);
  16021. requestAnimationFrame(function () {
  16022. _this._drawVirtualJoystick();
  16023. });
  16024. }
  16025. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  16026. this._joystickSensibility = newJoystickSensibility;
  16027. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  16028. };
  16029. VirtualJoystick.prototype._onPointerDown = function (e) {
  16030. var positionOnScreenCondition;
  16031. e.preventDefault();
  16032. if (this._leftJoystick === true) {
  16033. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  16034. } else {
  16035. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  16036. }
  16037. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  16038. this._joystickPointerID = e.pointerId;
  16039. this._joystickPointerStartPos.x = e.clientX;
  16040. this._joystickPointerStartPos.y = e.clientY;
  16041. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  16042. this._deltaJoystickVector.x = 0;
  16043. this._deltaJoystickVector.y = 0;
  16044. this.pressed = true;
  16045. this._touches.add(e.pointerId.toString(), e);
  16046. } else {
  16047. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  16048. this._action();
  16049. this._touches.add(e.pointerId.toString(), e);
  16050. }
  16051. }
  16052. };
  16053. VirtualJoystick.prototype._onPointerMove = function (e) {
  16054. if (this._joystickPointerID == e.pointerId) {
  16055. this._joystickPointerPos.x = e.clientX;
  16056. this._joystickPointerPos.y = e.clientY;
  16057. this._deltaJoystickVector = this._joystickPointerPos.clone();
  16058. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  16059. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  16060. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  16061. switch (this._axisTargetedByLeftAndRight) {
  16062. case 0 /* X */:
  16063. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  16064. break;
  16065. case 1 /* Y */:
  16066. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  16067. break;
  16068. case 2 /* Z */:
  16069. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  16070. break;
  16071. }
  16072. var directionUpDown = this.reverseUpDown ? 1 : -1;
  16073. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  16074. switch (this._axisTargetedByUpAndDown) {
  16075. case 0 /* X */:
  16076. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  16077. break;
  16078. case 1 /* Y */:
  16079. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  16080. break;
  16081. case 2 /* Z */:
  16082. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  16083. break;
  16084. }
  16085. } else {
  16086. if (this._touches.item(e.pointerId.toString())) {
  16087. this._touches.item(e.pointerId.toString()).x = e.clientX;
  16088. this._touches.item(e.pointerId.toString()).y = e.clientY;
  16089. }
  16090. }
  16091. };
  16092. VirtualJoystick.prototype._onPointerUp = function (e) {
  16093. this._clearCanvas();
  16094. if (this._joystickPointerID == e.pointerId) {
  16095. this._joystickPointerID = -1;
  16096. this.pressed = false;
  16097. }
  16098. this._deltaJoystickVector.x = 0;
  16099. this._deltaJoystickVector.y = 0;
  16100. this._touches.remove(e.pointerId.toString());
  16101. };
  16102. /**
  16103. * Change the color of the virtual joystick
  16104. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  16105. */
  16106. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  16107. this._joystickColor = newColor;
  16108. };
  16109. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  16110. this._action = action;
  16111. };
  16112. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  16113. switch (axis) {
  16114. case 0 /* X */:
  16115. case 1 /* Y */:
  16116. case 2 /* Z */:
  16117. this._axisTargetedByLeftAndRight = axis;
  16118. break;
  16119. default:
  16120. this._axisTargetedByLeftAndRight = 0 /* X */;
  16121. break;
  16122. }
  16123. };
  16124. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  16125. switch (axis) {
  16126. case 0 /* X */:
  16127. case 1 /* Y */:
  16128. case 2 /* Z */:
  16129. this._axisTargetedByUpAndDown = axis;
  16130. break;
  16131. default:
  16132. this._axisTargetedByUpAndDown = 1 /* Y */;
  16133. break;
  16134. }
  16135. };
  16136. VirtualJoystick.prototype._clearCanvas = function () {
  16137. if (this._leftJoystick) {
  16138. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  16139. } else {
  16140. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  16141. }
  16142. };
  16143. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  16144. var _this = this;
  16145. if (this.pressed) {
  16146. this._clearCanvas();
  16147. this._touches.forEach(function (touch) {
  16148. if (touch.pointerId === _this._joystickPointerID) {
  16149. VirtualJoystick.vjCanvasContext.beginPath();
  16150. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  16151. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  16152. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  16153. VirtualJoystick.vjCanvasContext.stroke();
  16154. VirtualJoystick.vjCanvasContext.beginPath();
  16155. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  16156. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  16157. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  16158. VirtualJoystick.vjCanvasContext.stroke();
  16159. VirtualJoystick.vjCanvasContext.beginPath();
  16160. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  16161. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  16162. VirtualJoystick.vjCanvasContext.stroke();
  16163. } else {
  16164. VirtualJoystick.vjCanvasContext.beginPath();
  16165. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  16166. VirtualJoystick.vjCanvasContext.beginPath();
  16167. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  16168. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  16169. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  16170. VirtualJoystick.vjCanvasContext.stroke();
  16171. }
  16172. ;
  16173. });
  16174. }
  16175. requestAnimationFrame(function () {
  16176. _this._drawVirtualJoystick();
  16177. });
  16178. };
  16179. VirtualJoystick.prototype.releaseCanvas = function () {
  16180. if (VirtualJoystick.vjCanvas) {
  16181. document.body.removeChild(VirtualJoystick.vjCanvas);
  16182. VirtualJoystick.vjCanvas = null;
  16183. }
  16184. };
  16185. VirtualJoystick._globalJoystickIndex = 0;
  16186. return VirtualJoystick;
  16187. })();
  16188. BABYLON.VirtualJoystick = VirtualJoystick;
  16189. })(BABYLON || (BABYLON = {}));
  16190. var BABYLON;
  16191. (function (BABYLON) {
  16192. (function (VirtualJoystick) {
  16193. var Collection = (function () {
  16194. function Collection() {
  16195. this._count = 0;
  16196. this._collection = new Array();
  16197. }
  16198. Collection.prototype.Count = function () {
  16199. return this._count;
  16200. };
  16201. Collection.prototype.add = function (key, item) {
  16202. if (this._collection[key] != undefined) {
  16203. return undefined;
  16204. }
  16205. this._collection[key] = item;
  16206. return ++this._count;
  16207. };
  16208. Collection.prototype.remove = function (key) {
  16209. if (this._collection[key] == undefined) {
  16210. return undefined;
  16211. }
  16212. delete this._collection[key];
  16213. return --this._count;
  16214. };
  16215. Collection.prototype.item = function (key) {
  16216. return this._collection[key];
  16217. };
  16218. Collection.prototype.forEach = function (block) {
  16219. var key;
  16220. for (key in this._collection) {
  16221. if (this._collection.hasOwnProperty(key)) {
  16222. block(this._collection[key]);
  16223. }
  16224. }
  16225. };
  16226. return Collection;
  16227. })();
  16228. VirtualJoystick.Collection = Collection;
  16229. })(BABYLON.VirtualJoystick || (BABYLON.VirtualJoystick = {}));
  16230. var VirtualJoystick = BABYLON.VirtualJoystick;
  16231. })(BABYLON || (BABYLON = {}));
  16232. var __extends = this.__extends || function (d, b) {
  16233. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  16234. function __() { this.constructor = d; }
  16235. __.prototype = b.prototype;
  16236. d.prototype = new __();
  16237. };
  16238. var BABYLON;
  16239. (function (BABYLON) {
  16240. var OculusRiftDevKit2013_Metric = {
  16241. HResolution: 1280,
  16242. VResolution: 800,
  16243. HScreenSize: 0.149759993,
  16244. VScreenSize: 0.0935999975,
  16245. VScreenCenter: 0.0467999987,
  16246. EyeToScreenDistance: 0.0410000011,
  16247. LensSeparationDistance: 0.0635000020,
  16248. InterpupillaryDistance: 0.0640000030,
  16249. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  16250. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  16251. PostProcessScaleFactor: 1.714605507808412,
  16252. LensCenterOffset: 0.151976421
  16253. };
  16254. var _OculusInnerCamera = (function (_super) {
  16255. __extends(_OculusInnerCamera, _super);
  16256. function _OculusInnerCamera(name, position, scene, isLeftEye) {
  16257. _super.call(this, name, position, scene);
  16258. this._workMatrix = new BABYLON.Matrix();
  16259. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  16260. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  16261. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  16262. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  16263. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  16264. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  16265. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  16266. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  16267. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  16268. }
  16269. _OculusInnerCamera.prototype.getProjectionMatrix = function () {
  16270. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  16271. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  16272. return this._projectionMatrix;
  16273. };
  16274. _OculusInnerCamera.prototype._getViewMatrix = function () {
  16275. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  16276. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  16277. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  16278. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  16279. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  16280. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  16281. return this._viewMatrix;
  16282. };
  16283. return _OculusInnerCamera;
  16284. })(BABYLON.FreeCamera);
  16285. var OculusCamera = (function (_super) {
  16286. __extends(OculusCamera, _super);
  16287. function OculusCamera(name, position, scene) {
  16288. _super.call(this, name, position, scene);
  16289. this._leftCamera = new _OculusInnerCamera(name + "_left", position.clone(), scene, true);
  16290. this._rightCamera = new _OculusInnerCamera(name + "_right", position.clone(), scene, false);
  16291. this.subCameras.push(this._leftCamera);
  16292. this.subCameras.push(this._rightCamera);
  16293. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  16294. }
  16295. OculusCamera.prototype._update = function () {
  16296. this._leftCamera.position.copyFrom(this.position);
  16297. this._rightCamera.position.copyFrom(this.position);
  16298. this._updateCamera(this._leftCamera);
  16299. this._updateCamera(this._rightCamera);
  16300. _super.prototype._update.call(this);
  16301. };
  16302. OculusCamera.prototype._updateCamera = function (camera) {
  16303. camera.minZ = this.minZ;
  16304. camera.maxZ = this.maxZ;
  16305. camera.rotation.x = this.rotation.x;
  16306. camera.rotation.y = this.rotation.y;
  16307. camera.rotation.z = this.rotation.z;
  16308. };
  16309. OculusCamera.prototype._onOrientationEvent = function (evt) {
  16310. var yaw = evt.alpha / 180 * Math.PI;
  16311. var pitch = evt.beta / 180 * Math.PI;
  16312. var roll = evt.gamma / 180 * Math.PI;
  16313. if (!this._offsetOrientation) {
  16314. this._offsetOrientation = {
  16315. yaw: yaw,
  16316. pitch: pitch,
  16317. roll: roll
  16318. };
  16319. return;
  16320. } else {
  16321. this.rotation.y += yaw - this._offsetOrientation.yaw;
  16322. this.rotation.x += pitch - this._offsetOrientation.pitch;
  16323. this.rotation.z += this._offsetOrientation.roll - roll;
  16324. this._offsetOrientation.yaw = yaw;
  16325. this._offsetOrientation.pitch = pitch;
  16326. this._offsetOrientation.roll = roll;
  16327. }
  16328. };
  16329. OculusCamera.prototype.attachControl = function (element, noPreventDefault) {
  16330. _super.prototype.attachControl.call(this, element, noPreventDefault);
  16331. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  16332. };
  16333. OculusCamera.prototype.detachControl = function (element) {
  16334. _super.prototype.detachControl.call(this, element);
  16335. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  16336. };
  16337. return OculusCamera;
  16338. })(BABYLON.FreeCamera);
  16339. BABYLON.OculusCamera = OculusCamera;
  16340. })(BABYLON || (BABYLON = {}));
  16341. var __extends = this.__extends || function (d, b) {
  16342. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  16343. function __() { this.constructor = d; }
  16344. __.prototype = b.prototype;
  16345. d.prototype = new __();
  16346. };
  16347. var BABYLON;
  16348. (function (BABYLON) {
  16349. var OculusRiftDevKit2013_Metric = {
  16350. HResolution: 1280,
  16351. VResolution: 800,
  16352. HScreenSize: 0.149759993,
  16353. VScreenSize: 0.0935999975,
  16354. VScreenCenter: 0.0467999987,
  16355. EyeToScreenDistance: 0.0410000011,
  16356. LensSeparationDistance: 0.0635000020,
  16357. InterpupillaryDistance: 0.0640000030,
  16358. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  16359. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  16360. PostProcessScaleFactor: 1.714605507808412,
  16361. LensCenterOffset: 0.151976421
  16362. };
  16363. var _OculusInnerGamepadCamera = (function (_super) {
  16364. __extends(_OculusInnerGamepadCamera, _super);
  16365. function _OculusInnerGamepadCamera(name, position, scene, isLeftEye) {
  16366. _super.call(this, name, position, scene);
  16367. this._workMatrix = new BABYLON.Matrix();
  16368. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  16369. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  16370. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  16371. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  16372. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  16373. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  16374. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  16375. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  16376. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  16377. }
  16378. _OculusInnerGamepadCamera.prototype.getProjectionMatrix = function () {
  16379. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  16380. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  16381. return this._projectionMatrix;
  16382. };
  16383. _OculusInnerGamepadCamera.prototype._getViewMatrix = function () {
  16384. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  16385. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  16386. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  16387. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  16388. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  16389. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  16390. return this._viewMatrix;
  16391. };
  16392. return _OculusInnerGamepadCamera;
  16393. })(BABYLON.FreeCamera);
  16394. var OculusGamepadCamera = (function (_super) {
  16395. __extends(OculusGamepadCamera, _super);
  16396. function OculusGamepadCamera(name, position, scene) {
  16397. var _this = this;
  16398. _super.call(this, name, position, scene);
  16399. this.angularSensibility = 200;
  16400. this.moveSensibility = 75;
  16401. this._leftCamera = new _OculusInnerGamepadCamera(name + "_left", position.clone(), scene, true);
  16402. this._rightCamera = new _OculusInnerGamepadCamera(name + "_right", position.clone(), scene, false);
  16403. this.subCameras.push(this._leftCamera);
  16404. this.subCameras.push(this._rightCamera);
  16405. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  16406. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  16407. _this._onNewGameConnected(gamepad);
  16408. });
  16409. }
  16410. OculusGamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  16411. if (gamepad.index === 0) {
  16412. this._gamepad = gamepad;
  16413. }
  16414. };
  16415. OculusGamepadCamera.prototype._update = function () {
  16416. this._leftCamera.position.copyFrom(this.position);
  16417. this._rightCamera.position.copyFrom(this.position);
  16418. this._updateCamera(this._leftCamera);
  16419. this._updateCamera(this._rightCamera);
  16420. _super.prototype._update.call(this);
  16421. };
  16422. OculusGamepadCamera.prototype._checkInputs = function () {
  16423. if (!this._gamepad) {
  16424. return;
  16425. }
  16426. var LSValues = this._gamepad.leftStick;
  16427. var normalizedLX = LSValues.x / this.moveSensibility;
  16428. var normalizedLY = LSValues.y / this.moveSensibility;
  16429. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  16430. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  16431. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  16432. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x, 0, -LSValues.y), cameraTransform);
  16433. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  16434. };
  16435. OculusGamepadCamera.prototype._updateCamera = function (camera) {
  16436. camera.minZ = this.minZ;
  16437. camera.maxZ = this.maxZ;
  16438. camera.rotation.x = this.rotation.x;
  16439. camera.rotation.y = this.rotation.y;
  16440. camera.rotation.z = this.rotation.z;
  16441. };
  16442. OculusGamepadCamera.prototype._onOrientationEvent = function (evt) {
  16443. var yaw = evt.alpha / 180 * Math.PI;
  16444. var pitch = evt.beta / 180 * Math.PI;
  16445. var roll = evt.gamma / 180 * Math.PI;
  16446. if (!this._offsetOrientation) {
  16447. this._offsetOrientation = {
  16448. yaw: yaw,
  16449. pitch: pitch,
  16450. roll: roll
  16451. };
  16452. return;
  16453. } else {
  16454. this.rotation.y += yaw - this._offsetOrientation.yaw;
  16455. this.rotation.x += pitch - this._offsetOrientation.pitch;
  16456. this.rotation.z += this._offsetOrientation.roll - roll;
  16457. this._offsetOrientation.yaw = yaw;
  16458. this._offsetOrientation.pitch = pitch;
  16459. this._offsetOrientation.roll = roll;
  16460. }
  16461. };
  16462. OculusGamepadCamera.prototype.attachControl = function (element, noPreventDefault) {
  16463. _super.prototype.attachControl.call(this, element, noPreventDefault);
  16464. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  16465. };
  16466. OculusGamepadCamera.prototype.detachControl = function (element) {
  16467. _super.prototype.detachControl.call(this, element);
  16468. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  16469. };
  16470. OculusGamepadCamera.prototype.dispose = function () {
  16471. this._gamepads.dispose();
  16472. _super.prototype.dispose.call(this);
  16473. };
  16474. return OculusGamepadCamera;
  16475. })(BABYLON.FreeCamera);
  16476. BABYLON.OculusGamepadCamera = OculusGamepadCamera;
  16477. })(BABYLON || (BABYLON = {}));
  16478. var __extends = this.__extends || function (d, b) {
  16479. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  16480. function __() { this.constructor = d; }
  16481. __.prototype = b.prototype;
  16482. d.prototype = new __();
  16483. };
  16484. var BABYLON;
  16485. (function (BABYLON) {
  16486. var VirtualJoysticksCamera = (function (_super) {
  16487. __extends(VirtualJoysticksCamera, _super);
  16488. function VirtualJoysticksCamera(name, position, scene) {
  16489. _super.call(this, name, position, scene);
  16490. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  16491. this._leftjoystick.setAxisForUpDown(2 /* Z */);
  16492. this._leftjoystick.setAxisForLeftRight(0 /* X */);
  16493. this._leftjoystick.setJoystickSensibility(0.15);
  16494. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  16495. this._rightjoystick.setAxisForUpDown(0 /* X */);
  16496. this._rightjoystick.setAxisForLeftRight(1 /* Y */);
  16497. this._rightjoystick.reverseUpDown = true;
  16498. this._rightjoystick.setJoystickSensibility(0.05);
  16499. this._rightjoystick.setJoystickColor("yellow");
  16500. }
  16501. VirtualJoysticksCamera.prototype._checkInputs = function () {
  16502. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  16503. var deltaTransform = BABYLON.Vector3.TransformCoordinates(this._leftjoystick.deltaPosition, cameraTransform);
  16504. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  16505. this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  16506. if (!this._leftjoystick.pressed) {
  16507. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  16508. }
  16509. if (!this._rightjoystick.pressed) {
  16510. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  16511. }
  16512. };
  16513. VirtualJoysticksCamera.prototype.dispose = function () {
  16514. this._leftjoystick.releaseCanvas();
  16515. _super.prototype.dispose.call(this);
  16516. };
  16517. return VirtualJoysticksCamera;
  16518. })(BABYLON.FreeCamera);
  16519. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  16520. })(BABYLON || (BABYLON = {}));
  16521. var __extends = this.__extends || function (d, b) {
  16522. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  16523. function __() { this.constructor = d; }
  16524. __.prototype = b.prototype;
  16525. d.prototype = new __();
  16526. };
  16527. var BABYLON;
  16528. (function (BABYLON) {
  16529. var ShaderMaterial = (function (_super) {
  16530. __extends(ShaderMaterial, _super);
  16531. function ShaderMaterial(name, scene, shaderPath, options) {
  16532. _super.call(this, name, scene);
  16533. this._textures = new Array();
  16534. this._floats = new Array();
  16535. this._floatsArrays = {};
  16536. this._colors3 = new Array();
  16537. this._colors4 = new Array();
  16538. this._vectors2 = new Array();
  16539. this._vectors3 = new Array();
  16540. this._matrices = new Array();
  16541. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  16542. this._shaderPath = shaderPath;
  16543. options.needAlphaBlending = options.needAlphaBlending || false;
  16544. options.needAlphaTesting = options.needAlphaTesting || false;
  16545. options.attributes = options.attributes || ["position", "normal", "uv"];
  16546. options.uniforms = options.uniforms || ["worldViewProjection"];
  16547. options.samplers = options.samplers || [];
  16548. this._options = options;
  16549. }
  16550. ShaderMaterial.prototype.needAlphaBlending = function () {
  16551. return this._options.needAlphaBlending;
  16552. };
  16553. ShaderMaterial.prototype.needAlphaTesting = function () {
  16554. return this._options.needAlphaTesting;
  16555. };
  16556. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  16557. if (this._options.uniforms.indexOf(uniformName) === -1) {
  16558. this._options.uniforms.push(uniformName);
  16559. }
  16560. };
  16561. ShaderMaterial.prototype.setTexture = function (name, texture) {
  16562. if (this._options.samplers.indexOf(name) === -1) {
  16563. this._options.samplers.push(name);
  16564. }
  16565. this._textures[name] = texture;
  16566. return this;
  16567. };
  16568. ShaderMaterial.prototype.setFloat = function (name, value) {
  16569. this._checkUniform(name);
  16570. this._floats[name] = value;
  16571. return this;
  16572. };
  16573. ShaderMaterial.prototype.setFloats = function (name, value) {
  16574. this._checkUniform(name);
  16575. this._floatsArrays[name] = value;
  16576. return this;
  16577. };
  16578. ShaderMaterial.prototype.setColor3 = function (name, value) {
  16579. this._checkUniform(name);
  16580. this._colors3[name] = value;
  16581. return this;
  16582. };
  16583. ShaderMaterial.prototype.setColor4 = function (name, value) {
  16584. this._checkUniform(name);
  16585. this._colors4[name] = value;
  16586. return this;
  16587. };
  16588. ShaderMaterial.prototype.setVector2 = function (name, value) {
  16589. this._checkUniform(name);
  16590. this._vectors2[name] = value;
  16591. return this;
  16592. };
  16593. ShaderMaterial.prototype.setVector3 = function (name, value) {
  16594. this._checkUniform(name);
  16595. this._vectors3[name] = value;
  16596. return this;
  16597. };
  16598. ShaderMaterial.prototype.setMatrix = function (name, value) {
  16599. this._checkUniform(name);
  16600. this._matrices[name] = value;
  16601. return this;
  16602. };
  16603. ShaderMaterial.prototype.isReady = function () {
  16604. var engine = this.getScene().getEngine();
  16605. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, "", null, this.onCompiled, this.onError);
  16606. if (!this._effect.isReady()) {
  16607. return false;
  16608. }
  16609. return true;
  16610. };
  16611. ShaderMaterial.prototype.bind = function (world) {
  16612. if (this._options.uniforms.indexOf("world") !== -1) {
  16613. this._effect.setMatrix("world", world);
  16614. }
  16615. if (this._options.uniforms.indexOf("view") !== -1) {
  16616. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  16617. }
  16618. if (this._options.uniforms.indexOf("worldView") !== -1) {
  16619. world.multiplyToRef(this.getScene().getViewMatrix(), this._cachedWorldViewMatrix);
  16620. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  16621. }
  16622. if (this._options.uniforms.indexOf("projection") !== -1) {
  16623. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  16624. }
  16625. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  16626. this._effect.setMatrix("worldViewProjection", world.multiply(this.getScene().getTransformMatrix()));
  16627. }
  16628. for (var name in this._textures) {
  16629. this._effect.setTexture(name, this._textures[name]);
  16630. }
  16631. for (name in this._floats) {
  16632. this._effect.setFloat(name, this._floats[name]);
  16633. }
  16634. for (name in this._floatsArrays) {
  16635. this._effect.setArray(name, this._floatsArrays[name]);
  16636. }
  16637. for (name in this._colors3) {
  16638. this._effect.setColor3(name, this._colors3[name]);
  16639. }
  16640. for (name in this._colors4) {
  16641. var color = this._colors4[name];
  16642. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  16643. }
  16644. for (name in this._vectors2) {
  16645. this._effect.setVector2(name, this._vectors2[name]);
  16646. }
  16647. for (name in this._vectors3) {
  16648. this._effect.setVector3(name, this._vectors3[name]);
  16649. }
  16650. for (name in this._matrices) {
  16651. this._effect.setMatrix(name, this._matrices[name]);
  16652. }
  16653. };
  16654. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  16655. for (var name in this._textures) {
  16656. this._textures[name].dispose();
  16657. }
  16658. this._textures = [];
  16659. _super.prototype.dispose.call(this, forceDisposeEffect);
  16660. };
  16661. return ShaderMaterial;
  16662. })(BABYLON.Material);
  16663. BABYLON.ShaderMaterial = ShaderMaterial;
  16664. })(BABYLON || (BABYLON = {}));
  16665. var BABYLON;
  16666. (function (BABYLON) {
  16667. var VertexData = (function () {
  16668. function VertexData() {
  16669. }
  16670. VertexData.prototype.set = function (data, kind) {
  16671. switch (kind) {
  16672. case BABYLON.VertexBuffer.PositionKind:
  16673. this.positions = data;
  16674. break;
  16675. case BABYLON.VertexBuffer.NormalKind:
  16676. this.normals = data;
  16677. break;
  16678. case BABYLON.VertexBuffer.UVKind:
  16679. this.uvs = data;
  16680. break;
  16681. case BABYLON.VertexBuffer.UV2Kind:
  16682. this.uv2s = data;
  16683. break;
  16684. case BABYLON.VertexBuffer.ColorKind:
  16685. this.colors = data;
  16686. break;
  16687. case BABYLON.VertexBuffer.MatricesIndicesKind:
  16688. this.matricesIndices = data;
  16689. break;
  16690. case BABYLON.VertexBuffer.MatricesWeightsKind:
  16691. this.matricesWeights = data;
  16692. break;
  16693. }
  16694. };
  16695. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  16696. this._applyTo(mesh, updatable);
  16697. };
  16698. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  16699. this._applyTo(geometry, updatable);
  16700. };
  16701. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  16702. this._update(mesh);
  16703. };
  16704. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  16705. this._update(geometry);
  16706. };
  16707. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  16708. if (this.positions) {
  16709. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  16710. }
  16711. if (this.normals) {
  16712. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  16713. }
  16714. if (this.uvs) {
  16715. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  16716. }
  16717. if (this.uv2s) {
  16718. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updatable);
  16719. }
  16720. if (this.colors) {
  16721. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  16722. }
  16723. if (this.matricesIndices) {
  16724. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  16725. }
  16726. if (this.matricesWeights) {
  16727. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  16728. }
  16729. if (this.indices) {
  16730. meshOrGeometry.setIndices(this.indices);
  16731. }
  16732. };
  16733. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  16734. if (this.positions) {
  16735. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  16736. }
  16737. if (this.normals) {
  16738. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  16739. }
  16740. if (this.uvs) {
  16741. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  16742. }
  16743. if (this.uv2s) {
  16744. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updateExtends, makeItUnique);
  16745. }
  16746. if (this.colors) {
  16747. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  16748. }
  16749. if (this.matricesIndices) {
  16750. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  16751. }
  16752. if (this.matricesWeights) {
  16753. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  16754. }
  16755. if (this.indices) {
  16756. meshOrGeometry.setIndices(this.indices);
  16757. }
  16758. };
  16759. VertexData.prototype.transform = function (matrix) {
  16760. var transformed = BABYLON.Vector3.Zero();
  16761. if (this.positions) {
  16762. var position = BABYLON.Vector3.Zero();
  16763. for (var index = 0; index < this.positions.length; index += 3) {
  16764. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  16765. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  16766. this.positions[index] = transformed.x;
  16767. this.positions[index + 1] = transformed.y;
  16768. this.positions[index + 2] = transformed.z;
  16769. }
  16770. }
  16771. if (this.normals) {
  16772. var normal = BABYLON.Vector3.Zero();
  16773. for (index = 0; index < this.normals.length; index += 3) {
  16774. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  16775. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  16776. this.normals[index] = transformed.x;
  16777. this.normals[index + 1] = transformed.y;
  16778. this.normals[index + 2] = transformed.z;
  16779. }
  16780. }
  16781. };
  16782. VertexData.prototype.merge = function (other) {
  16783. if (other.indices) {
  16784. if (!this.indices) {
  16785. this.indices = [];
  16786. }
  16787. var offset = this.positions ? this.positions.length / 3 : 0;
  16788. for (var index = 0; index < other.indices.length; index++) {
  16789. this.indices.push(other.indices[index] + offset);
  16790. }
  16791. }
  16792. if (other.positions) {
  16793. if (!this.positions) {
  16794. this.positions = [];
  16795. }
  16796. for (index = 0; index < other.positions.length; index++) {
  16797. this.positions.push(other.positions[index]);
  16798. }
  16799. }
  16800. if (other.normals) {
  16801. if (!this.normals) {
  16802. this.normals = [];
  16803. }
  16804. for (index = 0; index < other.normals.length; index++) {
  16805. this.normals.push(other.normals[index]);
  16806. }
  16807. }
  16808. if (other.uvs) {
  16809. if (!this.uvs) {
  16810. this.uvs = [];
  16811. }
  16812. for (index = 0; index < other.uvs.length; index++) {
  16813. this.uvs.push(other.uvs[index]);
  16814. }
  16815. }
  16816. if (other.uv2s) {
  16817. if (!this.uv2s) {
  16818. this.uv2s = [];
  16819. }
  16820. for (index = 0; index < other.uv2s.length; index++) {
  16821. this.uv2s.push(other.uv2s[index]);
  16822. }
  16823. }
  16824. if (other.matricesIndices) {
  16825. if (!this.matricesIndices) {
  16826. this.matricesIndices = [];
  16827. }
  16828. for (index = 0; index < other.matricesIndices.length; index++) {
  16829. this.matricesIndices.push(other.matricesIndices[index]);
  16830. }
  16831. }
  16832. if (other.matricesWeights) {
  16833. if (!this.matricesWeights) {
  16834. this.matricesWeights = [];
  16835. }
  16836. for (index = 0; index < other.matricesWeights.length; index++) {
  16837. this.matricesWeights.push(other.matricesWeights[index]);
  16838. }
  16839. }
  16840. if (other.colors) {
  16841. if (!this.colors) {
  16842. this.colors = [];
  16843. }
  16844. for (index = 0; index < other.colors.length; index++) {
  16845. this.colors.push(other.colors[index]);
  16846. }
  16847. }
  16848. };
  16849. VertexData.ExtractFromMesh = function (mesh) {
  16850. return VertexData._ExtractFrom(mesh);
  16851. };
  16852. VertexData.ExtractFromGeometry = function (geometry) {
  16853. return VertexData._ExtractFrom(geometry);
  16854. };
  16855. VertexData._ExtractFrom = function (meshOrGeometry) {
  16856. var result = new BABYLON.VertexData();
  16857. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  16858. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16859. }
  16860. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  16861. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16862. }
  16863. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  16864. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind);
  16865. }
  16866. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  16867. result.uv2s = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  16868. }
  16869. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  16870. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  16871. }
  16872. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  16873. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  16874. }
  16875. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  16876. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  16877. }
  16878. result.indices = meshOrGeometry.getIndices();
  16879. return result;
  16880. };
  16881. VertexData.CreateBox = function (size) {
  16882. var normalsSource = [
  16883. new BABYLON.Vector3(0, 0, 1),
  16884. new BABYLON.Vector3(0, 0, -1),
  16885. new BABYLON.Vector3(1, 0, 0),
  16886. new BABYLON.Vector3(-1, 0, 0),
  16887. new BABYLON.Vector3(0, 1, 0),
  16888. new BABYLON.Vector3(0, -1, 0)
  16889. ];
  16890. var indices = [];
  16891. var positions = [];
  16892. var normals = [];
  16893. var uvs = [];
  16894. size = size || 1;
  16895. for (var index = 0; index < normalsSource.length; index++) {
  16896. var normal = normalsSource[index];
  16897. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  16898. var side2 = BABYLON.Vector3.Cross(normal, side1);
  16899. var verticesLength = positions.length / 3;
  16900. indices.push(verticesLength);
  16901. indices.push(verticesLength + 1);
  16902. indices.push(verticesLength + 2);
  16903. indices.push(verticesLength);
  16904. indices.push(verticesLength + 2);
  16905. indices.push(verticesLength + 3);
  16906. var vertex = normal.subtract(side1).subtract(side2).scale(size / 2);
  16907. positions.push(vertex.x, vertex.y, vertex.z);
  16908. normals.push(normal.x, normal.y, normal.z);
  16909. uvs.push(1.0, 1.0);
  16910. vertex = normal.subtract(side1).add(side2).scale(size / 2);
  16911. positions.push(vertex.x, vertex.y, vertex.z);
  16912. normals.push(normal.x, normal.y, normal.z);
  16913. uvs.push(0.0, 1.0);
  16914. vertex = normal.add(side1).add(side2).scale(size / 2);
  16915. positions.push(vertex.x, vertex.y, vertex.z);
  16916. normals.push(normal.x, normal.y, normal.z);
  16917. uvs.push(0.0, 0.0);
  16918. vertex = normal.add(side1).subtract(side2).scale(size / 2);
  16919. positions.push(vertex.x, vertex.y, vertex.z);
  16920. normals.push(normal.x, normal.y, normal.z);
  16921. uvs.push(1.0, 0.0);
  16922. }
  16923. var vertexData = new BABYLON.VertexData();
  16924. vertexData.indices = indices;
  16925. vertexData.positions = positions;
  16926. vertexData.normals = normals;
  16927. vertexData.uvs = uvs;
  16928. return vertexData;
  16929. };
  16930. VertexData.CreateSphere = function (segments, diameter) {
  16931. segments = segments || 32;
  16932. diameter = diameter || 1;
  16933. var radius = diameter / 2;
  16934. var totalZRotationSteps = 2 + segments;
  16935. var totalYRotationSteps = 2 * totalZRotationSteps;
  16936. var indices = [];
  16937. var positions = [];
  16938. var normals = [];
  16939. var uvs = [];
  16940. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  16941. var normalizedZ = zRotationStep / totalZRotationSteps;
  16942. var angleZ = (normalizedZ * Math.PI);
  16943. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  16944. var normalizedY = yRotationStep / totalYRotationSteps;
  16945. var angleY = normalizedY * Math.PI * 2;
  16946. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  16947. var rotationY = BABYLON.Matrix.RotationY(angleY);
  16948. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  16949. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  16950. var vertex = complete.scale(radius);
  16951. var normal = BABYLON.Vector3.Normalize(vertex);
  16952. positions.push(vertex.x, vertex.y, vertex.z);
  16953. normals.push(normal.x, normal.y, normal.z);
  16954. uvs.push(normalizedZ, normalizedY);
  16955. }
  16956. if (zRotationStep > 0) {
  16957. var verticesCount = positions.length / 3;
  16958. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  16959. indices.push((firstIndex));
  16960. indices.push((firstIndex + 1));
  16961. indices.push(firstIndex + totalYRotationSteps + 1);
  16962. indices.push((firstIndex + totalYRotationSteps + 1));
  16963. indices.push((firstIndex + 1));
  16964. indices.push((firstIndex + totalYRotationSteps + 2));
  16965. }
  16966. }
  16967. }
  16968. var vertexData = new BABYLON.VertexData();
  16969. vertexData.indices = indices;
  16970. vertexData.positions = positions;
  16971. vertexData.normals = normals;
  16972. vertexData.uvs = uvs;
  16973. return vertexData;
  16974. };
  16975. VertexData.CreateCylinder = function (height, diameterTop, diameterBottom, tessellation, subdivisions) {
  16976. if (typeof subdivisions === "undefined") { subdivisions = 1; }
  16977. var radiusTop = diameterTop / 2;
  16978. var radiusBottom = diameterBottom / 2;
  16979. var indices = [];
  16980. var positions = [];
  16981. var normals = [];
  16982. var uvs = [];
  16983. height = height || 1;
  16984. diameterTop = diameterTop || 0.5;
  16985. diameterBottom = diameterBottom || 1;
  16986. tessellation = tessellation || 16;
  16987. subdivisions = subdivisions || 1;
  16988. subdivisions = (subdivisions < 1) ? 1 : subdivisions;
  16989. var getCircleVector = function (i) {
  16990. var angle = (i * 2.0 * Math.PI / tessellation);
  16991. var dx = Math.cos(angle);
  16992. var dz = Math.sin(angle);
  16993. return new BABYLON.Vector3(dx, 0, dz);
  16994. };
  16995. var createCylinderCap = function (isTop) {
  16996. var radius = isTop ? radiusTop : radiusBottom;
  16997. if (radius == 0) {
  16998. return;
  16999. }
  17000. var vbase = positions.length / 3;
  17001. var offset = new BABYLON.Vector3(0, height / 2, 0);
  17002. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  17003. if (!isTop) {
  17004. offset.scaleInPlace(-1);
  17005. textureScale.x = -textureScale.x;
  17006. }
  17007. for (i = 0; i < tessellation; i++) {
  17008. var circleVector = getCircleVector(i);
  17009. var position = circleVector.scale(radius).add(offset);
  17010. var textureCoordinate = new BABYLON.Vector2(circleVector.x * textureScale.x + 0.5, circleVector.z * textureScale.y + 0.5);
  17011. positions.push(position.x, position.y, position.z);
  17012. uvs.push(textureCoordinate.x, textureCoordinate.y);
  17013. }
  17014. for (var i = 0; i < tessellation - 2; i++) {
  17015. if (!isTop) {
  17016. indices.push(vbase);
  17017. indices.push(vbase + (i + 2) % tessellation);
  17018. indices.push(vbase + (i + 1) % tessellation);
  17019. } else {
  17020. indices.push(vbase);
  17021. indices.push(vbase + (i + 1) % tessellation);
  17022. indices.push(vbase + (i + 2) % tessellation);
  17023. }
  17024. }
  17025. };
  17026. var base = new BABYLON.Vector3(0, -1, 0).scale(height / 2);
  17027. var offset = new BABYLON.Vector3(0, 1, 0).scale(height / subdivisions);
  17028. var stride = tessellation + 1;
  17029. for (var i = 0; i <= tessellation; i++) {
  17030. var circleVector = getCircleVector(i);
  17031. var textureCoordinate = new BABYLON.Vector2(i / tessellation, 0);
  17032. var position, radius = radiusBottom;
  17033. for (var s = 0; s <= subdivisions; s++) {
  17034. position = circleVector.scale(radius);
  17035. position.addInPlace(base.add(offset.scale(s)));
  17036. textureCoordinate.y += 1 / subdivisions;
  17037. radius += (radiusTop - radiusBottom) / subdivisions;
  17038. positions.push(position.x, position.y, position.z);
  17039. uvs.push(textureCoordinate.x, textureCoordinate.y);
  17040. }
  17041. }
  17042. subdivisions += 1;
  17043. for (var s = 0; s < subdivisions - 1; s++) {
  17044. for (var i = 0; i <= tessellation; i++) {
  17045. indices.push(i * subdivisions + s);
  17046. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  17047. indices.push(i * subdivisions + (s + 1));
  17048. indices.push(i * subdivisions + (s + 1));
  17049. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  17050. indices.push((i * subdivisions + (s + subdivisions + 1)) % (stride * subdivisions));
  17051. }
  17052. }
  17053. createCylinderCap(true);
  17054. createCylinderCap(false);
  17055. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  17056. var vertexData = new BABYLON.VertexData();
  17057. vertexData.indices = indices;
  17058. vertexData.positions = positions;
  17059. vertexData.normals = normals;
  17060. vertexData.uvs = uvs;
  17061. return vertexData;
  17062. };
  17063. VertexData.CreateTorus = function (diameter, thickness, tessellation) {
  17064. var indices = [];
  17065. var positions = [];
  17066. var normals = [];
  17067. var uvs = [];
  17068. diameter = diameter || 1;
  17069. thickness = thickness || 0.5;
  17070. tessellation = tessellation || 16;
  17071. var stride = tessellation + 1;
  17072. for (var i = 0; i <= tessellation; i++) {
  17073. var u = i / tessellation;
  17074. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  17075. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  17076. for (var j = 0; j <= tessellation; j++) {
  17077. var v = 1 - j / tessellation;
  17078. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  17079. var dx = Math.cos(innerAngle);
  17080. var dy = Math.sin(innerAngle);
  17081. var normal = new BABYLON.Vector3(dx, dy, 0);
  17082. var position = normal.scale(thickness / 2);
  17083. var textureCoordinate = new BABYLON.Vector2(u, v);
  17084. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  17085. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  17086. positions.push(position.x, position.y, position.z);
  17087. normals.push(normal.x, normal.y, normal.z);
  17088. uvs.push(textureCoordinate.x, textureCoordinate.y);
  17089. var nextI = (i + 1) % stride;
  17090. var nextJ = (j + 1) % stride;
  17091. indices.push(i * stride + j);
  17092. indices.push(i * stride + nextJ);
  17093. indices.push(nextI * stride + j);
  17094. indices.push(i * stride + nextJ);
  17095. indices.push(nextI * stride + nextJ);
  17096. indices.push(nextI * stride + j);
  17097. }
  17098. }
  17099. var vertexData = new BABYLON.VertexData();
  17100. vertexData.indices = indices;
  17101. vertexData.positions = positions;
  17102. vertexData.normals = normals;
  17103. vertexData.uvs = uvs;
  17104. return vertexData;
  17105. };
  17106. VertexData.CreateLines = function (points) {
  17107. var indices = [];
  17108. var positions = [];
  17109. for (var index = 0; index < points.length; index++) {
  17110. positions.push(points[index].x, points[index].y, points[index].z);
  17111. if (index > 0) {
  17112. indices.push(index - 1);
  17113. indices.push(index);
  17114. }
  17115. }
  17116. var vertexData = new BABYLON.VertexData();
  17117. vertexData.indices = indices;
  17118. vertexData.positions = positions;
  17119. return vertexData;
  17120. };
  17121. VertexData.CreateGround = function (width, height, subdivisions) {
  17122. var indices = [];
  17123. var positions = [];
  17124. var normals = [];
  17125. var uvs = [];
  17126. var row, col;
  17127. width = width || 1;
  17128. height = height || 1;
  17129. subdivisions = subdivisions || 1;
  17130. for (row = 0; row <= subdivisions; row++) {
  17131. for (col = 0; col <= subdivisions; col++) {
  17132. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  17133. var normal = new BABYLON.Vector3(0, 1.0, 0);
  17134. positions.push(position.x, position.y, position.z);
  17135. normals.push(normal.x, normal.y, normal.z);
  17136. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  17137. }
  17138. }
  17139. for (row = 0; row < subdivisions; row++) {
  17140. for (col = 0; col < subdivisions; col++) {
  17141. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  17142. indices.push(col + 1 + row * (subdivisions + 1));
  17143. indices.push(col + row * (subdivisions + 1));
  17144. indices.push(col + (row + 1) * (subdivisions + 1));
  17145. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  17146. indices.push(col + row * (subdivisions + 1));
  17147. }
  17148. }
  17149. var vertexData = new BABYLON.VertexData();
  17150. vertexData.indices = indices;
  17151. vertexData.positions = positions;
  17152. vertexData.normals = normals;
  17153. vertexData.uvs = uvs;
  17154. return vertexData;
  17155. };
  17156. VertexData.CreateTiledGround = function (xmin, zmin, xmax, zmax, subdivisions, precision) {
  17157. if (typeof subdivisions === "undefined") { subdivisions = { w: 1, h: 1 }; }
  17158. if (typeof precision === "undefined") { precision = { w: 1, h: 1 }; }
  17159. var indices = [];
  17160. var positions = [];
  17161. var normals = [];
  17162. var uvs = [];
  17163. var row, col, tileRow, tileCol;
  17164. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  17165. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  17166. precision.w = (precision.w < 1) ? 1 : precision.w;
  17167. precision.h = (precision.h < 1) ? 1 : precision.h;
  17168. var tileSize = {
  17169. 'w': (xmax - xmin) / subdivisions.w,
  17170. 'h': (zmax - zmin) / subdivisions.h
  17171. };
  17172. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  17173. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  17174. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  17175. }
  17176. }
  17177. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  17178. var base = positions.length / 3;
  17179. var rowLength = precision.w + 1;
  17180. for (row = 0; row < precision.h; row++) {
  17181. for (col = 0; col < precision.w; col++) {
  17182. var square = [
  17183. base + col + row * rowLength,
  17184. base + (col + 1) + row * rowLength,
  17185. base + (col + 1) + (row + 1) * rowLength,
  17186. base + col + (row + 1) * rowLength
  17187. ];
  17188. indices.push(square[1]);
  17189. indices.push(square[2]);
  17190. indices.push(square[3]);
  17191. indices.push(square[0]);
  17192. indices.push(square[1]);
  17193. indices.push(square[3]);
  17194. }
  17195. }
  17196. var position = BABYLON.Vector3.Zero();
  17197. var normal = new BABYLON.Vector3(0, 1.0, 0);
  17198. for (row = 0; row <= precision.h; row++) {
  17199. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  17200. for (col = 0; col <= precision.w; col++) {
  17201. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  17202. position.y = 0;
  17203. positions.push(position.x, position.y, position.z);
  17204. normals.push(normal.x, normal.y, normal.z);
  17205. uvs.push(col / precision.w, row / precision.h);
  17206. }
  17207. }
  17208. }
  17209. var vertexData = new BABYLON.VertexData();
  17210. vertexData.indices = indices;
  17211. vertexData.positions = positions;
  17212. vertexData.normals = normals;
  17213. vertexData.uvs = uvs;
  17214. return vertexData;
  17215. };
  17216. VertexData.CreateGroundFromHeightMap = function (width, height, subdivisions, minHeight, maxHeight, buffer, bufferWidth, bufferHeight) {
  17217. var indices = [];
  17218. var positions = [];
  17219. var normals = [];
  17220. var uvs = [];
  17221. var row, col;
  17222. for (row = 0; row <= subdivisions; row++) {
  17223. for (col = 0; col <= subdivisions; col++) {
  17224. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  17225. var heightMapX = (((position.x + width / 2) / width) * (bufferWidth - 1)) | 0;
  17226. var heightMapY = ((1.0 - (position.z + height / 2) / height) * (bufferHeight - 1)) | 0;
  17227. var pos = (heightMapX + heightMapY * bufferWidth) * 4;
  17228. var r = buffer[pos] / 255.0;
  17229. var g = buffer[pos + 1] / 255.0;
  17230. var b = buffer[pos + 2] / 255.0;
  17231. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  17232. position.y = minHeight + (maxHeight - minHeight) * gradient;
  17233. positions.push(position.x, position.y, position.z);
  17234. normals.push(0, 0, 0);
  17235. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  17236. }
  17237. }
  17238. for (row = 0; row < subdivisions; row++) {
  17239. for (col = 0; col < subdivisions; col++) {
  17240. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  17241. indices.push(col + 1 + row * (subdivisions + 1));
  17242. indices.push(col + row * (subdivisions + 1));
  17243. indices.push(col + (row + 1) * (subdivisions + 1));
  17244. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  17245. indices.push(col + row * (subdivisions + 1));
  17246. }
  17247. }
  17248. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  17249. var vertexData = new BABYLON.VertexData();
  17250. vertexData.indices = indices;
  17251. vertexData.positions = positions;
  17252. vertexData.normals = normals;
  17253. vertexData.uvs = uvs;
  17254. return vertexData;
  17255. };
  17256. VertexData.CreatePlane = function (size) {
  17257. var indices = [];
  17258. var positions = [];
  17259. var normals = [];
  17260. var uvs = [];
  17261. size = size || 1;
  17262. var halfSize = size / 2.0;
  17263. positions.push(-halfSize, -halfSize, 0);
  17264. normals.push(0, 0, -1.0);
  17265. uvs.push(0.0, 0.0);
  17266. positions.push(halfSize, -halfSize, 0);
  17267. normals.push(0, 0, -1.0);
  17268. uvs.push(1.0, 0.0);
  17269. positions.push(halfSize, halfSize, 0);
  17270. normals.push(0, 0, -1.0);
  17271. uvs.push(1.0, 1.0);
  17272. positions.push(-halfSize, halfSize, 0);
  17273. normals.push(0, 0, -1.0);
  17274. uvs.push(0.0, 1.0);
  17275. indices.push(0);
  17276. indices.push(1);
  17277. indices.push(2);
  17278. indices.push(0);
  17279. indices.push(2);
  17280. indices.push(3);
  17281. var vertexData = new BABYLON.VertexData();
  17282. vertexData.indices = indices;
  17283. vertexData.positions = positions;
  17284. vertexData.normals = normals;
  17285. vertexData.uvs = uvs;
  17286. return vertexData;
  17287. };
  17288. VertexData.CreateTorusKnot = function (radius, tube, radialSegments, tubularSegments, p, q) {
  17289. var indices = [];
  17290. var positions = [];
  17291. var normals = [];
  17292. var uvs = [];
  17293. radius = radius || 2;
  17294. tube = tube || 0.5;
  17295. radialSegments = radialSegments || 32;
  17296. tubularSegments = tubularSegments || 32;
  17297. p = p || 2;
  17298. q = q || 3;
  17299. var getPos = function (angle) {
  17300. var cu = Math.cos(angle);
  17301. var su = Math.sin(angle);
  17302. var quOverP = q / p * angle;
  17303. var cs = Math.cos(quOverP);
  17304. var tx = radius * (2 + cs) * 0.5 * cu;
  17305. var ty = radius * (2 + cs) * su * 0.5;
  17306. var tz = radius * Math.sin(quOverP) * 0.5;
  17307. return new BABYLON.Vector3(tx, ty, tz);
  17308. };
  17309. for (var i = 0; i <= radialSegments; i++) {
  17310. var modI = i % radialSegments;
  17311. var u = modI / radialSegments * 2 * p * Math.PI;
  17312. var p1 = getPos(u);
  17313. var p2 = getPos(u + 0.01);
  17314. var tang = p2.subtract(p1);
  17315. var n = p2.add(p1);
  17316. var bitan = BABYLON.Vector3.Cross(tang, n);
  17317. n = BABYLON.Vector3.Cross(bitan, tang);
  17318. bitan.normalize();
  17319. n.normalize();
  17320. for (var j = 0; j < tubularSegments; j++) {
  17321. var modJ = j % tubularSegments;
  17322. var v = modJ / tubularSegments * 2 * Math.PI;
  17323. var cx = -tube * Math.cos(v);
  17324. var cy = tube * Math.sin(v);
  17325. positions.push(p1.x + cx * n.x + cy * bitan.x);
  17326. positions.push(p1.y + cx * n.y + cy * bitan.y);
  17327. positions.push(p1.z + cx * n.z + cy * bitan.z);
  17328. uvs.push(i / radialSegments);
  17329. uvs.push(j / tubularSegments);
  17330. }
  17331. }
  17332. for (i = 0; i < radialSegments; i++) {
  17333. for (j = 0; j < tubularSegments; j++) {
  17334. var jNext = (j + 1) % tubularSegments;
  17335. var a = i * tubularSegments + j;
  17336. var b = (i + 1) * tubularSegments + j;
  17337. var c = (i + 1) * tubularSegments + jNext;
  17338. var d = i * tubularSegments + jNext;
  17339. indices.push(d);
  17340. indices.push(b);
  17341. indices.push(a);
  17342. indices.push(d);
  17343. indices.push(c);
  17344. indices.push(b);
  17345. }
  17346. }
  17347. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  17348. var vertexData = new BABYLON.VertexData();
  17349. vertexData.indices = indices;
  17350. vertexData.positions = positions;
  17351. vertexData.normals = normals;
  17352. vertexData.uvs = uvs;
  17353. return vertexData;
  17354. };
  17355. VertexData.ComputeNormals = function (positions, indices, normals) {
  17356. var positionVectors = [];
  17357. var facesOfVertices = [];
  17358. var index;
  17359. for (index = 0; index < positions.length; index += 3) {
  17360. var vector3 = new BABYLON.Vector3(positions[index], positions[index + 1], positions[index + 2]);
  17361. positionVectors.push(vector3);
  17362. facesOfVertices.push([]);
  17363. }
  17364. var facesNormals = [];
  17365. for (index = 0; index < indices.length / 3; index++) {
  17366. var i1 = indices[index * 3];
  17367. var i2 = indices[index * 3 + 1];
  17368. var i3 = indices[index * 3 + 2];
  17369. var p1 = positionVectors[i1];
  17370. var p2 = positionVectors[i2];
  17371. var p3 = positionVectors[i3];
  17372. var p1p2 = p1.subtract(p2);
  17373. var p3p2 = p3.subtract(p2);
  17374. facesNormals[index] = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  17375. facesOfVertices[i1].push(index);
  17376. facesOfVertices[i2].push(index);
  17377. facesOfVertices[i3].push(index);
  17378. }
  17379. for (index = 0; index < positionVectors.length; index++) {
  17380. var faces = facesOfVertices[index];
  17381. var normal = BABYLON.Vector3.Zero();
  17382. for (var faceIndex = 0; faceIndex < faces.length; faceIndex++) {
  17383. normal.addInPlace(facesNormals[faces[faceIndex]]);
  17384. }
  17385. normal = BABYLON.Vector3.Normalize(normal.scale(1.0 / faces.length));
  17386. normals[index * 3] = normal.x;
  17387. normals[index * 3 + 1] = normal.y;
  17388. normals[index * 3 + 2] = normal.z;
  17389. }
  17390. };
  17391. return VertexData;
  17392. })();
  17393. BABYLON.VertexData = VertexData;
  17394. })(BABYLON || (BABYLON = {}));
  17395. var __extends = this.__extends || function (d, b) {
  17396. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  17397. function __() { this.constructor = d; }
  17398. __.prototype = b.prototype;
  17399. d.prototype = new __();
  17400. };
  17401. var BABYLON;
  17402. (function (BABYLON) {
  17403. var buildCamera = function (that, name) {
  17404. that._leftCamera.isIntermediate = true;
  17405. that.subCameras.push(that._leftCamera);
  17406. that.subCameras.push(that._rightCamera);
  17407. that._leftTexture = new BABYLON.PassPostProcess(name + "_leftTexture", 1.0, that._leftCamera);
  17408. that._anaglyphPostProcess = new BABYLON.AnaglyphPostProcess(name + "_anaglyph", 1.0, that._rightCamera);
  17409. that._anaglyphPostProcess.onApply = function (effect) {
  17410. effect.setTextureFromPostProcess("leftSampler", that._leftTexture);
  17411. };
  17412. that._update();
  17413. };
  17414. var AnaglyphArcRotateCamera = (function (_super) {
  17415. __extends(AnaglyphArcRotateCamera, _super);
  17416. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, eyeSpace, scene) {
  17417. _super.call(this, name, alpha, beta, radius, target, scene);
  17418. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  17419. this._leftCamera = new BABYLON.ArcRotateCamera(name + "_left", alpha - this._eyeSpace, beta, radius, target, scene);
  17420. this._rightCamera = new BABYLON.ArcRotateCamera(name + "_right", alpha + this._eyeSpace, beta, radius, target, scene);
  17421. buildCamera(this, name);
  17422. }
  17423. AnaglyphArcRotateCamera.prototype._update = function () {
  17424. this._updateCamera(this._leftCamera);
  17425. this._updateCamera(this._rightCamera);
  17426. this._leftCamera.alpha = this.alpha - this._eyeSpace;
  17427. this._rightCamera.alpha = this.alpha + this._eyeSpace;
  17428. _super.prototype._update.call(this);
  17429. };
  17430. AnaglyphArcRotateCamera.prototype._updateCamera = function (camera) {
  17431. camera.beta = this.beta;
  17432. camera.radius = this.radius;
  17433. camera.minZ = this.minZ;
  17434. camera.maxZ = this.maxZ;
  17435. camera.fov = this.fov;
  17436. camera.target = this.target;
  17437. };
  17438. return AnaglyphArcRotateCamera;
  17439. })(BABYLON.ArcRotateCamera);
  17440. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  17441. var AnaglyphFreeCamera = (function (_super) {
  17442. __extends(AnaglyphFreeCamera, _super);
  17443. function AnaglyphFreeCamera(name, position, eyeSpace, scene) {
  17444. _super.call(this, name, position, scene);
  17445. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  17446. this._transformMatrix = new BABYLON.Matrix();
  17447. this._leftCamera = new BABYLON.FreeCamera(name + "_left", position.clone(), scene);
  17448. this._rightCamera = new BABYLON.FreeCamera(name + "_right", position.clone(), scene);
  17449. buildCamera(this, name);
  17450. }
  17451. AnaglyphFreeCamera.prototype._getSubCameraPosition = function (eyeSpace, result) {
  17452. var target = this.getTarget();
  17453. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(eyeSpace), this._transformMatrix);
  17454. this._transformMatrix = this._transformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  17455. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._transformMatrix, result);
  17456. };
  17457. AnaglyphFreeCamera.prototype._update = function () {
  17458. this._getSubCameraPosition(-this._eyeSpace, this._leftCamera.position);
  17459. this._getSubCameraPosition(this._eyeSpace, this._rightCamera.position);
  17460. this._updateCamera(this._leftCamera);
  17461. this._updateCamera(this._rightCamera);
  17462. _super.prototype._update.call(this);
  17463. };
  17464. AnaglyphFreeCamera.prototype._updateCamera = function (camera) {
  17465. camera.minZ = this.minZ;
  17466. camera.maxZ = this.maxZ;
  17467. camera.fov = this.fov;
  17468. camera.viewport = this.viewport;
  17469. camera.setTarget(this.getTarget());
  17470. };
  17471. return AnaglyphFreeCamera;
  17472. })(BABYLON.FreeCamera);
  17473. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  17474. })(BABYLON || (BABYLON = {}));
  17475. var __extends = this.__extends || function (d, b) {
  17476. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  17477. function __() { this.constructor = d; }
  17478. __.prototype = b.prototype;
  17479. d.prototype = new __();
  17480. };
  17481. var BABYLON;
  17482. (function (BABYLON) {
  17483. var AnaglyphPostProcess = (function (_super) {
  17484. __extends(AnaglyphPostProcess, _super);
  17485. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  17486. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  17487. }
  17488. return AnaglyphPostProcess;
  17489. })(BABYLON.PostProcess);
  17490. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  17491. })(BABYLON || (BABYLON = {}));
  17492. var BABYLON;
  17493. (function (BABYLON) {
  17494. var Tags = (function () {
  17495. function Tags() {
  17496. }
  17497. Tags.EnableFor = function (obj) {
  17498. obj._tags = obj._tags || {};
  17499. obj.hasTags = function () {
  17500. return Tags.HasTags(obj);
  17501. };
  17502. obj.addTags = function (tagsString) {
  17503. return Tags.AddTagsTo(obj, tagsString);
  17504. };
  17505. obj.removeTags = function (tagsString) {
  17506. return Tags.RemoveTagsFrom(obj, tagsString);
  17507. };
  17508. obj.matchesTagsQuery = function (tagsQuery) {
  17509. return Tags.MatchesQuery(obj, tagsQuery);
  17510. };
  17511. };
  17512. Tags.DisableFor = function (obj) {
  17513. delete obj._tags;
  17514. delete obj.hasTags;
  17515. delete obj.addTags;
  17516. delete obj.removeTags;
  17517. delete obj.matchesTagsQuery;
  17518. };
  17519. Tags.HasTags = function (obj) {
  17520. if (!obj._tags) {
  17521. return false;
  17522. }
  17523. return !BABYLON.Tools.IsEmpty(obj._tags);
  17524. };
  17525. Tags.GetTags = function (obj) {
  17526. if (!obj._tags) {
  17527. return null;
  17528. }
  17529. return obj._tags;
  17530. };
  17531. Tags.AddTagsTo = function (obj, tagsString) {
  17532. if (!tagsString) {
  17533. return;
  17534. }
  17535. var tags = tagsString.split(" ");
  17536. for (var t in tags) {
  17537. Tags._AddTagTo(obj, tags[t]);
  17538. }
  17539. };
  17540. Tags._AddTagTo = function (obj, tag) {
  17541. tag = tag.trim();
  17542. if (tag === "" || tag === "true" || tag === "false") {
  17543. return;
  17544. }
  17545. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  17546. return;
  17547. }
  17548. Tags.EnableFor(obj);
  17549. obj._tags[tag] = true;
  17550. };
  17551. Tags.RemoveTagsFrom = function (obj, tagsString) {
  17552. if (!Tags.HasTags(obj)) {
  17553. return;
  17554. }
  17555. var tags = tagsString.split(" ");
  17556. for (var t in tags) {
  17557. Tags._RemoveTagFrom(obj, tags[t]);
  17558. }
  17559. };
  17560. Tags._RemoveTagFrom = function (obj, tag) {
  17561. delete obj._tags[tag];
  17562. };
  17563. Tags.MatchesQuery = function (obj, tagsQuery) {
  17564. if (tagsQuery === undefined) {
  17565. return true;
  17566. }
  17567. if (tagsQuery === "") {
  17568. return Tags.HasTags(obj);
  17569. }
  17570. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) {
  17571. return Tags.HasTags(obj) && obj._tags[r];
  17572. });
  17573. };
  17574. return Tags;
  17575. })();
  17576. BABYLON.Tags = Tags;
  17577. })(BABYLON || (BABYLON = {}));
  17578. var BABYLON;
  17579. (function (BABYLON) {
  17580. (function (Internals) {
  17581. var AndOrNotEvaluator = (function () {
  17582. function AndOrNotEvaluator() {
  17583. }
  17584. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  17585. if (!query.match(/\([^\(\)]*\)/g)) {
  17586. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  17587. } else {
  17588. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  17589. r = r.slice(1, r.length - 1);
  17590. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  17591. });
  17592. }
  17593. if (query === "true") {
  17594. return true;
  17595. }
  17596. if (query === "false") {
  17597. return false;
  17598. }
  17599. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  17600. };
  17601. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  17602. evaluateCallback = evaluateCallback || (function (r) {
  17603. return r === "true" ? true : false;
  17604. });
  17605. var result;
  17606. var or = parenthesisContent.split("||");
  17607. for (var i in or) {
  17608. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  17609. var and = ori.split("&&");
  17610. if (and.length > 1) {
  17611. for (var j = 0; j < and.length; ++j) {
  17612. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  17613. if (andj !== "true" && andj !== "false") {
  17614. if (andj[0] === "!") {
  17615. result = !evaluateCallback(andj.substring(1));
  17616. } else {
  17617. result = evaluateCallback(andj);
  17618. }
  17619. } else {
  17620. result = andj === "true" ? true : false;
  17621. }
  17622. if (!result) {
  17623. ori = "false";
  17624. break;
  17625. }
  17626. }
  17627. }
  17628. if (result || ori === "true") {
  17629. result = true;
  17630. break;
  17631. }
  17632. if (ori !== "true" && ori !== "false") {
  17633. if (ori[0] === "!") {
  17634. result = !evaluateCallback(ori.substring(1));
  17635. } else {
  17636. result = evaluateCallback(ori);
  17637. }
  17638. } else {
  17639. result = ori === "true" ? true : false;
  17640. }
  17641. }
  17642. return result ? "true" : "false";
  17643. };
  17644. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  17645. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  17646. r = r.replace(/[\s]/g, function () {
  17647. return "";
  17648. });
  17649. return r.length % 2 ? "!" : "";
  17650. });
  17651. booleanString = booleanString.trim();
  17652. if (booleanString === "!true") {
  17653. booleanString = "false";
  17654. } else if (booleanString === "!false") {
  17655. booleanString = "true";
  17656. }
  17657. return booleanString;
  17658. };
  17659. return AndOrNotEvaluator;
  17660. })();
  17661. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  17662. })(BABYLON.Internals || (BABYLON.Internals = {}));
  17663. var Internals = BABYLON.Internals;
  17664. })(BABYLON || (BABYLON = {}));
  17665. var BABYLON;
  17666. (function (BABYLON) {
  17667. var PostProcessRenderPass = (function () {
  17668. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  17669. this._enabled = true;
  17670. this._refCount = 0;
  17671. this._name = name;
  17672. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  17673. this.setRenderList(renderList);
  17674. this._renderTexture.onBeforeRender = beforeRender;
  17675. this._renderTexture.onAfterRender = afterRender;
  17676. this._scene = scene;
  17677. }
  17678. PostProcessRenderPass.prototype._incRefCount = function () {
  17679. if (this._refCount === 0) {
  17680. this._scene.customRenderTargets.push(this._renderTexture);
  17681. }
  17682. return ++this._refCount;
  17683. };
  17684. PostProcessRenderPass.prototype._decRefCount = function () {
  17685. this._refCount--;
  17686. if (this._refCount <= 0) {
  17687. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  17688. }
  17689. return this._refCount;
  17690. };
  17691. PostProcessRenderPass.prototype._update = function () {
  17692. this.setRenderList(this._renderList);
  17693. };
  17694. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  17695. this._renderTexture.renderList = renderList;
  17696. };
  17697. PostProcessRenderPass.prototype.getRenderTexture = function () {
  17698. return this._renderTexture;
  17699. };
  17700. return PostProcessRenderPass;
  17701. })();
  17702. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  17703. })(BABYLON || (BABYLON = {}));
  17704. var BABYLON;
  17705. (function (BABYLON) {
  17706. var PostProcessRenderEffect = (function () {
  17707. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  17708. this._engine = engine;
  17709. this._name = name;
  17710. this._singleInstance = singleInstance || true;
  17711. this._getPostProcess = getPostProcess;
  17712. this._cameras = [];
  17713. this._postProcesses = [];
  17714. this._indicesForCamera = [];
  17715. this._renderPasses = [];
  17716. this._renderEffectAsPasses = [];
  17717. }
  17718. PostProcessRenderEffect.prototype._update = function () {
  17719. for (var renderPassName in this._renderPasses) {
  17720. this._renderPasses[renderPassName]._update();
  17721. }
  17722. };
  17723. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  17724. this._renderPasses[renderPass._name] = renderPass;
  17725. this._linkParameters();
  17726. };
  17727. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  17728. delete this._renderPasses[renderPass._name];
  17729. this._linkParameters();
  17730. };
  17731. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  17732. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  17733. this._linkParameters();
  17734. };
  17735. PostProcessRenderEffect.prototype.getPass = function (passName) {
  17736. for (var renderPassName in this._renderPasses) {
  17737. if (renderPassName === passName) {
  17738. return this._renderPasses[passName];
  17739. }
  17740. }
  17741. };
  17742. PostProcessRenderEffect.prototype.emptyPasses = function () {
  17743. this._renderPasses.length = 0;
  17744. this._linkParameters();
  17745. };
  17746. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  17747. var cameraKey;
  17748. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  17749. for (var i = 0; i < _cam.length; i++) {
  17750. var camera = _cam[i];
  17751. var cameraName = camera.name;
  17752. if (this._singleInstance) {
  17753. cameraKey = 0;
  17754. } else {
  17755. cameraKey = cameraName;
  17756. }
  17757. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  17758. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  17759. if (!this._indicesForCamera[cameraName]) {
  17760. this._indicesForCamera[cameraName] = [];
  17761. }
  17762. this._indicesForCamera[cameraName].push(index);
  17763. if (this._cameras.indexOf(camera) === -1) {
  17764. this._cameras[cameraName] = camera;
  17765. }
  17766. for (var passName in this._renderPasses) {
  17767. this._renderPasses[passName]._incRefCount();
  17768. }
  17769. }
  17770. this._linkParameters();
  17771. };
  17772. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  17773. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  17774. for (var i = 0; i < _cam.length; i++) {
  17775. var camera = _cam[i];
  17776. var cameraName = camera.name;
  17777. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  17778. var index = this._cameras.indexOf(cameraName);
  17779. this._indicesForCamera.splice(index, 1);
  17780. this._cameras.splice(index, 1);
  17781. for (var passName in this._renderPasses) {
  17782. this._renderPasses[passName]._decRefCount();
  17783. }
  17784. }
  17785. };
  17786. PostProcessRenderEffect.prototype._enable = function (cameras) {
  17787. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  17788. for (var i = 0; i < _cam.length; i++) {
  17789. var camera = _cam[i];
  17790. var cameraName = camera.name;
  17791. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  17792. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  17793. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  17794. }
  17795. }
  17796. for (var passName in this._renderPasses) {
  17797. this._renderPasses[passName]._incRefCount();
  17798. }
  17799. }
  17800. };
  17801. PostProcessRenderEffect.prototype._disable = function (cameras) {
  17802. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  17803. for (var i = 0; i < _cam.length; i++) {
  17804. var camera = _cam[i];
  17805. var cameraName = camera.Name;
  17806. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  17807. for (var passName in this._renderPasses) {
  17808. this._renderPasses[passName]._decRefCount();
  17809. }
  17810. }
  17811. };
  17812. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  17813. if (this._singleInstance) {
  17814. return this._postProcesses[0];
  17815. } else {
  17816. return this._postProcesses[camera.name];
  17817. }
  17818. };
  17819. PostProcessRenderEffect.prototype._linkParameters = function () {
  17820. var _this = this;
  17821. for (var index in this._postProcesses) {
  17822. if (this.applyParameters) {
  17823. this.applyParameters(this._postProcesses[index]);
  17824. }
  17825. this._postProcesses[index].onBeforeRender = function (effect) {
  17826. _this._linkTextures(effect);
  17827. };
  17828. }
  17829. };
  17830. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  17831. for (var renderPassName in this._renderPasses) {
  17832. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  17833. }
  17834. for (var renderEffectName in this._renderEffectAsPasses) {
  17835. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  17836. }
  17837. };
  17838. return PostProcessRenderEffect;
  17839. })();
  17840. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  17841. })(BABYLON || (BABYLON = {}));
  17842. var BABYLON;
  17843. (function (BABYLON) {
  17844. var PostProcessRenderPipeline = (function () {
  17845. function PostProcessRenderPipeline(engine, name) {
  17846. this._engine = engine;
  17847. this._name = name;
  17848. this._renderEffects = [];
  17849. this._renderEffectsForIsolatedPass = [];
  17850. this._cameras = [];
  17851. }
  17852. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  17853. this._renderEffects[renderEffect._name] = renderEffect;
  17854. };
  17855. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  17856. var renderEffects = this._renderEffects[renderEffectName];
  17857. if (!renderEffects) {
  17858. return;
  17859. }
  17860. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  17861. };
  17862. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  17863. var renderEffects = this._renderEffects[renderEffectName];
  17864. if (!renderEffects) {
  17865. return;
  17866. }
  17867. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  17868. };
  17869. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  17870. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  17871. var indicesToDelete = [];
  17872. for (var i = 0; i < _cam.length; i++) {
  17873. var camera = _cam[i];
  17874. var cameraName = camera.name;
  17875. if (this._cameras.indexOf(camera) === -1) {
  17876. this._cameras[cameraName] = camera;
  17877. } else if (unique) {
  17878. indicesToDelete.push(i);
  17879. }
  17880. }
  17881. for (var i = 0; i < indicesToDelete.length; i++) {
  17882. cameras.splice(indicesToDelete[i], 1);
  17883. }
  17884. for (var renderEffectName in this._renderEffects) {
  17885. this._renderEffects[renderEffectName]._attachCameras(_cam);
  17886. }
  17887. };
  17888. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  17889. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  17890. for (var renderEffectName in this._renderEffects) {
  17891. this._renderEffects[renderEffectName]._detachCameras(_cam);
  17892. }
  17893. for (var i = 0; i < _cam.length; i++) {
  17894. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  17895. }
  17896. };
  17897. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  17898. var _this = this;
  17899. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  17900. var pass = null;
  17901. for (var renderEffectName in this._renderEffects) {
  17902. pass = this._renderEffects[renderEffectName].getPass(passName);
  17903. if (pass != null) {
  17904. break;
  17905. }
  17906. }
  17907. if (pass === null) {
  17908. return;
  17909. }
  17910. for (var renderEffectName in this._renderEffects) {
  17911. this._renderEffects[renderEffectName]._disable(_cam);
  17912. }
  17913. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  17914. for (var i = 0; i < _cam.length; i++) {
  17915. var camera = _cam[i];
  17916. var cameraName = camera.name;
  17917. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () {
  17918. return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true);
  17919. });
  17920. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  17921. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  17922. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  17923. }
  17924. };
  17925. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  17926. var _this = this;
  17927. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  17928. for (var i = 0; i < _cam.length; i++) {
  17929. var camera = _cam[i];
  17930. var cameraName = camera.name;
  17931. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () {
  17932. return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true);
  17933. });
  17934. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  17935. }
  17936. for (var renderEffectName in this._renderEffects) {
  17937. this._renderEffects[renderEffectName]._enable(_cam);
  17938. }
  17939. };
  17940. PostProcessRenderPipeline.prototype._update = function () {
  17941. for (var renderEffectName in this._renderEffects) {
  17942. this._renderEffects[renderEffectName]._update();
  17943. }
  17944. for (var i = 0; i < this._cameras.length; i++) {
  17945. var cameraName = this._cameras[i].name;
  17946. if (this._renderEffectsForIsolatedPass[cameraName]) {
  17947. this._renderEffectsForIsolatedPass[cameraName]._update();
  17948. }
  17949. }
  17950. };
  17951. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  17952. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  17953. return PostProcessRenderPipeline;
  17954. })();
  17955. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  17956. })(BABYLON || (BABYLON = {}));
  17957. var BABYLON;
  17958. (function (BABYLON) {
  17959. var PostProcessRenderPipelineManager = (function () {
  17960. function PostProcessRenderPipelineManager() {
  17961. this._renderPipelines = new Array();
  17962. }
  17963. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  17964. this._renderPipelines[renderPipeline._name] = renderPipeline;
  17965. };
  17966. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  17967. var renderPipeline = this._renderPipelines[renderPipelineName];
  17968. if (!renderPipeline) {
  17969. return;
  17970. }
  17971. renderPipeline._attachCameras(cameras, unique);
  17972. };
  17973. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  17974. var renderPipeline = this._renderPipelines[renderPipelineName];
  17975. if (!renderPipeline) {
  17976. return;
  17977. }
  17978. renderPipeline._detachCameras(cameras);
  17979. };
  17980. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  17981. var renderPipeline = this._renderPipelines[renderPipelineName];
  17982. if (!renderPipeline) {
  17983. return;
  17984. }
  17985. renderPipeline._enableEffect(renderEffectName, cameras);
  17986. };
  17987. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  17988. var renderPipeline = this._renderPipelines[renderPipelineName];
  17989. if (!renderPipeline) {
  17990. return;
  17991. }
  17992. renderPipeline._disableEffect(renderEffectName, cameras);
  17993. };
  17994. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  17995. var renderPipeline = this._renderPipelines[renderPipelineName];
  17996. if (!renderPipeline) {
  17997. return;
  17998. }
  17999. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  18000. };
  18001. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  18002. var renderPipeline = this._renderPipelines[renderPipelineName];
  18003. if (!renderPipeline) {
  18004. return;
  18005. }
  18006. renderPipeline._disableDisplayOnlyPass(cameras);
  18007. };
  18008. PostProcessRenderPipelineManager.prototype.update = function () {
  18009. for (var renderPipelineName in this._renderPipelines) {
  18010. this._renderPipelines[renderPipelineName]._update();
  18011. }
  18012. };
  18013. return PostProcessRenderPipelineManager;
  18014. })();
  18015. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  18016. })(BABYLON || (BABYLON = {}));
  18017. var __extends = this.__extends || function (d, b) {
  18018. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  18019. function __() { this.constructor = d; }
  18020. __.prototype = b.prototype;
  18021. d.prototype = new __();
  18022. };
  18023. var BABYLON;
  18024. (function (BABYLON) {
  18025. var DisplayPassPostProcess = (function (_super) {
  18026. __extends(DisplayPassPostProcess, _super);
  18027. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  18028. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  18029. }
  18030. return DisplayPassPostProcess;
  18031. })(BABYLON.PostProcess);
  18032. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  18033. })(BABYLON || (BABYLON = {}));
  18034. var BABYLON;
  18035. (function (BABYLON) {
  18036. var BoundingBoxRenderer = (function () {
  18037. function BoundingBoxRenderer(scene) {
  18038. this.frontColor = new BABYLON.Color3(1, 1, 1);
  18039. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  18040. this.showBackLines = true;
  18041. this.renderList = new BABYLON.SmartArray(32);
  18042. this._scene = scene;
  18043. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  18044. attributes: ["position"],
  18045. uniforms: ["worldViewProjection", "color"]
  18046. });
  18047. var engine = this._scene.getEngine();
  18048. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  18049. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  18050. 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]);
  18051. }
  18052. BoundingBoxRenderer.prototype.reset = function () {
  18053. this.renderList.reset();
  18054. };
  18055. BoundingBoxRenderer.prototype.render = function () {
  18056. if (this.renderList.length == 0 || !this._colorShader.isReady()) {
  18057. return;
  18058. }
  18059. var engine = this._scene.getEngine();
  18060. engine.setDepthWrite(false);
  18061. this._colorShader._preBind();
  18062. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  18063. var boundingBox = this.renderList.data[boundingBoxIndex];
  18064. var min = boundingBox.minimum;
  18065. var max = boundingBox.maximum;
  18066. var diff = max.subtract(min);
  18067. var median = min.add(diff.scale(0.5));
  18068. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z).multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z)).multiply(boundingBox.getWorldMatrix());
  18069. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  18070. if (this.showBackLines) {
  18071. engine.setDepthFunctionToGreaterOrEqual();
  18072. this._colorShader.setColor4("color", this.backColor.toColor4());
  18073. this._colorShader.bind(worldMatrix);
  18074. engine.draw(false, 0, 24);
  18075. }
  18076. engine.setDepthFunctionToLess();
  18077. this._colorShader.setColor4("color", this.frontColor.toColor4());
  18078. this._colorShader.bind(worldMatrix);
  18079. engine.draw(false, 0, 24);
  18080. }
  18081. this._colorShader.unbind();
  18082. engine.setDepthFunctionToLessOrEqual();
  18083. engine.setDepthWrite(true);
  18084. };
  18085. BoundingBoxRenderer.prototype.dispose = function () {
  18086. this._colorShader.dispose();
  18087. this._vb.dispose();
  18088. this._scene.getEngine()._releaseBuffer(this._ib);
  18089. };
  18090. return BoundingBoxRenderer;
  18091. })();
  18092. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  18093. })(BABYLON || (BABYLON = {}));
  18094. /**
  18095. * Based on jsTGALoader - Javascript loader for TGA file
  18096. * By Vincent Thibault
  18097. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  18098. */
  18099. var BABYLON;
  18100. (function (BABYLON) {
  18101. (function (Internals) {
  18102. var TGATools = (function () {
  18103. function TGATools() {
  18104. }
  18105. TGATools.GetTGAHeader = function (data) {
  18106. var offset = 0;
  18107. var header = {
  18108. id_length: data[offset++],
  18109. colormap_type: data[offset++],
  18110. image_type: data[offset++],
  18111. colormap_index: data[offset++] | data[offset++] << 8,
  18112. colormap_length: data[offset++] | data[offset++] << 8,
  18113. colormap_size: data[offset++],
  18114. origin: [
  18115. data[offset++] | data[offset++] << 8,
  18116. data[offset++] | data[offset++] << 8
  18117. ],
  18118. width: data[offset++] | data[offset++] << 8,
  18119. height: data[offset++] | data[offset++] << 8,
  18120. pixel_size: data[offset++],
  18121. flags: data[offset++]
  18122. };
  18123. return header;
  18124. };
  18125. TGATools.UploadContent = function (gl, data) {
  18126. if (data.length < 19) {
  18127. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  18128. return;
  18129. }
  18130. var offset = 18;
  18131. var header = TGATools.GetTGAHeader(data);
  18132. if (header.id_length + offset > data.length) {
  18133. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  18134. return;
  18135. }
  18136. offset += header.id_length;
  18137. var use_rle = false;
  18138. var use_pal = false;
  18139. var use_rgb = false;
  18140. var use_grey = false;
  18141. switch (header.image_type) {
  18142. case TGATools._TYPE_RLE_INDEXED:
  18143. use_rle = true;
  18144. case TGATools._TYPE_INDEXED:
  18145. use_pal = true;
  18146. break;
  18147. case TGATools._TYPE_RLE_RGB:
  18148. use_rle = true;
  18149. case TGATools._TYPE_RGB:
  18150. use_rgb = true;
  18151. break;
  18152. case TGATools._TYPE_RLE_GREY:
  18153. use_rle = true;
  18154. case TGATools._TYPE_GREY:
  18155. use_grey = true;
  18156. break;
  18157. }
  18158. var pixel_data;
  18159. var numAlphaBits = header.flags & 0xf;
  18160. var pixel_size = header.pixel_size >> 3;
  18161. var pixel_total = header.width * header.height * pixel_size;
  18162. var palettes;
  18163. if (use_pal) {
  18164. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  18165. }
  18166. if (use_rle) {
  18167. pixel_data = new Uint8Array(pixel_total);
  18168. var c, count, i;
  18169. var localOffset = 0;
  18170. var pixels = new Uint8Array(pixel_size);
  18171. while (offset < pixel_total && localOffset < pixel_total) {
  18172. c = data[offset++];
  18173. count = (c & 0x7f) + 1;
  18174. if (c & 0x80) {
  18175. for (i = 0; i < pixel_size; ++i) {
  18176. pixels[i] = data[offset++];
  18177. }
  18178. for (i = 0; i < count; ++i) {
  18179. pixel_data.set(pixels, localOffset + i * pixel_size);
  18180. }
  18181. localOffset += pixel_size * count;
  18182. } else {
  18183. count *= pixel_size;
  18184. for (i = 0; i < count; ++i) {
  18185. pixel_data[localOffset + i] = data[offset++];
  18186. }
  18187. localOffset += count;
  18188. }
  18189. }
  18190. } else {
  18191. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  18192. }
  18193. var x_start, y_start, x_step, y_step, y_end, x_end;
  18194. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  18195. default:
  18196. case TGATools._ORIGIN_UL:
  18197. x_start = 0;
  18198. x_step = 1;
  18199. x_end = header.width;
  18200. y_start = 0;
  18201. y_step = 1;
  18202. y_end = header.height;
  18203. break;
  18204. case TGATools._ORIGIN_BL:
  18205. x_start = 0;
  18206. x_step = 1;
  18207. x_end = header.width;
  18208. y_start = header.height - 1;
  18209. y_step = -1;
  18210. y_end = -1;
  18211. break;
  18212. case TGATools._ORIGIN_UR:
  18213. x_start = header.width - 1;
  18214. x_step = -1;
  18215. x_end = -1;
  18216. y_start = 0;
  18217. y_step = 1;
  18218. y_end = header.height;
  18219. break;
  18220. case TGATools._ORIGIN_BR:
  18221. x_start = header.width - 1;
  18222. x_step = -1;
  18223. x_end = -1;
  18224. y_start = header.height - 1;
  18225. y_step = -1;
  18226. y_end = -1;
  18227. break;
  18228. }
  18229. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  18230. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  18231. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  18232. };
  18233. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  18234. var image = pixel_data, colormap = palettes;
  18235. var width = header.width, height = header.height;
  18236. var color, i = 0, x, y;
  18237. var imageData = new Uint8Array(width * height * 4);
  18238. for (y = y_start; y !== y_end; y += y_step) {
  18239. for (x = x_start; x !== x_end; x += x_step, i++) {
  18240. color = image[i];
  18241. imageData[(x + width * y) * 4 + 3] = 255;
  18242. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  18243. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  18244. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  18245. }
  18246. }
  18247. return imageData;
  18248. };
  18249. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  18250. var image = pixel_data;
  18251. var width = header.width, height = header.height;
  18252. var color, i = 0, x, y;
  18253. var imageData = new Uint8Array(width * height * 4);
  18254. for (y = y_start; y !== y_end; y += y_step) {
  18255. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  18256. color = image[i + 0] + (image[i + 1] << 8);
  18257. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  18258. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  18259. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  18260. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  18261. }
  18262. }
  18263. return imageData;
  18264. };
  18265. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  18266. var image = pixel_data;
  18267. var width = header.width, height = header.height;
  18268. var i = 0, x, y;
  18269. var imageData = new Uint8Array(width * height * 4);
  18270. for (y = y_start; y !== y_end; y += y_step) {
  18271. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  18272. imageData[(x + width * y) * 4 + 3] = 255;
  18273. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  18274. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  18275. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  18276. }
  18277. }
  18278. return imageData;
  18279. };
  18280. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  18281. var image = pixel_data;
  18282. var width = header.width, height = header.height;
  18283. var i = 0, x, y;
  18284. var imageData = new Uint8Array(width * height * 4);
  18285. for (y = y_start; y !== y_end; y += y_step) {
  18286. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  18287. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  18288. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  18289. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  18290. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  18291. }
  18292. }
  18293. return imageData;
  18294. };
  18295. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  18296. var image = pixel_data;
  18297. var width = header.width, height = header.height;
  18298. var color, i = 0, x, y;
  18299. var imageData = new Uint8Array(width * height * 4);
  18300. for (y = y_start; y !== y_end; y += y_step) {
  18301. for (x = x_start; x !== x_end; x += x_step, i++) {
  18302. color = image[i];
  18303. imageData[(x + width * y) * 4 + 0] = color;
  18304. imageData[(x + width * y) * 4 + 1] = color;
  18305. imageData[(x + width * y) * 4 + 2] = color;
  18306. imageData[(x + width * y) * 4 + 3] = 255;
  18307. }
  18308. }
  18309. return imageData;
  18310. };
  18311. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  18312. var image = pixel_data;
  18313. var width = header.width, height = header.height;
  18314. var i = 0, x, y;
  18315. var imageData = new Uint8Array(width * height * 4);
  18316. for (y = y_start; y !== y_end; y += y_step) {
  18317. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  18318. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  18319. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  18320. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  18321. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  18322. }
  18323. }
  18324. return imageData;
  18325. };
  18326. TGATools._TYPE_NO_DATA = 0;
  18327. TGATools._TYPE_INDEXED = 1;
  18328. TGATools._TYPE_RGB = 2;
  18329. TGATools._TYPE_GREY = 3;
  18330. TGATools._TYPE_RLE_INDEXED = 9;
  18331. TGATools._TYPE_RLE_RGB = 10;
  18332. TGATools._TYPE_RLE_GREY = 11;
  18333. TGATools._ORIGIN_MASK = 0x30;
  18334. TGATools._ORIGIN_SHIFT = 0x04;
  18335. TGATools._ORIGIN_BL = 0x00;
  18336. TGATools._ORIGIN_BR = 0x01;
  18337. TGATools._ORIGIN_UL = 0x02;
  18338. TGATools._ORIGIN_UR = 0x03;
  18339. return TGATools;
  18340. })();
  18341. Internals.TGATools = TGATools;
  18342. })(BABYLON.Internals || (BABYLON.Internals = {}));
  18343. var Internals = BABYLON.Internals;
  18344. })(BABYLON || (BABYLON = {}));
  18345. var BABYLON;
  18346. (function (BABYLON) {
  18347. (function (Internals) {
  18348. var DDS_MAGIC = 0x20534444;
  18349. 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;
  18350. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  18351. 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;
  18352. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  18353. function FourCCToInt32(value) {
  18354. return value.charCodeAt(0) + (value.charCodeAt(1) << 8) + (value.charCodeAt(2) << 16) + (value.charCodeAt(3) << 24);
  18355. }
  18356. function Int32ToFourCC(value) {
  18357. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  18358. }
  18359. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  18360. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  18361. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  18362. var headerLengthInt = 31;
  18363. var off_magic = 0;
  18364. var off_size = 1;
  18365. var off_flags = 2;
  18366. var off_height = 3;
  18367. var off_width = 4;
  18368. var off_mipmapCount = 7;
  18369. var off_pfFlags = 20;
  18370. var off_pfFourCC = 21;
  18371. var off_RGBbpp = 22;
  18372. var off_RMask = 23;
  18373. var off_GMask = 24;
  18374. var off_BMask = 25;
  18375. var off_AMask = 26;
  18376. var off_caps1 = 27;
  18377. var off_caps2 = 28;
  18378. ;
  18379. var DDSTools = (function () {
  18380. function DDSTools() {
  18381. }
  18382. DDSTools.GetDDSInfo = function (arrayBuffer) {
  18383. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  18384. var mipmapCount = 1;
  18385. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  18386. mipmapCount = Math.max(1, header[off_mipmapCount]);
  18387. }
  18388. return {
  18389. width: header[off_width],
  18390. height: header[off_height],
  18391. mipmapCount: mipmapCount,
  18392. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  18393. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  18394. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  18395. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  18396. };
  18397. };
  18398. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  18399. var byteArray = new Uint8Array(dataLength);
  18400. var srcData = new Uint8Array(arrayBuffer);
  18401. var index = 0;
  18402. for (var y = height - 1; y >= 0; y--) {
  18403. for (var x = 0; x < width; x++) {
  18404. var srcPos = dataOffset + (x + y * width) * 4;
  18405. byteArray[index + 2] = srcData[srcPos];
  18406. byteArray[index + 1] = srcData[srcPos + 1];
  18407. byteArray[index] = srcData[srcPos + 2];
  18408. byteArray[index + 3] = srcData[srcPos + 3];
  18409. index += 4;
  18410. }
  18411. }
  18412. return byteArray;
  18413. };
  18414. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  18415. var byteArray = new Uint8Array(dataLength);
  18416. var srcData = new Uint8Array(arrayBuffer);
  18417. var index = 0;
  18418. for (var y = height - 1; y >= 0; y--) {
  18419. for (var x = 0; x < width; x++) {
  18420. var srcPos = dataOffset + (x + y * width) * 3;
  18421. byteArray[index + 2] = srcData[srcPos];
  18422. byteArray[index + 1] = srcData[srcPos + 1];
  18423. byteArray[index] = srcData[srcPos + 2];
  18424. index += 3;
  18425. }
  18426. }
  18427. return byteArray;
  18428. };
  18429. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  18430. var byteArray = new Uint8Array(dataLength);
  18431. var srcData = new Uint8Array(arrayBuffer);
  18432. var index = 0;
  18433. for (var y = height - 1; y >= 0; y--) {
  18434. for (var x = 0; x < width; x++) {
  18435. var srcPos = dataOffset + (x + y * width);
  18436. byteArray[index] = srcData[srcPos];
  18437. index++;
  18438. }
  18439. }
  18440. return byteArray;
  18441. };
  18442. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  18443. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  18444. if (header[off_magic] != DDS_MAGIC) {
  18445. BABYLON.Tools.Error("Invalid magic number in DDS header");
  18446. return;
  18447. }
  18448. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  18449. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  18450. return;
  18451. }
  18452. if (info.isFourCC) {
  18453. fourCC = header[off_pfFourCC];
  18454. switch (fourCC) {
  18455. case FOURCC_DXT1:
  18456. blockBytes = 8;
  18457. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  18458. break;
  18459. case FOURCC_DXT3:
  18460. blockBytes = 16;
  18461. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  18462. break;
  18463. case FOURCC_DXT5:
  18464. blockBytes = 16;
  18465. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  18466. break;
  18467. default:
  18468. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  18469. return;
  18470. }
  18471. }
  18472. mipmapCount = 1;
  18473. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  18474. mipmapCount = Math.max(1, header[off_mipmapCount]);
  18475. }
  18476. var bpp = header[off_RGBbpp];
  18477. for (var face = 0; face < faces; face++) {
  18478. var sampler = faces == 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  18479. width = header[off_width];
  18480. height = header[off_height];
  18481. dataOffset = header[off_size] + 4;
  18482. for (i = 0; i < mipmapCount; ++i) {
  18483. if (info.isRGB) {
  18484. if (bpp == 24) {
  18485. dataLength = width * height * 3;
  18486. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  18487. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  18488. } else {
  18489. dataLength = width * height * 4;
  18490. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  18491. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  18492. }
  18493. } else if (info.isLuminance) {
  18494. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  18495. var unpaddedRowSize = width;
  18496. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  18497. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  18498. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  18499. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  18500. } else {
  18501. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  18502. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  18503. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  18504. }
  18505. dataOffset += dataLength;
  18506. width *= 0.5;
  18507. height *= 0.5;
  18508. width = Math.max(1.0, width);
  18509. height = Math.max(1.0, height);
  18510. }
  18511. }
  18512. };
  18513. return DDSTools;
  18514. })();
  18515. Internals.DDSTools = DDSTools;
  18516. })(BABYLON.Internals || (BABYLON.Internals = {}));
  18517. var Internals = BABYLON.Internals;
  18518. })(BABYLON || (BABYLON = {}));
  18519. var BABYLON;
  18520. (function (BABYLON) {
  18521. var SmartArray = (function () {
  18522. function SmartArray(capacity) {
  18523. this.length = 0;
  18524. this._duplicateId = 0;
  18525. this.data = new Array(capacity);
  18526. this._id = SmartArray._GlobalId++;
  18527. }
  18528. SmartArray.prototype.push = function (value) {
  18529. this.data[this.length++] = value;
  18530. if (this.length > this.data.length) {
  18531. this.data.length *= 2;
  18532. }
  18533. if (!value.__smartArrayFlags) {
  18534. value.__smartArrayFlags = {};
  18535. }
  18536. value.__smartArrayFlags[this._id] = this._duplicateId;
  18537. };
  18538. SmartArray.prototype.pushNoDuplicate = function (value) {
  18539. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  18540. return;
  18541. }
  18542. this.push(value);
  18543. };
  18544. SmartArray.prototype.sort = function (compareFn) {
  18545. this.data.sort(compareFn);
  18546. };
  18547. SmartArray.prototype.reset = function () {
  18548. this.length = 0;
  18549. this._duplicateId++;
  18550. };
  18551. SmartArray.prototype.concat = function (array) {
  18552. if (array.length === 0) {
  18553. return;
  18554. }
  18555. if (this.length + array.length > this.data.length) {
  18556. this.data.length = (this.length + array.length) * 2;
  18557. }
  18558. for (var index = 0; index < array.length; index++) {
  18559. this.data[this.length++] = (array.data || array)[index];
  18560. }
  18561. };
  18562. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  18563. if (array.length === 0) {
  18564. return;
  18565. }
  18566. if (this.length + array.length > this.data.length) {
  18567. this.data.length = (this.length + array.length) * 2;
  18568. }
  18569. for (var index = 0; index < array.length; index++) {
  18570. var item = (array.data || array)[index];
  18571. this.pushNoDuplicate(item);
  18572. }
  18573. };
  18574. SmartArray.prototype.indexOf = function (value) {
  18575. var position = this.data.indexOf(value);
  18576. if (position >= this.length) {
  18577. return -1;
  18578. }
  18579. return position;
  18580. };
  18581. SmartArray._GlobalId = 0;
  18582. return SmartArray;
  18583. })();
  18584. BABYLON.SmartArray = SmartArray;
  18585. })(BABYLON || (BABYLON = {}));
  18586. var BABYLON;
  18587. (function (BABYLON) {
  18588. var CannonJSPlugin = (function () {
  18589. function CannonJSPlugin() {
  18590. this._registeredMeshes = [];
  18591. this._physicsMaterials = [];
  18592. this.updateBodyPosition = function (mesh) {
  18593. for (var index = 0; index < this._registeredMeshes.length; index++) {
  18594. var registeredMesh = this._registeredMeshes[index];
  18595. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  18596. var body = registeredMesh.body.body;
  18597. var center = mesh.getBoundingInfo().boundingBox.center;
  18598. body.position.set(center.x, center.z, center.y);
  18599. body.quaternion.x = mesh.rotationQuaternion.x;
  18600. body.quaternion.z = mesh.rotationQuaternion.y;
  18601. body.quaternion.y = mesh.rotationQuaternion.z;
  18602. body.quaternion.w = -mesh.rotationQuaternion.w;
  18603. return;
  18604. }
  18605. }
  18606. };
  18607. }
  18608. CannonJSPlugin.prototype.initialize = function (iterations) {
  18609. if (typeof iterations === "undefined") { iterations = 10; }
  18610. this._world = new CANNON.World();
  18611. this._world.broadphase = new CANNON.NaiveBroadphase();
  18612. this._world.solver.iterations = iterations;
  18613. };
  18614. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  18615. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  18616. };
  18617. CannonJSPlugin.prototype.runOneStep = function (delta) {
  18618. this._world.step(delta);
  18619. for (var index = 0; index < this._registeredMeshes.length; index++) {
  18620. var registeredMesh = this._registeredMeshes[index];
  18621. if (registeredMesh.isChild) {
  18622. continue;
  18623. }
  18624. var bodyX = registeredMesh.body.position.x, bodyY = registeredMesh.body.position.y, bodyZ = registeredMesh.body.position.z;
  18625. var deltaPos = registeredMesh.delta;
  18626. if (deltaPos) {
  18627. registeredMesh.mesh.position.x = bodyX + deltaPos.x;
  18628. registeredMesh.mesh.position.y = bodyZ + deltaPos.y;
  18629. registeredMesh.mesh.position.z = bodyY + deltaPos.z;
  18630. } else {
  18631. registeredMesh.mesh.position.x = bodyX;
  18632. registeredMesh.mesh.position.y = bodyZ;
  18633. registeredMesh.mesh.position.z = bodyY;
  18634. }
  18635. if (!registeredMesh.mesh.rotationQuaternion) {
  18636. registeredMesh.mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  18637. }
  18638. registeredMesh.mesh.rotationQuaternion.x = registeredMesh.body.quaternion.x;
  18639. registeredMesh.mesh.rotationQuaternion.y = registeredMesh.body.quaternion.z;
  18640. registeredMesh.mesh.rotationQuaternion.z = registeredMesh.body.quaternion.y;
  18641. registeredMesh.mesh.rotationQuaternion.w = -registeredMesh.body.quaternion.w;
  18642. }
  18643. };
  18644. CannonJSPlugin.prototype.setGravity = function (gravity) {
  18645. this._world.gravity.set(gravity.x, gravity.z, gravity.y);
  18646. };
  18647. CannonJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  18648. this.unregisterMesh(mesh);
  18649. mesh.computeWorldMatrix(true);
  18650. switch (impostor) {
  18651. case BABYLON.PhysicsEngine.SphereImpostor:
  18652. var bbox = mesh.getBoundingInfo().boundingBox;
  18653. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  18654. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  18655. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  18656. return this._createSphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2, mesh, options);
  18657. case BABYLON.PhysicsEngine.BoxImpostor:
  18658. bbox = mesh.getBoundingInfo().boundingBox;
  18659. var min = bbox.minimumWorld;
  18660. var max = bbox.maximumWorld;
  18661. var box = max.subtract(min).scale(0.5);
  18662. return this._createBox(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z), mesh, options);
  18663. case BABYLON.PhysicsEngine.PlaneImpostor:
  18664. return this._createPlane(mesh, options);
  18665. case BABYLON.PhysicsEngine.MeshImpostor:
  18666. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18667. var rawFaces = mesh.getIndices();
  18668. return this._createConvexPolyhedron(rawVerts, rawFaces, mesh, options);
  18669. }
  18670. return null;
  18671. };
  18672. CannonJSPlugin.prototype._createSphere = function (radius, mesh, options) {
  18673. var shape = new CANNON.Sphere(radius);
  18674. if (!options) {
  18675. return shape;
  18676. }
  18677. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  18678. };
  18679. CannonJSPlugin.prototype._createBox = function (x, y, z, mesh, options) {
  18680. var shape = new CANNON.Box(new CANNON.Vec3(x, z, y));
  18681. if (!options) {
  18682. return shape;
  18683. }
  18684. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  18685. };
  18686. CannonJSPlugin.prototype._createPlane = function (mesh, options) {
  18687. var shape = new CANNON.Plane();
  18688. if (!options) {
  18689. return shape;
  18690. }
  18691. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  18692. };
  18693. CannonJSPlugin.prototype._createConvexPolyhedron = function (rawVerts, rawFaces, mesh, options) {
  18694. var verts = [], faces = [];
  18695. mesh.computeWorldMatrix(true);
  18696. for (var i = 0; i < rawVerts.length; i += 3) {
  18697. var transformed = BABYLON.Vector3.Zero();
  18698. BABYLON.Vector3.TransformNormalFromFloatsToRef(rawVerts[i], rawVerts[i + 1], rawVerts[i + 2], mesh.getWorldMatrix(), transformed);
  18699. verts.push(new CANNON.Vec3(transformed.x, transformed.z, transformed.y));
  18700. }
  18701. for (var j = 0; j < rawFaces.length; j += 3) {
  18702. faces.push([rawFaces[j], rawFaces[j + 2], rawFaces[j + 1]]);
  18703. }
  18704. var shape = new CANNON.ConvexPolyhedron(verts, faces);
  18705. if (!options) {
  18706. return shape;
  18707. }
  18708. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  18709. };
  18710. CannonJSPlugin.prototype._addMaterial = function (friction, restitution) {
  18711. var index;
  18712. var mat;
  18713. for (index = 0; index < this._physicsMaterials.length; index++) {
  18714. mat = this._physicsMaterials[index];
  18715. if (mat.friction === friction && mat.restitution === restitution) {
  18716. return mat;
  18717. }
  18718. }
  18719. var currentMat = new CANNON.Material();
  18720. currentMat.friction = friction;
  18721. currentMat.restitution = restitution;
  18722. this._physicsMaterials.push(currentMat);
  18723. for (index = 0; index < this._physicsMaterials.length; index++) {
  18724. mat = this._physicsMaterials[index];
  18725. var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, mat.friction * currentMat.friction, mat.restitution * currentMat.restitution);
  18726. contactMaterial.contactEquationStiffness = 1e10;
  18727. contactMaterial.contactEquationRegularizationTime = 10;
  18728. this._world.addContactMaterial(contactMaterial);
  18729. }
  18730. return currentMat;
  18731. };
  18732. CannonJSPlugin.prototype._createRigidBodyFromShape = function (shape, mesh, mass, friction, restitution) {
  18733. var initialRotation = null;
  18734. if (mesh.rotationQuaternion) {
  18735. initialRotation = mesh.rotationQuaternion.clone();
  18736. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  18737. }
  18738. var bbox = mesh.getBoundingInfo().boundingBox;
  18739. var deltaPosition = mesh.position.subtract(bbox.center);
  18740. var material = this._addMaterial(friction, restitution);
  18741. var body = new CANNON.RigidBody(mass, shape, material);
  18742. if (initialRotation) {
  18743. body.quaternion.x = initialRotation.x;
  18744. body.quaternion.z = initialRotation.y;
  18745. body.quaternion.y = initialRotation.z;
  18746. body.quaternion.w = -initialRotation.w;
  18747. }
  18748. body.position.set(bbox.center.x, bbox.center.z, bbox.center.y);
  18749. this._world.add(body);
  18750. this._registeredMeshes.push({ mesh: mesh, body: body, material: material, delta: deltaPosition });
  18751. return body;
  18752. };
  18753. CannonJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  18754. var compoundShape = new CANNON.Compound();
  18755. for (var index = 0; index < parts.length; index++) {
  18756. var mesh = parts[index].mesh;
  18757. var shape = this.registerMesh(mesh, parts[index].impostor);
  18758. if (index == 0) {
  18759. compoundShape.addChild(shape, new CANNON.Vec3(0, 0, 0));
  18760. } else {
  18761. compoundShape.addChild(shape, new CANNON.Vec3(mesh.position.x, mesh.position.z, mesh.position.y));
  18762. }
  18763. }
  18764. var initialMesh = parts[0].mesh;
  18765. var body = this._createRigidBodyFromShape(compoundShape, initialMesh, options.mass, options.friction, options.restitution);
  18766. body.parts = parts;
  18767. return body;
  18768. };
  18769. CannonJSPlugin.prototype._unbindBody = function (body) {
  18770. for (var index = 0; index < this._registeredMeshes.length; index++) {
  18771. var registeredMesh = this._registeredMeshes[index];
  18772. if (registeredMesh.body === body) {
  18773. registeredMesh.body = null;
  18774. registeredMesh.delta = 0;
  18775. }
  18776. }
  18777. };
  18778. CannonJSPlugin.prototype.unregisterMesh = function (mesh) {
  18779. for (var index = 0; index < this._registeredMeshes.length; index++) {
  18780. var registeredMesh = this._registeredMeshes[index];
  18781. if (registeredMesh.mesh === mesh) {
  18782. if (registeredMesh.body) {
  18783. this._world.remove(registeredMesh.body);
  18784. this._unbindBody(registeredMesh.body);
  18785. }
  18786. this._registeredMeshes.splice(index, 1);
  18787. return;
  18788. }
  18789. }
  18790. };
  18791. CannonJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  18792. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.z, contactPoint.y);
  18793. var impulse = new CANNON.Vec3(force.x, force.z, force.y);
  18794. for (var index = 0; index < this._registeredMeshes.length; index++) {
  18795. var registeredMesh = this._registeredMeshes[index];
  18796. if (registeredMesh.mesh === mesh) {
  18797. registeredMesh.body.applyImpulse(impulse, worldPoint);
  18798. return;
  18799. }
  18800. }
  18801. };
  18802. CannonJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2) {
  18803. var body1 = null, body2 = null;
  18804. for (var index = 0; index < this._registeredMeshes.length; index++) {
  18805. var registeredMesh = this._registeredMeshes[index];
  18806. if (registeredMesh.mesh === mesh1) {
  18807. body1 = registeredMesh.body;
  18808. } else if (registeredMesh.mesh === mesh2) {
  18809. body2 = registeredMesh.body;
  18810. }
  18811. }
  18812. if (!body1 || !body2) {
  18813. return false;
  18814. }
  18815. 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));
  18816. this._world.addConstraint(constraint);
  18817. return true;
  18818. };
  18819. CannonJSPlugin.prototype.dispose = function () {
  18820. while (this._registeredMeshes.length) {
  18821. this.unregisterMesh(this._registeredMeshes[0].mesh);
  18822. }
  18823. };
  18824. CannonJSPlugin.prototype.isSupported = function () {
  18825. return window.CANNON !== undefined;
  18826. };
  18827. return CannonJSPlugin;
  18828. })();
  18829. BABYLON.CannonJSPlugin = CannonJSPlugin;
  18830. })(BABYLON || (BABYLON = {}));
  18831. var __extends = this.__extends || function (d, b) {
  18832. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  18833. function __() { this.constructor = d; }
  18834. __.prototype = b.prototype;
  18835. d.prototype = new __();
  18836. };
  18837. var BABYLON;
  18838. (function (BABYLON) {
  18839. var Condition = (function () {
  18840. function Condition(actionManager) {
  18841. this._actionManager = actionManager;
  18842. }
  18843. Condition.prototype.isValid = function () {
  18844. return true;
  18845. };
  18846. Condition.prototype._getProperty = function (propertyPath) {
  18847. return this._actionManager._getProperty(propertyPath);
  18848. };
  18849. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  18850. return this._actionManager._getEffectiveTarget(target, propertyPath);
  18851. };
  18852. return Condition;
  18853. })();
  18854. BABYLON.Condition = Condition;
  18855. var ValueCondition = (function (_super) {
  18856. __extends(ValueCondition, _super);
  18857. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  18858. if (typeof operator === "undefined") { operator = ValueCondition.IsEqual; }
  18859. _super.call(this, actionManager);
  18860. this.propertyPath = propertyPath;
  18861. this.value = value;
  18862. this.operator = operator;
  18863. this._target = this._getEffectiveTarget(target, this.propertyPath);
  18864. this._property = this._getProperty(this.propertyPath);
  18865. }
  18866. Object.defineProperty(ValueCondition, "IsEqual", {
  18867. get: function () {
  18868. return ValueCondition._IsEqual;
  18869. },
  18870. enumerable: true,
  18871. configurable: true
  18872. });
  18873. Object.defineProperty(ValueCondition, "IsDifferent", {
  18874. get: function () {
  18875. return ValueCondition._IsDifferent;
  18876. },
  18877. enumerable: true,
  18878. configurable: true
  18879. });
  18880. Object.defineProperty(ValueCondition, "IsGreater", {
  18881. get: function () {
  18882. return ValueCondition._IsGreater;
  18883. },
  18884. enumerable: true,
  18885. configurable: true
  18886. });
  18887. Object.defineProperty(ValueCondition, "IsLesser", {
  18888. get: function () {
  18889. return ValueCondition._IsLesser;
  18890. },
  18891. enumerable: true,
  18892. configurable: true
  18893. });
  18894. ValueCondition.prototype.isValid = function () {
  18895. switch (this.operator) {
  18896. case ValueCondition.IsGreater:
  18897. return this._target[this._property] > this.value;
  18898. case ValueCondition.IsLesser:
  18899. return this._target[this._property] < this.value;
  18900. case ValueCondition.IsEqual:
  18901. case ValueCondition.IsDifferent:
  18902. var check;
  18903. if (this.value.equals) {
  18904. check = this.value.equals(this._target[this._property]);
  18905. } else {
  18906. check = this.value === this._target[this._property];
  18907. }
  18908. return this.operator === ValueCondition.IsEqual ? check : !check;
  18909. }
  18910. return false;
  18911. };
  18912. ValueCondition._IsEqual = 0;
  18913. ValueCondition._IsDifferent = 1;
  18914. ValueCondition._IsGreater = 2;
  18915. ValueCondition._IsLesser = 3;
  18916. return ValueCondition;
  18917. })(Condition);
  18918. BABYLON.ValueCondition = ValueCondition;
  18919. var PredicateCondition = (function (_super) {
  18920. __extends(PredicateCondition, _super);
  18921. function PredicateCondition(actionManager, predicate) {
  18922. _super.call(this, actionManager);
  18923. this.predicate = predicate;
  18924. }
  18925. PredicateCondition.prototype.isValid = function () {
  18926. return this.predicate();
  18927. };
  18928. return PredicateCondition;
  18929. })(Condition);
  18930. BABYLON.PredicateCondition = PredicateCondition;
  18931. var StateCondition = (function (_super) {
  18932. __extends(StateCondition, _super);
  18933. function StateCondition(actionManager, target, value) {
  18934. _super.call(this, actionManager);
  18935. this.value = value;
  18936. this._target = target;
  18937. }
  18938. StateCondition.prototype.isValid = function () {
  18939. return this._target.state === this.value;
  18940. };
  18941. return StateCondition;
  18942. })(Condition);
  18943. BABYLON.StateCondition = StateCondition;
  18944. })(BABYLON || (BABYLON = {}));
  18945. var BABYLON;
  18946. (function (BABYLON) {
  18947. var Action = (function () {
  18948. function Action(triggerOptions, condition) {
  18949. this.triggerOptions = triggerOptions;
  18950. if (triggerOptions.parameter) {
  18951. this.trigger = triggerOptions.trigger;
  18952. this._triggerParameter = triggerOptions.parameter;
  18953. } else {
  18954. this.trigger = triggerOptions;
  18955. }
  18956. this._nextActiveAction = this;
  18957. this._condition = condition;
  18958. }
  18959. Action.prototype._prepare = function () {
  18960. };
  18961. Action.prototype.getTriggerParameter = function () {
  18962. return this._triggerParameter;
  18963. };
  18964. Action.prototype._executeCurrent = function (evt) {
  18965. if (this._condition) {
  18966. var currentRenderId = this._actionManager.getScene().getRenderId();
  18967. if (this._condition._evaluationId === currentRenderId) {
  18968. if (!this._condition._currentResult) {
  18969. return;
  18970. }
  18971. } else {
  18972. this._condition._evaluationId = currentRenderId;
  18973. if (!this._condition.isValid()) {
  18974. this._condition._currentResult = false;
  18975. return;
  18976. }
  18977. this._condition._currentResult = true;
  18978. }
  18979. }
  18980. this._nextActiveAction.execute(evt);
  18981. if (this._nextActiveAction._child) {
  18982. if (!this._nextActiveAction._child._actionManager) {
  18983. this._nextActiveAction._child._actionManager = this._actionManager;
  18984. }
  18985. this._nextActiveAction = this._nextActiveAction._child;
  18986. } else {
  18987. this._nextActiveAction = this;
  18988. }
  18989. };
  18990. Action.prototype.execute = function (evt) {
  18991. };
  18992. Action.prototype.then = function (action) {
  18993. this._child = action;
  18994. action._actionManager = this._actionManager;
  18995. action._prepare();
  18996. return action;
  18997. };
  18998. Action.prototype._getProperty = function (propertyPath) {
  18999. return this._actionManager._getProperty(propertyPath);
  19000. };
  19001. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  19002. return this._actionManager._getEffectiveTarget(target, propertyPath);
  19003. };
  19004. return Action;
  19005. })();
  19006. BABYLON.Action = Action;
  19007. })(BABYLON || (BABYLON = {}));
  19008. var BABYLON;
  19009. (function (BABYLON) {
  19010. var ActionEvent = (function () {
  19011. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent) {
  19012. this.source = source;
  19013. this.pointerX = pointerX;
  19014. this.pointerY = pointerY;
  19015. this.meshUnderPointer = meshUnderPointer;
  19016. this.sourceEvent = sourceEvent;
  19017. }
  19018. ActionEvent.CreateNew = function (source) {
  19019. var scene = source.getScene();
  19020. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer);
  19021. };
  19022. ActionEvent.CreateNewFromScene = function (scene, evt) {
  19023. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  19024. };
  19025. return ActionEvent;
  19026. })();
  19027. BABYLON.ActionEvent = ActionEvent;
  19028. var ActionManager = (function () {
  19029. function ActionManager(scene) {
  19030. this.actions = new Array();
  19031. this._scene = scene;
  19032. scene._actionManagers.push(this);
  19033. }
  19034. Object.defineProperty(ActionManager, "NothingTrigger", {
  19035. get: function () {
  19036. return ActionManager._NothingTrigger;
  19037. },
  19038. enumerable: true,
  19039. configurable: true
  19040. });
  19041. Object.defineProperty(ActionManager, "OnPickTrigger", {
  19042. get: function () {
  19043. return ActionManager._OnPickTrigger;
  19044. },
  19045. enumerable: true,
  19046. configurable: true
  19047. });
  19048. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  19049. get: function () {
  19050. return ActionManager._OnLeftPickTrigger;
  19051. },
  19052. enumerable: true,
  19053. configurable: true
  19054. });
  19055. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  19056. get: function () {
  19057. return ActionManager._OnRightPickTrigger;
  19058. },
  19059. enumerable: true,
  19060. configurable: true
  19061. });
  19062. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  19063. get: function () {
  19064. return ActionManager._OnCenterPickTrigger;
  19065. },
  19066. enumerable: true,
  19067. configurable: true
  19068. });
  19069. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  19070. get: function () {
  19071. return ActionManager._OnPointerOverTrigger;
  19072. },
  19073. enumerable: true,
  19074. configurable: true
  19075. });
  19076. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  19077. get: function () {
  19078. return ActionManager._OnPointerOutTrigger;
  19079. },
  19080. enumerable: true,
  19081. configurable: true
  19082. });
  19083. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  19084. get: function () {
  19085. return ActionManager._OnEveryFrameTrigger;
  19086. },
  19087. enumerable: true,
  19088. configurable: true
  19089. });
  19090. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  19091. get: function () {
  19092. return ActionManager._OnIntersectionEnterTrigger;
  19093. },
  19094. enumerable: true,
  19095. configurable: true
  19096. });
  19097. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  19098. get: function () {
  19099. return ActionManager._OnIntersectionExitTrigger;
  19100. },
  19101. enumerable: true,
  19102. configurable: true
  19103. });
  19104. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  19105. get: function () {
  19106. return ActionManager._OnKeyDownTrigger;
  19107. },
  19108. enumerable: true,
  19109. configurable: true
  19110. });
  19111. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  19112. get: function () {
  19113. return ActionManager._OnKeyUpTrigger;
  19114. },
  19115. enumerable: true,
  19116. configurable: true
  19117. });
  19118. ActionManager.prototype.dispose = function () {
  19119. var index = this._scene._actionManagers.indexOf(this);
  19120. if (index > -1) {
  19121. this._scene._actionManagers.splice(index, 1);
  19122. }
  19123. };
  19124. ActionManager.prototype.getScene = function () {
  19125. return this._scene;
  19126. };
  19127. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  19128. for (var index = 0; index < this.actions.length; index++) {
  19129. var action = this.actions[index];
  19130. if (triggers.indexOf(action.trigger) > -1) {
  19131. return true;
  19132. }
  19133. }
  19134. return false;
  19135. };
  19136. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  19137. get: function () {
  19138. for (var index = 0; index < this.actions.length; index++) {
  19139. var action = this.actions[index];
  19140. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  19141. return true;
  19142. }
  19143. }
  19144. return false;
  19145. },
  19146. enumerable: true,
  19147. configurable: true
  19148. });
  19149. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  19150. get: function () {
  19151. for (var index = 0; index < this.actions.length; index++) {
  19152. var action = this.actions[index];
  19153. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnCenterPickTrigger) {
  19154. return true;
  19155. }
  19156. }
  19157. return false;
  19158. },
  19159. enumerable: true,
  19160. configurable: true
  19161. });
  19162. ActionManager.prototype.registerAction = function (action) {
  19163. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  19164. if (this.getScene().actionManager !== this) {
  19165. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  19166. return null;
  19167. }
  19168. }
  19169. this.actions.push(action);
  19170. action._actionManager = this;
  19171. action._prepare();
  19172. return action;
  19173. };
  19174. ActionManager.prototype.processTrigger = function (trigger, evt) {
  19175. for (var index = 0; index < this.actions.length; index++) {
  19176. var action = this.actions[index];
  19177. if (action.trigger === trigger) {
  19178. if (trigger == ActionManager.OnKeyUpTrigger || trigger == ActionManager.OnKeyDownTrigger) {
  19179. var parameter = action.getTriggerParameter();
  19180. if (parameter) {
  19181. if (evt.sourceEvent.key !== parameter) {
  19182. continue;
  19183. }
  19184. }
  19185. }
  19186. action._executeCurrent(evt);
  19187. }
  19188. }
  19189. };
  19190. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  19191. var properties = propertyPath.split(".");
  19192. for (var index = 0; index < properties.length - 1; index++) {
  19193. target = target[properties[index]];
  19194. }
  19195. return target;
  19196. };
  19197. ActionManager.prototype._getProperty = function (propertyPath) {
  19198. var properties = propertyPath.split(".");
  19199. return properties[properties.length - 1];
  19200. };
  19201. ActionManager._NothingTrigger = 0;
  19202. ActionManager._OnPickTrigger = 1;
  19203. ActionManager._OnLeftPickTrigger = 2;
  19204. ActionManager._OnRightPickTrigger = 3;
  19205. ActionManager._OnCenterPickTrigger = 4;
  19206. ActionManager._OnPointerOverTrigger = 5;
  19207. ActionManager._OnPointerOutTrigger = 6;
  19208. ActionManager._OnEveryFrameTrigger = 7;
  19209. ActionManager._OnIntersectionEnterTrigger = 8;
  19210. ActionManager._OnIntersectionExitTrigger = 9;
  19211. ActionManager._OnKeyDownTrigger = 10;
  19212. ActionManager._OnKeyUpTrigger = 11;
  19213. return ActionManager;
  19214. })();
  19215. BABYLON.ActionManager = ActionManager;
  19216. })(BABYLON || (BABYLON = {}));
  19217. var __extends = this.__extends || function (d, b) {
  19218. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  19219. function __() { this.constructor = d; }
  19220. __.prototype = b.prototype;
  19221. d.prototype = new __();
  19222. };
  19223. var BABYLON;
  19224. (function (BABYLON) {
  19225. var InterpolateValueAction = (function (_super) {
  19226. __extends(InterpolateValueAction, _super);
  19227. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations) {
  19228. if (typeof duration === "undefined") { duration = 1000; }
  19229. _super.call(this, triggerOptions, condition);
  19230. this.propertyPath = propertyPath;
  19231. this.value = value;
  19232. this.duration = duration;
  19233. this.stopOtherAnimations = stopOtherAnimations;
  19234. this._target = target;
  19235. }
  19236. InterpolateValueAction.prototype._prepare = function () {
  19237. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  19238. this._property = this._getProperty(this.propertyPath);
  19239. };
  19240. InterpolateValueAction.prototype.execute = function () {
  19241. var scene = this._actionManager.getScene();
  19242. var keys = [
  19243. {
  19244. frame: 0,
  19245. value: this._target[this._property]
  19246. }, {
  19247. frame: 100,
  19248. value: this.value
  19249. }
  19250. ];
  19251. var dataType;
  19252. if (typeof this.value === "number") {
  19253. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  19254. } else if (this.value instanceof BABYLON.Color3) {
  19255. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  19256. } else if (this.value instanceof BABYLON.Vector3) {
  19257. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  19258. } else if (this.value instanceof BABYLON.Matrix) {
  19259. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  19260. } else if (this.value instanceof BABYLON.Quaternion) {
  19261. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  19262. } else {
  19263. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  19264. return;
  19265. }
  19266. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  19267. animation.setKeys(keys);
  19268. if (this.stopOtherAnimations) {
  19269. scene.stopAnimation(this._target);
  19270. }
  19271. scene.beginDirectAnimation(this._target, [animation], 0, 100);
  19272. };
  19273. return InterpolateValueAction;
  19274. })(BABYLON.Action);
  19275. BABYLON.InterpolateValueAction = InterpolateValueAction;
  19276. })(BABYLON || (BABYLON = {}));
  19277. var __extends = this.__extends || function (d, b) {
  19278. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  19279. function __() { this.constructor = d; }
  19280. __.prototype = b.prototype;
  19281. d.prototype = new __();
  19282. };
  19283. var BABYLON;
  19284. (function (BABYLON) {
  19285. var SwitchBooleanAction = (function (_super) {
  19286. __extends(SwitchBooleanAction, _super);
  19287. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  19288. _super.call(this, triggerOptions, condition);
  19289. this.propertyPath = propertyPath;
  19290. this._target = target;
  19291. }
  19292. SwitchBooleanAction.prototype._prepare = function () {
  19293. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  19294. this._property = this._getProperty(this.propertyPath);
  19295. };
  19296. SwitchBooleanAction.prototype.execute = function () {
  19297. this._target[this._property] = !this._target[this._property];
  19298. };
  19299. return SwitchBooleanAction;
  19300. })(BABYLON.Action);
  19301. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  19302. var SetStateAction = (function (_super) {
  19303. __extends(SetStateAction, _super);
  19304. function SetStateAction(triggerOptions, target, value, condition) {
  19305. _super.call(this, triggerOptions, condition);
  19306. this.value = value;
  19307. this._target = target;
  19308. }
  19309. SetStateAction.prototype.execute = function () {
  19310. this._target.state = this.value;
  19311. };
  19312. return SetStateAction;
  19313. })(BABYLON.Action);
  19314. BABYLON.SetStateAction = SetStateAction;
  19315. var SetValueAction = (function (_super) {
  19316. __extends(SetValueAction, _super);
  19317. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  19318. _super.call(this, triggerOptions, condition);
  19319. this.propertyPath = propertyPath;
  19320. this.value = value;
  19321. this._target = target;
  19322. }
  19323. SetValueAction.prototype._prepare = function () {
  19324. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  19325. this._property = this._getProperty(this.propertyPath);
  19326. };
  19327. SetValueAction.prototype.execute = function () {
  19328. this._target[this._property] = this.value;
  19329. };
  19330. return SetValueAction;
  19331. })(BABYLON.Action);
  19332. BABYLON.SetValueAction = SetValueAction;
  19333. var IncrementValueAction = (function (_super) {
  19334. __extends(IncrementValueAction, _super);
  19335. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  19336. _super.call(this, triggerOptions, condition);
  19337. this.propertyPath = propertyPath;
  19338. this.value = value;
  19339. this._target = target;
  19340. }
  19341. IncrementValueAction.prototype._prepare = function () {
  19342. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  19343. this._property = this._getProperty(this.propertyPath);
  19344. if (typeof this._target[this._property] !== "number") {
  19345. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  19346. }
  19347. };
  19348. IncrementValueAction.prototype.execute = function () {
  19349. this._target[this._property] += this.value;
  19350. };
  19351. return IncrementValueAction;
  19352. })(BABYLON.Action);
  19353. BABYLON.IncrementValueAction = IncrementValueAction;
  19354. var PlayAnimationAction = (function (_super) {
  19355. __extends(PlayAnimationAction, _super);
  19356. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  19357. _super.call(this, triggerOptions, condition);
  19358. this.from = from;
  19359. this.to = to;
  19360. this.loop = loop;
  19361. this._target = target;
  19362. }
  19363. PlayAnimationAction.prototype._prepare = function () {
  19364. };
  19365. PlayAnimationAction.prototype.execute = function () {
  19366. var scene = this._actionManager.getScene();
  19367. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  19368. };
  19369. return PlayAnimationAction;
  19370. })(BABYLON.Action);
  19371. BABYLON.PlayAnimationAction = PlayAnimationAction;
  19372. var StopAnimationAction = (function (_super) {
  19373. __extends(StopAnimationAction, _super);
  19374. function StopAnimationAction(triggerOptions, target, condition) {
  19375. _super.call(this, triggerOptions, condition);
  19376. this._target = target;
  19377. }
  19378. StopAnimationAction.prototype._prepare = function () {
  19379. };
  19380. StopAnimationAction.prototype.execute = function () {
  19381. var scene = this._actionManager.getScene();
  19382. scene.stopAnimation(this._target);
  19383. };
  19384. return StopAnimationAction;
  19385. })(BABYLON.Action);
  19386. BABYLON.StopAnimationAction = StopAnimationAction;
  19387. var DoNothingAction = (function (_super) {
  19388. __extends(DoNothingAction, _super);
  19389. function DoNothingAction(triggerOptions, condition) {
  19390. if (typeof triggerOptions === "undefined") { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  19391. _super.call(this, triggerOptions, condition);
  19392. }
  19393. DoNothingAction.prototype.execute = function () {
  19394. };
  19395. return DoNothingAction;
  19396. })(BABYLON.Action);
  19397. BABYLON.DoNothingAction = DoNothingAction;
  19398. var CombineAction = (function (_super) {
  19399. __extends(CombineAction, _super);
  19400. function CombineAction(triggerOptions, children, condition) {
  19401. _super.call(this, triggerOptions, condition);
  19402. this.children = children;
  19403. }
  19404. CombineAction.prototype._prepare = function () {
  19405. for (var index = 0; index < this.children.length; index++) {
  19406. this.children[index]._actionManager = this._actionManager;
  19407. this.children[index]._prepare();
  19408. }
  19409. };
  19410. CombineAction.prototype.execute = function (evt) {
  19411. for (var index = 0; index < this.children.length; index++) {
  19412. this.children[index].execute(evt);
  19413. }
  19414. };
  19415. return CombineAction;
  19416. })(BABYLON.Action);
  19417. BABYLON.CombineAction = CombineAction;
  19418. var ExecuteCodeAction = (function (_super) {
  19419. __extends(ExecuteCodeAction, _super);
  19420. function ExecuteCodeAction(triggerOptions, func, condition) {
  19421. _super.call(this, triggerOptions, condition);
  19422. this.func = func;
  19423. }
  19424. ExecuteCodeAction.prototype.execute = function (evt) {
  19425. this.func(evt);
  19426. };
  19427. return ExecuteCodeAction;
  19428. })(BABYLON.Action);
  19429. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  19430. var SetParentAction = (function (_super) {
  19431. __extends(SetParentAction, _super);
  19432. function SetParentAction(triggerOptions, target, parent, condition) {
  19433. _super.call(this, triggerOptions, condition);
  19434. this._target = target;
  19435. this._parent = parent;
  19436. }
  19437. SetParentAction.prototype._prepare = function () {
  19438. };
  19439. SetParentAction.prototype.execute = function () {
  19440. if (this._target.parent === this._parent) {
  19441. return;
  19442. }
  19443. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  19444. invertParentWorldMatrix.invert();
  19445. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  19446. this._target.parent = this._parent;
  19447. };
  19448. return SetParentAction;
  19449. })(BABYLON.Action);
  19450. BABYLON.SetParentAction = SetParentAction;
  19451. })(BABYLON || (BABYLON = {}));
  19452. var __extends = this.__extends || function (d, b) {
  19453. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  19454. function __() { this.constructor = d; }
  19455. __.prototype = b.prototype;
  19456. d.prototype = new __();
  19457. };
  19458. var BABYLON;
  19459. (function (BABYLON) {
  19460. var Geometry = (function () {
  19461. function Geometry(id, scene, vertexData, updatable, mesh) {
  19462. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  19463. this._totalVertices = 0;
  19464. this._indices = [];
  19465. this.id = id;
  19466. this._engine = scene.getEngine();
  19467. this._meshes = [];
  19468. this._scene = scene;
  19469. if (vertexData) {
  19470. this.setAllVerticesData(vertexData, updatable);
  19471. } else {
  19472. this._totalVertices = 0;
  19473. this._indices = [];
  19474. }
  19475. if (mesh) {
  19476. this.applyToMesh(mesh);
  19477. }
  19478. }
  19479. Geometry.prototype.getScene = function () {
  19480. return this._scene;
  19481. };
  19482. Geometry.prototype.getEngine = function () {
  19483. return this._engine;
  19484. };
  19485. Geometry.prototype.isReady = function () {
  19486. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  19487. };
  19488. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  19489. vertexData.applyToGeometry(this, updatable);
  19490. };
  19491. Geometry.prototype.setVerticesData = function (kind, data, updatable) {
  19492. this._vertexBuffers = this._vertexBuffers || {};
  19493. if (this._vertexBuffers[kind]) {
  19494. this._vertexBuffers[kind].dispose();
  19495. }
  19496. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0);
  19497. if (kind === BABYLON.VertexBuffer.PositionKind) {
  19498. var stride = this._vertexBuffers[kind].getStrideSize();
  19499. this._totalVertices = data.length / stride;
  19500. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  19501. var meshes = this._meshes;
  19502. var numOfMeshes = meshes.length;
  19503. for (var index = 0; index < numOfMeshes; index++) {
  19504. var mesh = meshes[index];
  19505. mesh._resetPointsArrayCache();
  19506. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  19507. mesh._createGlobalSubMesh();
  19508. mesh.computeWorldMatrix(true);
  19509. }
  19510. }
  19511. };
  19512. Geometry.prototype.updateVerticesDataDirectly = function (kind, data) {
  19513. var vertexBuffer = this.getVertexBuffer(kind);
  19514. if (!vertexBuffer) {
  19515. return;
  19516. }
  19517. vertexBuffer.updateDirectly(data);
  19518. };
  19519. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  19520. var vertexBuffer = this.getVertexBuffer(kind);
  19521. if (!vertexBuffer) {
  19522. return;
  19523. }
  19524. vertexBuffer.update(data);
  19525. if (kind === BABYLON.VertexBuffer.PositionKind) {
  19526. var extend;
  19527. if (updateExtends) {
  19528. var stride = vertexBuffer.getStrideSize();
  19529. this._totalVertices = data.length / stride;
  19530. extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  19531. }
  19532. var meshes = this._meshes;
  19533. var numOfMeshes = meshes.length;
  19534. for (var index = 0; index < numOfMeshes; index++) {
  19535. var mesh = meshes[index];
  19536. mesh._resetPointsArrayCache();
  19537. if (updateExtends) {
  19538. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  19539. }
  19540. }
  19541. }
  19542. };
  19543. Geometry.prototype.getTotalVertices = function () {
  19544. if (!this.isReady()) {
  19545. return 0;
  19546. }
  19547. return this._totalVertices;
  19548. };
  19549. Geometry.prototype.getVerticesData = function (kind) {
  19550. var vertexBuffer = this.getVertexBuffer(kind);
  19551. if (!vertexBuffer) {
  19552. return null;
  19553. }
  19554. return vertexBuffer.getData();
  19555. };
  19556. Geometry.prototype.getVertexBuffer = function (kind) {
  19557. if (!this.isReady()) {
  19558. return null;
  19559. }
  19560. return this._vertexBuffers[kind];
  19561. };
  19562. Geometry.prototype.getVertexBuffers = function () {
  19563. if (!this.isReady()) {
  19564. return null;
  19565. }
  19566. return this._vertexBuffers;
  19567. };
  19568. Geometry.prototype.isVerticesDataPresent = function (kind) {
  19569. if (!this._vertexBuffers) {
  19570. if (this._delayInfo) {
  19571. return this._delayInfo.indexOf(kind) !== -1;
  19572. }
  19573. return false;
  19574. }
  19575. return this._vertexBuffers[kind] !== undefined;
  19576. };
  19577. Geometry.prototype.getVerticesDataKinds = function () {
  19578. var result = [];
  19579. if (!this._vertexBuffers && this._delayInfo) {
  19580. for (var kind in this._delayInfo) {
  19581. result.push(kind);
  19582. }
  19583. } else {
  19584. for (kind in this._vertexBuffers) {
  19585. result.push(kind);
  19586. }
  19587. }
  19588. return result;
  19589. };
  19590. Geometry.prototype.setIndices = function (indices) {
  19591. if (this._indexBuffer) {
  19592. this._engine._releaseBuffer(this._indexBuffer);
  19593. }
  19594. this._indices = indices;
  19595. if (this._meshes.length !== 0 && this._indices) {
  19596. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  19597. }
  19598. var meshes = this._meshes;
  19599. var numOfMeshes = meshes.length;
  19600. for (var index = 0; index < numOfMeshes; index++) {
  19601. meshes[index]._createGlobalSubMesh();
  19602. }
  19603. };
  19604. Geometry.prototype.getTotalIndices = function () {
  19605. if (!this.isReady()) {
  19606. return 0;
  19607. }
  19608. return this._indices.length;
  19609. };
  19610. Geometry.prototype.getIndices = function () {
  19611. if (!this.isReady()) {
  19612. return null;
  19613. }
  19614. return this._indices;
  19615. };
  19616. Geometry.prototype.getIndexBuffer = function () {
  19617. if (!this.isReady()) {
  19618. return null;
  19619. }
  19620. return this._indexBuffer;
  19621. };
  19622. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  19623. var meshes = this._meshes;
  19624. var index = meshes.indexOf(mesh);
  19625. if (index === -1) {
  19626. return;
  19627. }
  19628. for (var kind in this._vertexBuffers) {
  19629. this._vertexBuffers[kind].dispose();
  19630. }
  19631. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  19632. this._indexBuffer = null;
  19633. }
  19634. meshes.splice(index, 1);
  19635. mesh._geometry = null;
  19636. if (meshes.length == 0 && shouldDispose) {
  19637. this.dispose();
  19638. }
  19639. };
  19640. Geometry.prototype.applyToMesh = function (mesh) {
  19641. if (mesh._geometry === this) {
  19642. return;
  19643. }
  19644. var previousGeometry = mesh._geometry;
  19645. if (previousGeometry) {
  19646. previousGeometry.releaseForMesh(mesh);
  19647. }
  19648. var meshes = this._meshes;
  19649. mesh._geometry = this;
  19650. this._scene.pushGeometry(this);
  19651. meshes.push(mesh);
  19652. if (this.isReady()) {
  19653. this._applyToMesh(mesh);
  19654. } else {
  19655. mesh._boundingInfo = this._boundingInfo;
  19656. }
  19657. };
  19658. Geometry.prototype._applyToMesh = function (mesh) {
  19659. var numOfMeshes = this._meshes.length;
  19660. for (var kind in this._vertexBuffers) {
  19661. if (numOfMeshes === 1) {
  19662. this._vertexBuffers[kind].create();
  19663. }
  19664. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  19665. if (kind === BABYLON.VertexBuffer.PositionKind) {
  19666. mesh._resetPointsArrayCache();
  19667. var extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  19668. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  19669. mesh._createGlobalSubMesh();
  19670. }
  19671. }
  19672. if (numOfMeshes === 1 && this._indices) {
  19673. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  19674. }
  19675. if (this._indexBuffer) {
  19676. this._indexBuffer.references = numOfMeshes;
  19677. }
  19678. };
  19679. Geometry.prototype.load = function (scene, onLoaded) {
  19680. var _this = this;
  19681. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  19682. return;
  19683. }
  19684. if (this.isReady()) {
  19685. if (onLoaded) {
  19686. onLoaded();
  19687. }
  19688. return;
  19689. }
  19690. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  19691. scene._addPendingData(this);
  19692. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  19693. _this._delayLoadingFunction(JSON.parse(data), _this);
  19694. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  19695. _this._delayInfo = [];
  19696. scene._removePendingData(_this);
  19697. var meshes = _this._meshes;
  19698. var numOfMeshes = meshes.length;
  19699. for (var index = 0; index < numOfMeshes; index++) {
  19700. _this._applyToMesh(meshes[index]);
  19701. }
  19702. if (onLoaded) {
  19703. onLoaded();
  19704. }
  19705. }, function () {
  19706. }, scene.database);
  19707. };
  19708. Geometry.prototype.dispose = function () {
  19709. var meshes = this._meshes;
  19710. var numOfMeshes = meshes.length;
  19711. for (var index = 0; index < numOfMeshes; index++) {
  19712. this.releaseForMesh(meshes[index]);
  19713. }
  19714. this._meshes = [];
  19715. for (var kind in this._vertexBuffers) {
  19716. this._vertexBuffers[kind].dispose();
  19717. }
  19718. this._vertexBuffers = [];
  19719. this._totalVertices = 0;
  19720. if (this._indexBuffer) {
  19721. this._engine._releaseBuffer(this._indexBuffer);
  19722. }
  19723. this._indexBuffer = null;
  19724. this._indices = [];
  19725. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  19726. this.delayLoadingFile = null;
  19727. this._delayLoadingFunction = null;
  19728. this._delayInfo = [];
  19729. this._boundingInfo = null;
  19730. var geometries = this._scene.getGeometries();
  19731. index = geometries.indexOf(this);
  19732. if (index > -1) {
  19733. geometries.splice(index, 1);
  19734. }
  19735. };
  19736. Geometry.prototype.copy = function (id) {
  19737. var vertexData = new BABYLON.VertexData();
  19738. vertexData.indices = [];
  19739. var indices = this.getIndices();
  19740. for (var index = 0; index < indices.length; index++) {
  19741. vertexData.indices.push(indices[index]);
  19742. }
  19743. var updatable = false;
  19744. var stopChecking = false;
  19745. for (var kind in this._vertexBuffers) {
  19746. vertexData.set(this.getVerticesData(kind), kind);
  19747. if (!stopChecking) {
  19748. updatable = this.getVertexBuffer(kind).isUpdatable();
  19749. stopChecking = !updatable;
  19750. }
  19751. }
  19752. var geometry = new BABYLON.Geometry(id, this._scene, vertexData, updatable, null);
  19753. geometry.delayLoadState = this.delayLoadState;
  19754. geometry.delayLoadingFile = this.delayLoadingFile;
  19755. geometry._delayLoadingFunction = this._delayLoadingFunction;
  19756. for (kind in this._delayInfo) {
  19757. geometry._delayInfo = geometry._delayInfo || [];
  19758. geometry._delayInfo.push(kind);
  19759. }
  19760. var extend = BABYLON.Tools.ExtractMinAndMax(this.getVerticesData(BABYLON.VertexBuffer.PositionKind), 0, this.getTotalVertices());
  19761. geometry._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  19762. return geometry;
  19763. };
  19764. Geometry.ExtractFromMesh = function (mesh, id) {
  19765. var geometry = mesh._geometry;
  19766. if (!geometry) {
  19767. return null;
  19768. }
  19769. return geometry.copy(id);
  19770. };
  19771. Geometry.RandomId = function () {
  19772. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  19773. var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
  19774. return v.toString(16);
  19775. });
  19776. };
  19777. return Geometry;
  19778. })();
  19779. BABYLON.Geometry = Geometry;
  19780. (function (Geometry) {
  19781. (function (Primitives) {
  19782. var _Primitive = (function (_super) {
  19783. __extends(_Primitive, _super);
  19784. function _Primitive(id, scene, vertexData, canBeRegenerated, mesh) {
  19785. this._beingRegenerated = true;
  19786. this._canBeRegenerated = canBeRegenerated;
  19787. _super.call(this, id, scene, vertexData, false, mesh);
  19788. this._beingRegenerated = false;
  19789. }
  19790. _Primitive.prototype.canBeRegenerated = function () {
  19791. return this._canBeRegenerated;
  19792. };
  19793. _Primitive.prototype.regenerate = function () {
  19794. if (!this._canBeRegenerated) {
  19795. return;
  19796. }
  19797. this._beingRegenerated = true;
  19798. this.setAllVerticesData(this._regenerateVertexData(), false);
  19799. this._beingRegenerated = false;
  19800. };
  19801. _Primitive.prototype.asNewGeometry = function (id) {
  19802. return _super.prototype.copy.call(this, id);
  19803. };
  19804. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  19805. if (!this._beingRegenerated) {
  19806. return;
  19807. }
  19808. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  19809. };
  19810. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  19811. if (!this._beingRegenerated) {
  19812. return;
  19813. }
  19814. _super.prototype.setVerticesData.call(this, kind, data, false);
  19815. };
  19816. _Primitive.prototype._regenerateVertexData = function () {
  19817. throw new Error("Abstract method");
  19818. };
  19819. _Primitive.prototype.copy = function (id) {
  19820. throw new Error("Must be overriden in sub-classes.");
  19821. };
  19822. return _Primitive;
  19823. })(Geometry);
  19824. Primitives._Primitive = _Primitive;
  19825. var Box = (function (_super) {
  19826. __extends(Box, _super);
  19827. function Box(id, scene, size, canBeRegenerated, mesh) {
  19828. this.size = size;
  19829. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  19830. }
  19831. Box.prototype._regenerateVertexData = function () {
  19832. return BABYLON.VertexData.CreateBox(this.size);
  19833. };
  19834. Box.prototype.copy = function (id) {
  19835. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null);
  19836. };
  19837. return Box;
  19838. })(_Primitive);
  19839. Primitives.Box = Box;
  19840. var Sphere = (function (_super) {
  19841. __extends(Sphere, _super);
  19842. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh) {
  19843. this.segments = segments;
  19844. this.diameter = diameter;
  19845. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  19846. }
  19847. Sphere.prototype._regenerateVertexData = function () {
  19848. return BABYLON.VertexData.CreateSphere(this.segments, this.diameter);
  19849. };
  19850. Sphere.prototype.copy = function (id) {
  19851. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null);
  19852. };
  19853. return Sphere;
  19854. })(_Primitive);
  19855. Primitives.Sphere = Sphere;
  19856. var Cylinder = (function (_super) {
  19857. __extends(Cylinder, _super);
  19858. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh) {
  19859. if (typeof subdivisions === "undefined") { subdivisions = 1; }
  19860. this.height = height;
  19861. this.diameterTop = diameterTop;
  19862. this.diameterBottom = diameterBottom;
  19863. this.tessellation = tessellation;
  19864. this.subdivisions = subdivisions;
  19865. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  19866. }
  19867. Cylinder.prototype._regenerateVertexData = function () {
  19868. return BABYLON.VertexData.CreateCylinder(this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions);
  19869. };
  19870. Cylinder.prototype.copy = function (id) {
  19871. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null);
  19872. };
  19873. return Cylinder;
  19874. })(_Primitive);
  19875. Primitives.Cylinder = Cylinder;
  19876. var Torus = (function (_super) {
  19877. __extends(Torus, _super);
  19878. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh) {
  19879. this.diameter = diameter;
  19880. this.thickness = thickness;
  19881. this.tessellation = tessellation;
  19882. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  19883. }
  19884. Torus.prototype._regenerateVertexData = function () {
  19885. return BABYLON.VertexData.CreateTorus(this.diameter, this.thickness, this.tessellation);
  19886. };
  19887. Torus.prototype.copy = function (id) {
  19888. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null);
  19889. };
  19890. return Torus;
  19891. })(_Primitive);
  19892. Primitives.Torus = Torus;
  19893. var Ground = (function (_super) {
  19894. __extends(Ground, _super);
  19895. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  19896. this.width = width;
  19897. this.height = height;
  19898. this.subdivisions = subdivisions;
  19899. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  19900. }
  19901. Ground.prototype._regenerateVertexData = function () {
  19902. return BABYLON.VertexData.CreateGround(this.width, this.height, this.subdivisions);
  19903. };
  19904. Ground.prototype.copy = function (id) {
  19905. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  19906. };
  19907. return Ground;
  19908. })(_Primitive);
  19909. Primitives.Ground = Ground;
  19910. var TiledGround = (function (_super) {
  19911. __extends(TiledGround, _super);
  19912. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  19913. this.xmin = xmin;
  19914. this.zmin = zmin;
  19915. this.xmax = xmax;
  19916. this.zmax = zmax;
  19917. this.subdivisions = subdivisions;
  19918. this.precision = precision;
  19919. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  19920. }
  19921. TiledGround.prototype._regenerateVertexData = function () {
  19922. return BABYLON.VertexData.CreateTiledGround(this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision);
  19923. };
  19924. TiledGround.prototype.copy = function (id) {
  19925. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  19926. };
  19927. return TiledGround;
  19928. })(_Primitive);
  19929. Primitives.TiledGround = TiledGround;
  19930. var Plane = (function (_super) {
  19931. __extends(Plane, _super);
  19932. function Plane(id, scene, size, canBeRegenerated, mesh) {
  19933. this.size = size;
  19934. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  19935. }
  19936. Plane.prototype._regenerateVertexData = function () {
  19937. return BABYLON.VertexData.CreatePlane(this.size);
  19938. };
  19939. Plane.prototype.copy = function (id) {
  19940. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null);
  19941. };
  19942. return Plane;
  19943. })(_Primitive);
  19944. Primitives.Plane = Plane;
  19945. var TorusKnot = (function (_super) {
  19946. __extends(TorusKnot, _super);
  19947. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh) {
  19948. this.radius = radius;
  19949. this.tube = tube;
  19950. this.radialSegments = radialSegments;
  19951. this.tubularSegments = tubularSegments;
  19952. this.p = p;
  19953. this.q = q;
  19954. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  19955. }
  19956. TorusKnot.prototype._regenerateVertexData = function () {
  19957. return BABYLON.VertexData.CreateTorusKnot(this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q);
  19958. };
  19959. TorusKnot.prototype.copy = function (id) {
  19960. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null);
  19961. };
  19962. return TorusKnot;
  19963. })(_Primitive);
  19964. Primitives.TorusKnot = TorusKnot;
  19965. })(Geometry.Primitives || (Geometry.Primitives = {}));
  19966. var Primitives = Geometry.Primitives;
  19967. })(BABYLON.Geometry || (BABYLON.Geometry = {}));
  19968. var Geometry = BABYLON.Geometry;
  19969. })(BABYLON || (BABYLON = {}));
  19970. var __extends = this.__extends || function (d, b) {
  19971. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  19972. function __() { this.constructor = d; }
  19973. __.prototype = b.prototype;
  19974. d.prototype = new __();
  19975. };
  19976. var BABYLON;
  19977. (function (BABYLON) {
  19978. var Gamepads = (function () {
  19979. function Gamepads(ongamedpadconnected) {
  19980. var _this = this;
  19981. this.babylonGamepads = [];
  19982. this.oneGamepadConnected = false;
  19983. this.isMonitoring = false;
  19984. this.gamepadEventSupported = 'GamepadEvent' in window;
  19985. this.gamepadSupportAvailable = (navigator.getGamepads || !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  19986. 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=";
  19987. this._callbackGamepadConnected = ongamedpadconnected;
  19988. if (this.gamepadSupportAvailable) {
  19989. if (this.gamepadEventSupported) {
  19990. window.addEventListener('gamepadconnected', function (evt) {
  19991. _this._onGamepadConnected(evt);
  19992. }, false);
  19993. window.addEventListener('gamepaddisconnected', function (evt) {
  19994. _this._onGamepadDisconnected(evt);
  19995. }, false);
  19996. } else {
  19997. this._startMonitoringGamepads();
  19998. }
  19999. if (!this.oneGamepadConnected) {
  20000. this._insertGamepadDOMInstructions();
  20001. }
  20002. } else {
  20003. this._insertGamepadDOMNotSupported();
  20004. }
  20005. }
  20006. Gamepads.prototype._insertGamepadDOMInstructions = function () {
  20007. Gamepads.gamepadDOMInfo = document.createElement("div");
  20008. var buttonAImage = document.createElement("img");
  20009. buttonAImage.src = this.buttonADataURL;
  20010. var spanMessage = document.createElement("span");
  20011. spanMessage.innerHTML = "<strong>to activate gamepad</strong>";
  20012. Gamepads.gamepadDOMInfo.appendChild(buttonAImage);
  20013. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  20014. Gamepads.gamepadDOMInfo.style.position = "absolute";
  20015. Gamepads.gamepadDOMInfo.style.width = "100%";
  20016. Gamepads.gamepadDOMInfo.style.height = "48px";
  20017. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  20018. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  20019. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  20020. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  20021. buttonAImage.style.position = "relative";
  20022. buttonAImage.style.bottom = "8px";
  20023. spanMessage.style.position = "relative";
  20024. spanMessage.style.fontSize = "32px";
  20025. spanMessage.style.bottom = "32px";
  20026. spanMessage.style.color = "green";
  20027. document.body.appendChild(Gamepads.gamepadDOMInfo);
  20028. };
  20029. Gamepads.prototype._insertGamepadDOMNotSupported = function () {
  20030. Gamepads.gamepadDOMInfo = document.createElement("div");
  20031. var spanMessage = document.createElement("span");
  20032. spanMessage.innerHTML = "<strong>gamepad not supported</strong>";
  20033. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  20034. Gamepads.gamepadDOMInfo.style.position = "absolute";
  20035. Gamepads.gamepadDOMInfo.style.width = "100%";
  20036. Gamepads.gamepadDOMInfo.style.height = "40px";
  20037. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  20038. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  20039. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  20040. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  20041. spanMessage.style.position = "relative";
  20042. spanMessage.style.fontSize = "32px";
  20043. spanMessage.style.color = "red";
  20044. document.body.appendChild(Gamepads.gamepadDOMInfo);
  20045. };
  20046. Gamepads.prototype.dispose = function () {
  20047. document.body.removeChild(Gamepads.gamepadDOMInfo);
  20048. };
  20049. Gamepads.prototype._onGamepadConnected = function (evt) {
  20050. var newGamepad = this._addNewGamepad(evt.gamepad);
  20051. if (this._callbackGamepadConnected)
  20052. this._callbackGamepadConnected(newGamepad);
  20053. this._startMonitoringGamepads();
  20054. };
  20055. Gamepads.prototype._addNewGamepad = function (gamepad) {
  20056. if (!this.oneGamepadConnected) {
  20057. this.oneGamepadConnected = true;
  20058. if (Gamepads.gamepadDOMInfo) {
  20059. document.body.removeChild(Gamepads.gamepadDOMInfo);
  20060. Gamepads.gamepadDOMInfo = null;
  20061. }
  20062. }
  20063. var newGamepad;
  20064. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  20065. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  20066. } else {
  20067. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  20068. }
  20069. this.babylonGamepads.push(newGamepad);
  20070. return newGamepad;
  20071. };
  20072. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  20073. for (var i in this.babylonGamepads) {
  20074. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  20075. this.babylonGamepads.splice(i, 1);
  20076. break;
  20077. }
  20078. }
  20079. if (this.babylonGamepads.length == 0) {
  20080. this._stopMonitoringGamepads();
  20081. }
  20082. };
  20083. Gamepads.prototype._startMonitoringGamepads = function () {
  20084. if (!this.isMonitoring) {
  20085. this.isMonitoring = true;
  20086. this._checkGamepadsStatus();
  20087. }
  20088. };
  20089. Gamepads.prototype._stopMonitoringGamepads = function () {
  20090. this.isMonitoring = false;
  20091. };
  20092. Gamepads.prototype._checkGamepadsStatus = function () {
  20093. var _this = this;
  20094. this._updateGamepadObjects();
  20095. for (var i in this.babylonGamepads) {
  20096. this.babylonGamepads[i].update();
  20097. }
  20098. if (this.isMonitoring) {
  20099. if (window.requestAnimationFrame) {
  20100. window.requestAnimationFrame(function () {
  20101. _this._checkGamepadsStatus();
  20102. });
  20103. } else if (window.mozRequestAnimationFrame) {
  20104. window.mozRequestAnimationFrame(function () {
  20105. _this._checkGamepadsStatus();
  20106. });
  20107. } else if (window.webkitRequestAnimationFrame) {
  20108. window.webkitRequestAnimationFrame(function () {
  20109. _this._checkGamepadsStatus();
  20110. });
  20111. }
  20112. }
  20113. };
  20114. Gamepads.prototype._updateGamepadObjects = function () {
  20115. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  20116. for (var i = 0; i < gamepads.length; i++) {
  20117. if (gamepads[i]) {
  20118. if (!(gamepads[i].index in this.babylonGamepads)) {
  20119. var newGamepad = this._addNewGamepad(gamepads[i]);
  20120. if (this._callbackGamepadConnected) {
  20121. this._callbackGamepadConnected(newGamepad);
  20122. }
  20123. } else {
  20124. this.babylonGamepads[i].browserGamepad = gamepads[i];
  20125. }
  20126. }
  20127. }
  20128. };
  20129. return Gamepads;
  20130. })();
  20131. BABYLON.Gamepads = Gamepads;
  20132. var StickValues = (function () {
  20133. function StickValues(x, y) {
  20134. this.x = x;
  20135. this.y = y;
  20136. }
  20137. return StickValues;
  20138. })();
  20139. BABYLON.StickValues = StickValues;
  20140. var Gamepad = (function () {
  20141. function Gamepad(id, index, browserGamepad) {
  20142. this.id = id;
  20143. this.index = index;
  20144. this.browserGamepad = browserGamepad;
  20145. if (this.browserGamepad.axes.length >= 2) {
  20146. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  20147. }
  20148. if (this.browserGamepad.axes.length >= 4) {
  20149. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  20150. }
  20151. }
  20152. Gamepad.prototype.onleftstickchanged = function (callback) {
  20153. this._onleftstickchanged = callback;
  20154. };
  20155. Gamepad.prototype.onrightstickchanged = function (callback) {
  20156. this._onrightstickchanged = callback;
  20157. };
  20158. Object.defineProperty(Gamepad.prototype, "leftStick", {
  20159. get: function () {
  20160. return this._leftStick;
  20161. },
  20162. set: function (newValues) {
  20163. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  20164. this._onleftstickchanged(newValues);
  20165. }
  20166. this._leftStick = newValues;
  20167. },
  20168. enumerable: true,
  20169. configurable: true
  20170. });
  20171. Object.defineProperty(Gamepad.prototype, "rightStick", {
  20172. get: function () {
  20173. return this._rightStick;
  20174. },
  20175. set: function (newValues) {
  20176. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  20177. this._onrightstickchanged(newValues);
  20178. }
  20179. this._rightStick = newValues;
  20180. },
  20181. enumerable: true,
  20182. configurable: true
  20183. });
  20184. Gamepad.prototype.update = function () {
  20185. if (this._leftStick) {
  20186. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  20187. }
  20188. if (this._rightStick) {
  20189. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  20190. }
  20191. };
  20192. return Gamepad;
  20193. })();
  20194. BABYLON.Gamepad = Gamepad;
  20195. var GenericPad = (function (_super) {
  20196. __extends(GenericPad, _super);
  20197. function GenericPad(id, index, gamepad) {
  20198. _super.call(this, id, index, gamepad);
  20199. this.id = id;
  20200. this.index = index;
  20201. this.gamepad = gamepad;
  20202. this._buttons = new Array(gamepad.buttons.length);
  20203. }
  20204. GenericPad.prototype.onbuttondown = function (callback) {
  20205. this._onbuttondown = callback;
  20206. };
  20207. GenericPad.prototype.onbuttonup = function (callback) {
  20208. this._onbuttonup = callback;
  20209. };
  20210. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  20211. if (newValue !== currentValue) {
  20212. if (this._onbuttondown && newValue === 1) {
  20213. this._onbuttondown(buttonIndex);
  20214. }
  20215. if (this._onbuttonup && newValue === 0) {
  20216. this._onbuttonup(buttonIndex);
  20217. }
  20218. }
  20219. return newValue;
  20220. };
  20221. GenericPad.prototype.update = function () {
  20222. _super.prototype.update.call(this);
  20223. for (var index = 0; index < this._buttons.length; index++) {
  20224. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  20225. }
  20226. };
  20227. return GenericPad;
  20228. })(Gamepad);
  20229. BABYLON.GenericPad = GenericPad;
  20230. (function (Xbox360Button) {
  20231. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  20232. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  20233. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  20234. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  20235. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  20236. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  20237. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  20238. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  20239. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  20240. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  20241. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  20242. var Xbox360Button = BABYLON.Xbox360Button;
  20243. (function (Xbox360Dpad) {
  20244. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  20245. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  20246. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  20247. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  20248. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  20249. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  20250. var Xbox360Pad = (function (_super) {
  20251. __extends(Xbox360Pad, _super);
  20252. function Xbox360Pad() {
  20253. _super.apply(this, arguments);
  20254. this._leftTrigger = 0;
  20255. this._rightTrigger = 0;
  20256. this._buttonA = 0;
  20257. this._buttonB = 0;
  20258. this._buttonX = 0;
  20259. this._buttonY = 0;
  20260. this._buttonBack = 0;
  20261. this._buttonStart = 0;
  20262. this._buttonLB = 0;
  20263. this._buttonRB = 0;
  20264. this._buttonLeftStick = 0;
  20265. this._buttonRightStick = 0;
  20266. this._dPadUp = 0;
  20267. this._dPadDown = 0;
  20268. this._dPadLeft = 0;
  20269. this._dPadRight = 0;
  20270. }
  20271. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  20272. this._onlefttriggerchanged = callback;
  20273. };
  20274. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  20275. this._onrighttriggerchanged = callback;
  20276. };
  20277. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  20278. get: function () {
  20279. return this._leftTrigger;
  20280. },
  20281. set: function (newValue) {
  20282. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  20283. this._onlefttriggerchanged(newValue);
  20284. }
  20285. this._leftTrigger = newValue;
  20286. },
  20287. enumerable: true,
  20288. configurable: true
  20289. });
  20290. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  20291. get: function () {
  20292. return this._rightTrigger;
  20293. },
  20294. set: function (newValue) {
  20295. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  20296. this._onrighttriggerchanged(newValue);
  20297. }
  20298. this._rightTrigger = newValue;
  20299. },
  20300. enumerable: true,
  20301. configurable: true
  20302. });
  20303. Xbox360Pad.prototype.onbuttondown = function (callback) {
  20304. this._onbuttondown = callback;
  20305. };
  20306. Xbox360Pad.prototype.onbuttonup = function (callback) {
  20307. this._onbuttonup = callback;
  20308. };
  20309. Xbox360Pad.prototype.ondpaddown = function (callback) {
  20310. this._ondpaddown = callback;
  20311. };
  20312. Xbox360Pad.prototype.ondpadup = function (callback) {
  20313. this._ondpadup = callback;
  20314. };
  20315. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  20316. if (newValue !== currentValue) {
  20317. if (this._onbuttondown && newValue === 1) {
  20318. this._onbuttondown(buttonType);
  20319. }
  20320. if (this._onbuttonup && newValue === 0) {
  20321. this._onbuttonup(buttonType);
  20322. }
  20323. }
  20324. return newValue;
  20325. };
  20326. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  20327. if (newValue !== currentValue) {
  20328. if (this._ondpaddown && newValue === 1) {
  20329. this._ondpaddown(buttonType);
  20330. }
  20331. if (this._ondpadup && newValue === 0) {
  20332. this._ondpadup(buttonType);
  20333. }
  20334. }
  20335. return newValue;
  20336. };
  20337. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  20338. get: function () {
  20339. return this._buttonA;
  20340. },
  20341. set: function (value) {
  20342. this._buttonA = this._setButtonValue(value, this._buttonA, 0 /* A */);
  20343. },
  20344. enumerable: true,
  20345. configurable: true
  20346. });
  20347. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  20348. get: function () {
  20349. return this._buttonB;
  20350. },
  20351. set: function (value) {
  20352. this._buttonB = this._setButtonValue(value, this._buttonB, 1 /* B */);
  20353. },
  20354. enumerable: true,
  20355. configurable: true
  20356. });
  20357. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  20358. get: function () {
  20359. return this._buttonX;
  20360. },
  20361. set: function (value) {
  20362. this._buttonX = this._setButtonValue(value, this._buttonX, 2 /* X */);
  20363. },
  20364. enumerable: true,
  20365. configurable: true
  20366. });
  20367. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  20368. get: function () {
  20369. return this._buttonY;
  20370. },
  20371. set: function (value) {
  20372. this._buttonY = this._setButtonValue(value, this._buttonY, 3 /* Y */);
  20373. },
  20374. enumerable: true,
  20375. configurable: true
  20376. });
  20377. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  20378. get: function () {
  20379. return this._buttonStart;
  20380. },
  20381. set: function (value) {
  20382. this._buttonStart = this._setButtonValue(value, this._buttonStart, 4 /* Start */);
  20383. },
  20384. enumerable: true,
  20385. configurable: true
  20386. });
  20387. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  20388. get: function () {
  20389. return this._buttonBack;
  20390. },
  20391. set: function (value) {
  20392. this._buttonBack = this._setButtonValue(value, this._buttonBack, 5 /* Back */);
  20393. },
  20394. enumerable: true,
  20395. configurable: true
  20396. });
  20397. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  20398. get: function () {
  20399. return this._buttonLB;
  20400. },
  20401. set: function (value) {
  20402. this._buttonLB = this._setButtonValue(value, this._buttonLB, 6 /* LB */);
  20403. },
  20404. enumerable: true,
  20405. configurable: true
  20406. });
  20407. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  20408. get: function () {
  20409. return this._buttonRB;
  20410. },
  20411. set: function (value) {
  20412. this._buttonRB = this._setButtonValue(value, this._buttonRB, 7 /* RB */);
  20413. },
  20414. enumerable: true,
  20415. configurable: true
  20416. });
  20417. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  20418. get: function () {
  20419. return this._buttonLeftStick;
  20420. },
  20421. set: function (value) {
  20422. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, 8 /* LeftStick */);
  20423. },
  20424. enumerable: true,
  20425. configurable: true
  20426. });
  20427. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  20428. get: function () {
  20429. return this._buttonRightStick;
  20430. },
  20431. set: function (value) {
  20432. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, 9 /* RightStick */);
  20433. },
  20434. enumerable: true,
  20435. configurable: true
  20436. });
  20437. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  20438. get: function () {
  20439. return this._dPadUp;
  20440. },
  20441. set: function (value) {
  20442. this._dPadUp = this._setDPadValue(value, this._dPadUp, 0 /* Up */);
  20443. },
  20444. enumerable: true,
  20445. configurable: true
  20446. });
  20447. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  20448. get: function () {
  20449. return this._dPadDown;
  20450. },
  20451. set: function (value) {
  20452. this._dPadDown = this._setDPadValue(value, this._dPadDown, 1 /* Down */);
  20453. },
  20454. enumerable: true,
  20455. configurable: true
  20456. });
  20457. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  20458. get: function () {
  20459. return this._dPadLeft;
  20460. },
  20461. set: function (value) {
  20462. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, 2 /* Left */);
  20463. },
  20464. enumerable: true,
  20465. configurable: true
  20466. });
  20467. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  20468. get: function () {
  20469. return this._dPadRight;
  20470. },
  20471. set: function (value) {
  20472. this._dPadRight = this._setDPadValue(value, this._dPadRight, 3 /* Right */);
  20473. },
  20474. enumerable: true,
  20475. configurable: true
  20476. });
  20477. Xbox360Pad.prototype.update = function () {
  20478. _super.prototype.update.call(this);
  20479. this.buttonA = this.browserGamepad.buttons[0].value;
  20480. this.buttonB = this.browserGamepad.buttons[1].value;
  20481. this.buttonX = this.browserGamepad.buttons[2].value;
  20482. this.buttonY = this.browserGamepad.buttons[3].value;
  20483. this.buttonLB = this.browserGamepad.buttons[4].value;
  20484. this.buttonRB = this.browserGamepad.buttons[5].value;
  20485. this.leftTrigger = this.browserGamepad.buttons[6].value;
  20486. this.rightTrigger = this.browserGamepad.buttons[7].value;
  20487. this.buttonBack = this.browserGamepad.buttons[8].value;
  20488. this.buttonStart = this.browserGamepad.buttons[9].value;
  20489. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  20490. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  20491. this.dPadUp = this.browserGamepad.buttons[12].value;
  20492. this.dPadDown = this.browserGamepad.buttons[13].value;
  20493. this.dPadLeft = this.browserGamepad.buttons[14].value;
  20494. this.dPadRight = this.browserGamepad.buttons[15].value;
  20495. };
  20496. return Xbox360Pad;
  20497. })(Gamepad);
  20498. BABYLON.Xbox360Pad = Xbox360Pad;
  20499. })(BABYLON || (BABYLON = {}));
  20500. var __extends = this.__extends || function (d, b) {
  20501. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  20502. function __() { this.constructor = d; }
  20503. __.prototype = b.prototype;
  20504. d.prototype = new __();
  20505. };
  20506. var BABYLON;
  20507. (function (BABYLON) {
  20508. var GamepadCamera = (function (_super) {
  20509. __extends(GamepadCamera, _super);
  20510. function GamepadCamera(name, position, scene) {
  20511. var _this = this;
  20512. _super.call(this, name, position, scene);
  20513. this.angularSensibility = 200;
  20514. this.moveSensibility = 75;
  20515. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  20516. _this._onNewGameConnected(gamepad);
  20517. });
  20518. }
  20519. GamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  20520. if (gamepad.index === 0) {
  20521. this._gamepad = gamepad;
  20522. }
  20523. };
  20524. GamepadCamera.prototype._checkInputs = function () {
  20525. if (!this._gamepad) {
  20526. return;
  20527. }
  20528. var LSValues = this._gamepad.leftStick;
  20529. var normalizedLX = LSValues.x / this.moveSensibility;
  20530. var normalizedLY = LSValues.y / this.moveSensibility;
  20531. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  20532. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  20533. var RSValues = this._gamepad.rightStick;
  20534. var normalizedRX = RSValues.x / this.angularSensibility;
  20535. var normalizedRY = RSValues.y / this.angularSensibility;
  20536. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  20537. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  20538. ;
  20539. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  20540. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x, 0, -LSValues.y), cameraTransform);
  20541. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  20542. this.cameraRotation = this.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  20543. };
  20544. GamepadCamera.prototype.dispose = function () {
  20545. this._gamepads.dispose();
  20546. _super.prototype.dispose.call(this);
  20547. };
  20548. return GamepadCamera;
  20549. })(BABYLON.FreeCamera);
  20550. BABYLON.GamepadCamera = GamepadCamera;
  20551. })(BABYLON || (BABYLON = {}));
  20552. var __extends = this.__extends || function (d, b) {
  20553. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  20554. function __() { this.constructor = d; }
  20555. __.prototype = b.prototype;
  20556. d.prototype = new __();
  20557. };
  20558. var BABYLON;
  20559. (function (BABYLON) {
  20560. var LinesMesh = (function (_super) {
  20561. __extends(LinesMesh, _super);
  20562. function LinesMesh(name, scene, updatable) {
  20563. if (typeof updatable === "undefined") { updatable = false; }
  20564. _super.call(this, name, scene);
  20565. this.color = new BABYLON.Color3(1, 1, 1);
  20566. this.alpha = 1;
  20567. this._indices = new Array();
  20568. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  20569. attributes: ["position"],
  20570. uniforms: ["worldViewProjection", "color"],
  20571. needAlphaBlending: true
  20572. });
  20573. }
  20574. Object.defineProperty(LinesMesh.prototype, "material", {
  20575. get: function () {
  20576. return this._colorShader;
  20577. },
  20578. enumerable: true,
  20579. configurable: true
  20580. });
  20581. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  20582. get: function () {
  20583. return false;
  20584. },
  20585. enumerable: true,
  20586. configurable: true
  20587. });
  20588. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  20589. get: function () {
  20590. return false;
  20591. },
  20592. enumerable: true,
  20593. configurable: true
  20594. });
  20595. LinesMesh.prototype._bind = function (subMesh, effect, wireframe) {
  20596. var engine = this.getScene().getEngine();
  20597. var indexToBind = this._geometry.getIndexBuffer();
  20598. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  20599. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  20600. };
  20601. LinesMesh.prototype._draw = function (subMesh, useTriangles, instancesCount) {
  20602. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  20603. return;
  20604. }
  20605. var engine = this.getScene().getEngine();
  20606. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  20607. };
  20608. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  20609. return null;
  20610. };
  20611. LinesMesh.prototype.dispose = function (doNotRecurse) {
  20612. this._colorShader.dispose();
  20613. _super.prototype.dispose.call(this, doNotRecurse);
  20614. };
  20615. return LinesMesh;
  20616. })(BABYLON.Mesh);
  20617. BABYLON.LinesMesh = LinesMesh;
  20618. })(BABYLON || (BABYLON = {}));
  20619. var BABYLON;
  20620. (function (BABYLON) {
  20621. var OutlineRenderer = (function () {
  20622. function OutlineRenderer(scene) {
  20623. this._scene = scene;
  20624. }
  20625. OutlineRenderer.prototype.render = function (subMesh, batch) {
  20626. var scene = this._scene;
  20627. var engine = this._scene.getEngine();
  20628. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances !== null);
  20629. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  20630. return;
  20631. }
  20632. var mesh = subMesh.getRenderingMesh();
  20633. var material = subMesh.getMaterial();
  20634. engine.enableEffect(this._effect);
  20635. this._effect.setFloat("offset", mesh.outlineWidth);
  20636. this._effect.setColor3("color", mesh.outlineColor);
  20637. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  20638. var useBones = mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  20639. if (useBones) {
  20640. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  20641. }
  20642. mesh._bind(subMesh, this._effect, false);
  20643. if (material && material.needAlphaTesting()) {
  20644. var alphaTexture = material.getAlphaTestTexture();
  20645. this._effect.setTexture("diffuseSampler", alphaTexture);
  20646. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  20647. }
  20648. if (hardwareInstancedRendering) {
  20649. mesh._renderWithInstances(subMesh, false, batch, this._effect, engine);
  20650. } else {
  20651. if (batch.renderSelf[subMesh._id]) {
  20652. this._effect.setMatrix("world", mesh.getWorldMatrix());
  20653. mesh._draw(subMesh, true);
  20654. }
  20655. if (batch.visibleInstances[subMesh._id]) {
  20656. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  20657. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  20658. this._effect.setMatrix("world", instance.getWorldMatrix());
  20659. mesh._draw(subMesh, true);
  20660. }
  20661. }
  20662. }
  20663. };
  20664. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  20665. var defines = [];
  20666. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  20667. var mesh = subMesh.getMesh();
  20668. var material = subMesh.getMaterial();
  20669. if (material && material.needAlphaTesting()) {
  20670. defines.push("#define ALPHATEST");
  20671. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  20672. attribs.push(BABYLON.VertexBuffer.UVKind);
  20673. defines.push("#define UV1");
  20674. }
  20675. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  20676. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  20677. defines.push("#define UV2");
  20678. }
  20679. }
  20680. if (mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  20681. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  20682. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  20683. defines.push("#define BONES");
  20684. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  20685. }
  20686. if (useInstances) {
  20687. defines.push("#define INSTANCES");
  20688. attribs.push("world0");
  20689. attribs.push("world1");
  20690. attribs.push("world2");
  20691. attribs.push("world3");
  20692. }
  20693. var join = defines.join("\n");
  20694. if (this._cachedDefines != join) {
  20695. this._cachedDefines = join;
  20696. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  20697. }
  20698. return this._effect.isReady();
  20699. };
  20700. return OutlineRenderer;
  20701. })();
  20702. BABYLON.OutlineRenderer = OutlineRenderer;
  20703. })(BABYLON || (BABYLON = {}));
  20704. var BABYLON;
  20705. (function (BABYLON) {
  20706. var MeshAssetTask = (function () {
  20707. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  20708. this.name = name;
  20709. this.meshesNames = meshesNames;
  20710. this.rootUrl = rootUrl;
  20711. this.sceneFilename = sceneFilename;
  20712. this.isCompleted = false;
  20713. }
  20714. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  20715. var _this = this;
  20716. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  20717. _this.loadedMeshes = meshes;
  20718. _this.loadedParticleSystems = particleSystems;
  20719. _this.loadedSkeletons = skeletons;
  20720. _this.isCompleted = true;
  20721. if (_this.onSuccess) {
  20722. _this.onSuccess(_this);
  20723. }
  20724. onSuccess();
  20725. }, null, function () {
  20726. if (_this.onError) {
  20727. _this.onError(_this);
  20728. }
  20729. onError();
  20730. });
  20731. };
  20732. return MeshAssetTask;
  20733. })();
  20734. BABYLON.MeshAssetTask = MeshAssetTask;
  20735. var TextFileAssetTask = (function () {
  20736. function TextFileAssetTask(name, url) {
  20737. this.name = name;
  20738. this.url = url;
  20739. this.isCompleted = false;
  20740. }
  20741. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  20742. var _this = this;
  20743. BABYLON.Tools.LoadFile(this.url, function (data) {
  20744. _this.text = data;
  20745. _this.isCompleted = true;
  20746. if (_this.onSuccess) {
  20747. _this.onSuccess(_this);
  20748. }
  20749. onSuccess();
  20750. }, null, scene.database, false, function () {
  20751. if (_this.onError) {
  20752. _this.onError(_this);
  20753. }
  20754. onError();
  20755. });
  20756. };
  20757. return TextFileAssetTask;
  20758. })();
  20759. BABYLON.TextFileAssetTask = TextFileAssetTask;
  20760. var BinaryFileAssetTask = (function () {
  20761. function BinaryFileAssetTask(name, url) {
  20762. this.name = name;
  20763. this.url = url;
  20764. this.isCompleted = false;
  20765. }
  20766. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  20767. var _this = this;
  20768. BABYLON.Tools.LoadFile(this.url, function (data) {
  20769. _this.data = data;
  20770. _this.isCompleted = true;
  20771. if (_this.onSuccess) {
  20772. _this.onSuccess(_this);
  20773. }
  20774. onSuccess();
  20775. }, null, scene.database, true, function () {
  20776. if (_this.onError) {
  20777. _this.onError(_this);
  20778. }
  20779. onError();
  20780. });
  20781. };
  20782. return BinaryFileAssetTask;
  20783. })();
  20784. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  20785. var ImageAssetTask = (function () {
  20786. function ImageAssetTask(name, url) {
  20787. this.name = name;
  20788. this.url = url;
  20789. this.isCompleted = false;
  20790. }
  20791. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  20792. var _this = this;
  20793. var img = new Image();
  20794. img.onload = function () {
  20795. _this.image = img;
  20796. _this.isCompleted = true;
  20797. if (_this.onSuccess) {
  20798. _this.onSuccess(_this);
  20799. }
  20800. onSuccess();
  20801. };
  20802. img.onerror = function () {
  20803. if (_this.onError) {
  20804. _this.onError(_this);
  20805. }
  20806. onError();
  20807. };
  20808. img.src = this.url;
  20809. };
  20810. return ImageAssetTask;
  20811. })();
  20812. BABYLON.ImageAssetTask = ImageAssetTask;
  20813. var TextureAssetTask = (function () {
  20814. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  20815. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  20816. this.name = name;
  20817. this.url = url;
  20818. this.noMipmap = noMipmap;
  20819. this.invertY = invertY;
  20820. this.samplingMode = samplingMode;
  20821. this.isCompleted = false;
  20822. }
  20823. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  20824. var _this = this;
  20825. var onload = function () {
  20826. _this.isCompleted = true;
  20827. if (_this.onSuccess) {
  20828. _this.onSuccess(_this);
  20829. }
  20830. onSuccess();
  20831. };
  20832. var onerror = function () {
  20833. if (_this.onError) {
  20834. _this.onError(_this);
  20835. }
  20836. onError();
  20837. };
  20838. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onError);
  20839. };
  20840. return TextureAssetTask;
  20841. })();
  20842. BABYLON.TextureAssetTask = TextureAssetTask;
  20843. var AssetsManager = (function () {
  20844. function AssetsManager(scene) {
  20845. this._tasks = new Array();
  20846. this._waitingTasksCount = 0;
  20847. this.useDefaultLoadingScreen = true;
  20848. this._scene = scene;
  20849. }
  20850. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  20851. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  20852. this._tasks.push(task);
  20853. return task;
  20854. };
  20855. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  20856. var task = new TextFileAssetTask(taskName, url);
  20857. this._tasks.push(task);
  20858. return task;
  20859. };
  20860. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  20861. var task = new BinaryFileAssetTask(taskName, url);
  20862. this._tasks.push(task);
  20863. return task;
  20864. };
  20865. AssetsManager.prototype.addImageTask = function (taskName, url) {
  20866. var task = new ImageAssetTask(taskName, url);
  20867. this._tasks.push(task);
  20868. return task;
  20869. };
  20870. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  20871. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  20872. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  20873. this._tasks.push(task);
  20874. return task;
  20875. };
  20876. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  20877. this._waitingTasksCount--;
  20878. if (this._waitingTasksCount === 0) {
  20879. if (this.onFinish) {
  20880. this.onFinish(this._tasks);
  20881. }
  20882. this._scene.getEngine().hideLoadingUI();
  20883. }
  20884. };
  20885. AssetsManager.prototype._runTask = function (task) {
  20886. var _this = this;
  20887. task.run(this._scene, function () {
  20888. if (_this.onTaskSuccess) {
  20889. _this.onTaskSuccess(task);
  20890. }
  20891. _this._decreaseWaitingTasksCount();
  20892. }, function () {
  20893. if (_this.onTaskError) {
  20894. _this.onTaskError(task);
  20895. }
  20896. _this._decreaseWaitingTasksCount();
  20897. });
  20898. };
  20899. AssetsManager.prototype.reset = function () {
  20900. this._tasks = new Array();
  20901. return this;
  20902. };
  20903. AssetsManager.prototype.load = function () {
  20904. this._waitingTasksCount = this._tasks.length;
  20905. if (this._waitingTasksCount === 0) {
  20906. if (this.onFinish) {
  20907. this.onFinish(this._tasks);
  20908. }
  20909. return this;
  20910. }
  20911. if (this.useDefaultLoadingScreen) {
  20912. this._scene.getEngine().displayLoadingUI();
  20913. }
  20914. for (var index = 0; index < this._tasks.length; index++) {
  20915. var task = this._tasks[index];
  20916. this._runTask(task);
  20917. }
  20918. return this;
  20919. };
  20920. return AssetsManager;
  20921. })();
  20922. BABYLON.AssetsManager = AssetsManager;
  20923. })(BABYLON || (BABYLON = {}));
  20924. var __extends = this.__extends || function (d, b) {
  20925. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  20926. function __() { this.constructor = d; }
  20927. __.prototype = b.prototype;
  20928. d.prototype = new __();
  20929. };
  20930. var BABYLON;
  20931. (function (BABYLON) {
  20932. var VRDeviceOrientationCamera = (function (_super) {
  20933. __extends(VRDeviceOrientationCamera, _super);
  20934. function VRDeviceOrientationCamera(name, position, scene) {
  20935. _super.call(this, name, position, scene);
  20936. this._alpha = 0;
  20937. this._beta = 0;
  20938. this._gamma = 0;
  20939. }
  20940. VRDeviceOrientationCamera.prototype._onOrientationEvent = function (evt) {
  20941. this._alpha = +evt.alpha | 0;
  20942. this._beta = +evt.beta | 0;
  20943. this._gamma = +evt.gamma | 0;
  20944. if (this._gamma < 0) {
  20945. this._gamma = 90 + this._gamma;
  20946. } else {
  20947. this._gamma = 270 - this._gamma;
  20948. }
  20949. this.rotation.x = this._gamma / 180.0 * Math.PI;
  20950. this.rotation.y = -this._alpha / 180.0 * Math.PI;
  20951. this.rotation.z = this._beta / 180.0 * Math.PI;
  20952. };
  20953. return VRDeviceOrientationCamera;
  20954. })(BABYLON.OculusCamera);
  20955. BABYLON.VRDeviceOrientationCamera = VRDeviceOrientationCamera;
  20956. })(BABYLON || (BABYLON = {}));
  20957. var __extends = this.__extends || function (d, b) {
  20958. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  20959. function __() { this.constructor = d; }
  20960. __.prototype = b.prototype;
  20961. d.prototype = new __();
  20962. };
  20963. var BABYLON;
  20964. (function (BABYLON) {
  20965. var WebVRCamera = (function (_super) {
  20966. __extends(WebVRCamera, _super);
  20967. function WebVRCamera(name, position, scene) {
  20968. _super.call(this, name, position, scene);
  20969. this._hmdDevice = null;
  20970. this._sensorDevice = null;
  20971. this._cacheState = null;
  20972. this._cacheQuaternion = new BABYLON.Quaternion();
  20973. this._cacheRotation = BABYLON.Vector3.Zero();
  20974. this._vrEnabled = false;
  20975. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  20976. }
  20977. WebVRCamera.prototype._getWebVRDevices = function (devices) {
  20978. var size = devices.length;
  20979. var i = 0;
  20980. this._sensorDevice = null;
  20981. this._hmdDevice = null;
  20982. while (i < size && this._hmdDevice === null) {
  20983. if (devices[i] instanceof HMDVRDevice) {
  20984. this._hmdDevice = devices[i];
  20985. }
  20986. i++;
  20987. }
  20988. i = 0;
  20989. while (i < size && this._sensorDevice === null) {
  20990. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  20991. this._sensorDevice = devices[i];
  20992. }
  20993. i++;
  20994. }
  20995. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  20996. };
  20997. WebVRCamera.prototype._update = function () {
  20998. if (this._vrEnabled) {
  20999. this._cacheState = this._sensorDevice.getState();
  21000. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  21001. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  21002. this.rotation.x = -this._cacheRotation.z;
  21003. this.rotation.y = -this._cacheRotation.y;
  21004. this.rotation.z = this._cacheRotation.x;
  21005. }
  21006. _super.prototype._update.call(this);
  21007. };
  21008. WebVRCamera.prototype.attachControl = function (element, noPreventDefault) {
  21009. _super.prototype.attachControl.call(this, element, noPreventDefault);
  21010. if (navigator.getVRDevices) {
  21011. navigator.getVRDevices().then(this._getWebVRDevices);
  21012. } else if (navigator.mozGetVRDevices) {
  21013. navigator.mozGetVRDevices(this._getWebVRDevices);
  21014. }
  21015. };
  21016. WebVRCamera.prototype.detachControl = function (element) {
  21017. _super.prototype.detachControl.call(this, element);
  21018. this._vrEnabled = false;
  21019. };
  21020. return WebVRCamera;
  21021. })(BABYLON.OculusCamera);
  21022. BABYLON.WebVRCamera = WebVRCamera;
  21023. })(BABYLON || (BABYLON = {}));