babylon.2.0-alpha.debug.js 1.1 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739
  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 Vector4 = (function () {
  698. function Vector4(x, y, z, w) {
  699. this.x = x;
  700. this.y = y;
  701. this.z = z;
  702. this.w = w;
  703. }
  704. Vector4.prototype.toString = function () {
  705. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "W:" + this.w + "}";
  706. };
  707. Vector4.prototype.asArray = function () {
  708. var result = [];
  709. this.toArray(result, 0);
  710. return result;
  711. };
  712. Vector4.prototype.toArray = function (array, index) {
  713. if (index === undefined) {
  714. index = 0;
  715. }
  716. array[index] = this.x;
  717. array[index + 1] = this.y;
  718. array[index + 2] = this.z;
  719. array[index + 3] = this.w;
  720. };
  721. Vector4.prototype.addInPlace = function (otherVector) {
  722. this.x += otherVector.x;
  723. this.y += otherVector.y;
  724. this.z += otherVector.z;
  725. this.w += otherVector.w;
  726. };
  727. Vector4.prototype.add = function (otherVector) {
  728. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  729. };
  730. Vector4.prototype.addToRef = function (otherVector, result) {
  731. result.x = this.x + otherVector.x;
  732. result.y = this.y + otherVector.y;
  733. result.z = this.z + otherVector.z;
  734. result.w = this.w + otherVector.w;
  735. };
  736. Vector4.prototype.subtractInPlace = function (otherVector) {
  737. this.x -= otherVector.x;
  738. this.y -= otherVector.y;
  739. this.z -= otherVector.z;
  740. this.w -= otherVector.w;
  741. };
  742. Vector4.prototype.subtract = function (otherVector) {
  743. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  744. };
  745. Vector4.prototype.subtractToRef = function (otherVector, result) {
  746. result.x = this.x - otherVector.x;
  747. result.y = this.y - otherVector.y;
  748. result.z = this.z - otherVector.z;
  749. result.w = this.w - otherVector.w;
  750. };
  751. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  752. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  753. };
  754. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  755. result.x = this.x - x;
  756. result.y = this.y - y;
  757. result.z = this.z - z;
  758. result.w = this.w - w;
  759. };
  760. Vector4.prototype.negate = function () {
  761. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  762. };
  763. Vector4.prototype.scaleInPlace = function (scale) {
  764. this.x *= scale;
  765. this.y *= scale;
  766. this.z *= scale;
  767. this.w *= scale;
  768. return this;
  769. };
  770. Vector4.prototype.scale = function (scale) {
  771. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  772. };
  773. Vector4.prototype.scaleToRef = function (scale, result) {
  774. result.x = this.x * scale;
  775. result.y = this.y * scale;
  776. result.z = this.z * scale;
  777. result.w = this.w * scale;
  778. };
  779. Vector4.prototype.equals = function (otherVector) {
  780. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  781. };
  782. Vector4.prototype.equalsWithEpsilon = function (otherVector) {
  783. return Math.abs(this.x - otherVector.x) < BABYLON.Engine.Epsilon && Math.abs(this.y - otherVector.y) < BABYLON.Engine.Epsilon && Math.abs(this.z - otherVector.z) < BABYLON.Engine.Epsilon && Math.abs(this.w - otherVector.w) < BABYLON.Engine.Epsilon;
  784. };
  785. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  786. return this.x === x && this.y === y && this.z === z && this.w === w;
  787. };
  788. Vector4.prototype.multiplyInPlace = function (otherVector) {
  789. this.x *= otherVector.x;
  790. this.y *= otherVector.y;
  791. this.z *= otherVector.z;
  792. this.w *= otherVector.w;
  793. };
  794. Vector4.prototype.multiply = function (otherVector) {
  795. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  796. };
  797. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  798. result.x = this.x * otherVector.x;
  799. result.y = this.y * otherVector.y;
  800. result.z = this.z * otherVector.z;
  801. result.w = this.w * otherVector.w;
  802. };
  803. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  804. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  805. };
  806. Vector4.prototype.divide = function (otherVector) {
  807. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  808. };
  809. Vector4.prototype.divideToRef = function (otherVector, result) {
  810. result.x = this.x / otherVector.x;
  811. result.y = this.y / otherVector.y;
  812. result.z = this.z / otherVector.z;
  813. result.w = this.w / otherVector.w;
  814. };
  815. Vector4.prototype.MinimizeInPlace = function (other) {
  816. if (other.x < this.x)
  817. this.x = other.x;
  818. if (other.y < this.y)
  819. this.y = other.y;
  820. if (other.z < this.z)
  821. this.z = other.z;
  822. if (other.w < this.w)
  823. this.w = other.w;
  824. };
  825. Vector4.prototype.MaximizeInPlace = function (other) {
  826. if (other.x > this.x)
  827. this.x = other.x;
  828. if (other.y > this.y)
  829. this.y = other.y;
  830. if (other.z > this.z)
  831. this.z = other.z;
  832. if (other.w > this.w)
  833. this.w = other.w;
  834. };
  835. Vector4.prototype.length = function () {
  836. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  837. };
  838. Vector4.prototype.lengthSquared = function () {
  839. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  840. };
  841. Vector4.prototype.normalize = function () {
  842. var len = this.length();
  843. if (len === 0)
  844. return this;
  845. var num = 1.0 / len;
  846. this.x *= num;
  847. this.y *= num;
  848. this.z *= num;
  849. this.w *= num;
  850. return this;
  851. };
  852. Vector4.prototype.clone = function () {
  853. return new Vector4(this.x, this.y, this.z, this.w);
  854. };
  855. Vector4.prototype.copyFrom = function (source) {
  856. this.x = source.x;
  857. this.y = source.y;
  858. this.z = source.z;
  859. this.w = source.w;
  860. };
  861. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  862. this.x = x;
  863. this.y = y;
  864. this.z = z;
  865. this.w = w;
  866. };
  867. Vector4.FromArray = function (array, offset) {
  868. if (!offset) {
  869. offset = 0;
  870. }
  871. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  872. };
  873. Vector4.FromArrayToRef = function (array, offset, result) {
  874. result.x = array[offset];
  875. result.y = array[offset + 1];
  876. result.z = array[offset + 2];
  877. result.w = array[offset + 3];
  878. };
  879. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  880. result.x = array[offset];
  881. result.y = array[offset + 1];
  882. result.z = array[offset + 2];
  883. result.w = array[offset + 3];
  884. };
  885. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  886. result.x = x;
  887. result.y = y;
  888. result.z = z;
  889. result.w = w;
  890. };
  891. Vector4.Zero = function () {
  892. return new Vector4(0, 0, 0, 0);
  893. };
  894. Vector4.Normalize = function (vector) {
  895. var result = Vector4.Zero();
  896. Vector4.NormalizeToRef(vector, result);
  897. return result;
  898. };
  899. Vector4.NormalizeToRef = function (vector, result) {
  900. result.copyFrom(vector);
  901. result.normalize();
  902. };
  903. Vector4.Minimize = function (left, right) {
  904. var min = left.clone();
  905. min.MinimizeInPlace(right);
  906. return min;
  907. };
  908. Vector4.Maximize = function (left, right) {
  909. var max = left.clone();
  910. max.MaximizeInPlace(right);
  911. return max;
  912. };
  913. Vector4.Distance = function (value1, value2) {
  914. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  915. };
  916. Vector4.DistanceSquared = function (value1, value2) {
  917. var x = value1.x - value2.x;
  918. var y = value1.y - value2.y;
  919. var z = value1.z - value2.z;
  920. var w = value1.w - value2.w;
  921. return (x * x) + (y * y) + (z * z) + (w * w);
  922. };
  923. Vector4.Center = function (value1, value2) {
  924. var center = value1.add(value2);
  925. center.scaleInPlace(0.5);
  926. return center;
  927. };
  928. return Vector4;
  929. })();
  930. BABYLON.Vector4 = Vector4;
  931. var Quaternion = (function () {
  932. function Quaternion(x, y, z, w) {
  933. if (typeof x === "undefined") { x = 0; }
  934. if (typeof y === "undefined") { y = 0; }
  935. if (typeof z === "undefined") { z = 0; }
  936. if (typeof w === "undefined") { w = 1; }
  937. this.x = x;
  938. this.y = y;
  939. this.z = z;
  940. this.w = w;
  941. }
  942. Quaternion.prototype.toString = function () {
  943. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  944. };
  945. Quaternion.prototype.asArray = function () {
  946. return [this.x, this.y, this.z, this.w];
  947. };
  948. Quaternion.prototype.equals = function (otherQuaternion) {
  949. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  950. };
  951. Quaternion.prototype.clone = function () {
  952. return new Quaternion(this.x, this.y, this.z, this.w);
  953. };
  954. Quaternion.prototype.copyFrom = function (other) {
  955. this.x = other.x;
  956. this.y = other.y;
  957. this.z = other.z;
  958. this.w = other.w;
  959. };
  960. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  961. this.x = x;
  962. this.y = y;
  963. this.z = z;
  964. this.w = w;
  965. };
  966. Quaternion.prototype.add = function (other) {
  967. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  968. };
  969. Quaternion.prototype.subtract = function (other) {
  970. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  971. };
  972. Quaternion.prototype.scale = function (value) {
  973. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  974. };
  975. Quaternion.prototype.multiply = function (q1) {
  976. var result = new Quaternion(0, 0, 0, 1.0);
  977. this.multiplyToRef(q1, result);
  978. return result;
  979. };
  980. Quaternion.prototype.multiplyToRef = function (q1, result) {
  981. result.x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  982. result.y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  983. result.z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  984. result.w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  985. };
  986. Quaternion.prototype.length = function () {
  987. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  988. };
  989. Quaternion.prototype.normalize = function () {
  990. var length = 1.0 / this.length();
  991. this.x *= length;
  992. this.y *= length;
  993. this.z *= length;
  994. this.w *= length;
  995. };
  996. Quaternion.prototype.toEulerAngles = function () {
  997. var result = Vector3.Zero();
  998. this.toEulerAnglesToRef(result);
  999. return result;
  1000. };
  1001. Quaternion.prototype.toEulerAnglesToRef = function (result) {
  1002. var qx = this.x;
  1003. var qy = this.y;
  1004. var qz = this.z;
  1005. var qw = this.w;
  1006. var qxy = qx * qy;
  1007. var qxz = qx * qz;
  1008. var qwy = qw * qy;
  1009. var qwz = qw * qz;
  1010. var qwx = qw * qx;
  1011. var qyz = qy * qz;
  1012. var sqx = qx * qx;
  1013. var sqy = qy * qy;
  1014. var determinant = sqx + sqy;
  1015. if (determinant != 0.000 && determinant != 1.000) {
  1016. result.x = Math.atan2(qxz + qwy, qwx - qyz);
  1017. result.y = Math.acos(1 - 2 * determinant);
  1018. result.z = Math.atan2(qxz - qwy, qwx + qyz);
  1019. } else {
  1020. if (determinant == 0.000) {
  1021. result.x = 0.0;
  1022. result.y = 0.0;
  1023. result.z = Math.atan2(qxy - qwz, 0.5 - sqy - qz * qz);
  1024. } else {
  1025. result.x = Math.atan2(qxy - qwz, 0.5 - sqy - qz * qz);
  1026. result.y = Math.PI;
  1027. result.z = 0.0;
  1028. }
  1029. }
  1030. };
  1031. Quaternion.prototype.toRotationMatrix = function (result) {
  1032. var xx = this.x * this.x;
  1033. var yy = this.y * this.y;
  1034. var zz = this.z * this.z;
  1035. var xy = this.x * this.y;
  1036. var zw = this.z * this.w;
  1037. var zx = this.z * this.x;
  1038. var yw = this.y * this.w;
  1039. var yz = this.y * this.z;
  1040. var xw = this.x * this.w;
  1041. result.m[0] = 1.0 - (2.0 * (yy + zz));
  1042. result.m[1] = 2.0 * (xy + zw);
  1043. result.m[2] = 2.0 * (zx - yw);
  1044. result.m[3] = 0;
  1045. result.m[4] = 2.0 * (xy - zw);
  1046. result.m[5] = 1.0 - (2.0 * (zz + xx));
  1047. result.m[6] = 2.0 * (yz + xw);
  1048. result.m[7] = 0;
  1049. result.m[8] = 2.0 * (zx + yw);
  1050. result.m[9] = 2.0 * (yz - xw);
  1051. result.m[10] = 1.0 - (2.0 * (yy + xx));
  1052. result.m[11] = 0;
  1053. result.m[12] = 0;
  1054. result.m[13] = 0;
  1055. result.m[14] = 0;
  1056. result.m[15] = 1.0;
  1057. };
  1058. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  1059. var data = matrix.m;
  1060. var m11 = data[0], m12 = data[4], m13 = data[8];
  1061. var m21 = data[1], m22 = data[5], m23 = data[9];
  1062. var m31 = data[2], m32 = data[6], m33 = data[10];
  1063. var trace = m11 + m22 + m33;
  1064. var s;
  1065. if (trace > 0) {
  1066. s = 0.5 / Math.sqrt(trace + 1.0);
  1067. this.w = 0.25 / s;
  1068. this.x = (m32 - m23) * s;
  1069. this.y = (m13 - m31) * s;
  1070. this.z = (m21 - m12) * s;
  1071. return;
  1072. }
  1073. if (m11 > m22 && m11 > m33) {
  1074. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1075. this.w = (m32 - m23) / s;
  1076. this.x = 0.25 * s;
  1077. this.y = (m12 + m21) / s;
  1078. this.z = (m13 + m31) / s;
  1079. return;
  1080. }
  1081. if (m22 > m33) {
  1082. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1083. this.w = (m13 - m31) / s;
  1084. this.x = (m12 + m21) / s;
  1085. this.y = 0.25 * s;
  1086. this.z = (m23 + m32) / s;
  1087. return;
  1088. }
  1089. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1090. this.w = (m21 - m12) / s;
  1091. this.x = (m13 + m31) / s;
  1092. this.y = (m23 + m32) / s;
  1093. this.z = 0.25 * s;
  1094. };
  1095. Quaternion.Inverse = function (q) {
  1096. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  1097. };
  1098. Quaternion.RotationAxis = function (axis, angle) {
  1099. var result = new Quaternion();
  1100. var sin = Math.sin(angle / 2);
  1101. result.w = Math.cos(angle / 2);
  1102. result.x = axis.x * sin;
  1103. result.y = axis.y * sin;
  1104. result.z = axis.z * sin;
  1105. return result;
  1106. };
  1107. Quaternion.FromArray = function (array, offset) {
  1108. if (!offset) {
  1109. offset = 0;
  1110. }
  1111. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1112. };
  1113. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1114. var result = new Quaternion();
  1115. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1116. return result;
  1117. };
  1118. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1119. var halfRoll = roll * 0.5;
  1120. var halfPitch = pitch * 0.5;
  1121. var halfYaw = yaw * 0.5;
  1122. var sinRoll = Math.sin(halfRoll);
  1123. var cosRoll = Math.cos(halfRoll);
  1124. var sinPitch = Math.sin(halfPitch);
  1125. var cosPitch = Math.cos(halfPitch);
  1126. var sinYaw = Math.sin(halfYaw);
  1127. var cosYaw = Math.cos(halfYaw);
  1128. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  1129. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  1130. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  1131. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  1132. };
  1133. Quaternion.Slerp = function (left, right, amount) {
  1134. var num2;
  1135. var num3;
  1136. var num = amount;
  1137. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  1138. var flag = false;
  1139. if (num4 < 0) {
  1140. flag = true;
  1141. num4 = -num4;
  1142. }
  1143. if (num4 > 0.999999) {
  1144. num3 = 1 - num;
  1145. num2 = flag ? -num : num;
  1146. } else {
  1147. var num5 = Math.acos(num4);
  1148. var num6 = (1.0 / Math.sin(num5));
  1149. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  1150. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  1151. }
  1152. 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));
  1153. };
  1154. return Quaternion;
  1155. })();
  1156. BABYLON.Quaternion = Quaternion;
  1157. var Matrix = (function () {
  1158. function Matrix() {
  1159. this.m = new Float32Array(16);
  1160. }
  1161. Matrix.prototype.isIdentity = function () {
  1162. if (this.m[0] != 1.0 || this.m[5] != 1.0 || this.m[10] != 1.0 || this.m[15] != 1.0)
  1163. return false;
  1164. 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)
  1165. return false;
  1166. return true;
  1167. };
  1168. Matrix.prototype.determinant = function () {
  1169. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  1170. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  1171. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  1172. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  1173. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  1174. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  1175. 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))));
  1176. };
  1177. Matrix.prototype.toArray = function () {
  1178. return this.m;
  1179. };
  1180. Matrix.prototype.asArray = function () {
  1181. return this.toArray();
  1182. };
  1183. Matrix.prototype.invert = function () {
  1184. this.invertToRef(this);
  1185. };
  1186. Matrix.prototype.invertToRef = function (other) {
  1187. var l1 = this.m[0];
  1188. var l2 = this.m[1];
  1189. var l3 = this.m[2];
  1190. var l4 = this.m[3];
  1191. var l5 = this.m[4];
  1192. var l6 = this.m[5];
  1193. var l7 = this.m[6];
  1194. var l8 = this.m[7];
  1195. var l9 = this.m[8];
  1196. var l10 = this.m[9];
  1197. var l11 = this.m[10];
  1198. var l12 = this.m[11];
  1199. var l13 = this.m[12];
  1200. var l14 = this.m[13];
  1201. var l15 = this.m[14];
  1202. var l16 = this.m[15];
  1203. var l17 = (l11 * l16) - (l12 * l15);
  1204. var l18 = (l10 * l16) - (l12 * l14);
  1205. var l19 = (l10 * l15) - (l11 * l14);
  1206. var l20 = (l9 * l16) - (l12 * l13);
  1207. var l21 = (l9 * l15) - (l11 * l13);
  1208. var l22 = (l9 * l14) - (l10 * l13);
  1209. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  1210. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  1211. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  1212. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  1213. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  1214. var l28 = (l7 * l16) - (l8 * l15);
  1215. var l29 = (l6 * l16) - (l8 * l14);
  1216. var l30 = (l6 * l15) - (l7 * l14);
  1217. var l31 = (l5 * l16) - (l8 * l13);
  1218. var l32 = (l5 * l15) - (l7 * l13);
  1219. var l33 = (l5 * l14) - (l6 * l13);
  1220. var l34 = (l7 * l12) - (l8 * l11);
  1221. var l35 = (l6 * l12) - (l8 * l10);
  1222. var l36 = (l6 * l11) - (l7 * l10);
  1223. var l37 = (l5 * l12) - (l8 * l9);
  1224. var l38 = (l5 * l11) - (l7 * l9);
  1225. var l39 = (l5 * l10) - (l6 * l9);
  1226. other.m[0] = l23 * l27;
  1227. other.m[4] = l24 * l27;
  1228. other.m[8] = l25 * l27;
  1229. other.m[12] = l26 * l27;
  1230. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  1231. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  1232. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  1233. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  1234. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  1235. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  1236. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  1237. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  1238. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  1239. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  1240. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  1241. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  1242. };
  1243. Matrix.prototype.setTranslation = function (vector3) {
  1244. this.m[12] = vector3.x;
  1245. this.m[13] = vector3.y;
  1246. this.m[14] = vector3.z;
  1247. };
  1248. Matrix.prototype.multiply = function (other) {
  1249. var result = new Matrix();
  1250. this.multiplyToRef(other, result);
  1251. return result;
  1252. };
  1253. Matrix.prototype.copyFrom = function (other) {
  1254. for (var index = 0; index < 16; index++) {
  1255. this.m[index] = other.m[index];
  1256. }
  1257. };
  1258. Matrix.prototype.copyToArray = function (array, offset) {
  1259. if (typeof offset === "undefined") { offset = 0; }
  1260. for (var index = 0; index < 16; index++) {
  1261. array[offset + index] = this.m[index];
  1262. }
  1263. };
  1264. Matrix.prototype.multiplyToRef = function (other, result) {
  1265. this.multiplyToArray(other, result.m, 0);
  1266. };
  1267. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1268. var tm0 = this.m[0];
  1269. var tm1 = this.m[1];
  1270. var tm2 = this.m[2];
  1271. var tm3 = this.m[3];
  1272. var tm4 = this.m[4];
  1273. var tm5 = this.m[5];
  1274. var tm6 = this.m[6];
  1275. var tm7 = this.m[7];
  1276. var tm8 = this.m[8];
  1277. var tm9 = this.m[9];
  1278. var tm10 = this.m[10];
  1279. var tm11 = this.m[11];
  1280. var tm12 = this.m[12];
  1281. var tm13 = this.m[13];
  1282. var tm14 = this.m[14];
  1283. var tm15 = this.m[15];
  1284. var om0 = other.m[0];
  1285. var om1 = other.m[1];
  1286. var om2 = other.m[2];
  1287. var om3 = other.m[3];
  1288. var om4 = other.m[4];
  1289. var om5 = other.m[5];
  1290. var om6 = other.m[6];
  1291. var om7 = other.m[7];
  1292. var om8 = other.m[8];
  1293. var om9 = other.m[9];
  1294. var om10 = other.m[10];
  1295. var om11 = other.m[11];
  1296. var om12 = other.m[12];
  1297. var om13 = other.m[13];
  1298. var om14 = other.m[14];
  1299. var om15 = other.m[15];
  1300. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1301. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1302. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1303. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1304. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1305. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1306. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1307. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1308. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1309. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1310. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1311. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1312. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1313. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1314. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1315. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1316. };
  1317. Matrix.prototype.equals = function (value) {
  1318. 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]);
  1319. };
  1320. Matrix.prototype.clone = function () {
  1321. 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]);
  1322. };
  1323. Matrix.FromArray = function (array, offset) {
  1324. var result = new Matrix();
  1325. if (!offset) {
  1326. offset = 0;
  1327. }
  1328. Matrix.FromArrayToRef(array, offset, result);
  1329. return result;
  1330. };
  1331. Matrix.FromArrayToRef = function (array, offset, result) {
  1332. for (var index = 0; index < 16; index++) {
  1333. result.m[index] = array[index + offset];
  1334. }
  1335. };
  1336. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  1337. result.m[0] = initialM11;
  1338. result.m[1] = initialM12;
  1339. result.m[2] = initialM13;
  1340. result.m[3] = initialM14;
  1341. result.m[4] = initialM21;
  1342. result.m[5] = initialM22;
  1343. result.m[6] = initialM23;
  1344. result.m[7] = initialM24;
  1345. result.m[8] = initialM31;
  1346. result.m[9] = initialM32;
  1347. result.m[10] = initialM33;
  1348. result.m[11] = initialM34;
  1349. result.m[12] = initialM41;
  1350. result.m[13] = initialM42;
  1351. result.m[14] = initialM43;
  1352. result.m[15] = initialM44;
  1353. };
  1354. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  1355. var result = new Matrix();
  1356. result.m[0] = initialM11;
  1357. result.m[1] = initialM12;
  1358. result.m[2] = initialM13;
  1359. result.m[3] = initialM14;
  1360. result.m[4] = initialM21;
  1361. result.m[5] = initialM22;
  1362. result.m[6] = initialM23;
  1363. result.m[7] = initialM24;
  1364. result.m[8] = initialM31;
  1365. result.m[9] = initialM32;
  1366. result.m[10] = initialM33;
  1367. result.m[11] = initialM34;
  1368. result.m[12] = initialM41;
  1369. result.m[13] = initialM42;
  1370. result.m[14] = initialM43;
  1371. result.m[15] = initialM44;
  1372. return result;
  1373. };
  1374. Matrix.Identity = function () {
  1375. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  1376. };
  1377. Matrix.IdentityToRef = function (result) {
  1378. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  1379. };
  1380. Matrix.Zero = function () {
  1381. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  1382. };
  1383. Matrix.RotationX = function (angle) {
  1384. var result = new Matrix();
  1385. Matrix.RotationXToRef(angle, result);
  1386. return result;
  1387. };
  1388. Matrix.Invert = function (source) {
  1389. var result = new Matrix();
  1390. source.invertToRef(result);
  1391. return result;
  1392. };
  1393. Matrix.RotationXToRef = function (angle, result) {
  1394. var s = Math.sin(angle);
  1395. var c = Math.cos(angle);
  1396. result.m[0] = 1.0;
  1397. result.m[15] = 1.0;
  1398. result.m[5] = c;
  1399. result.m[10] = c;
  1400. result.m[9] = -s;
  1401. result.m[6] = s;
  1402. result.m[1] = 0;
  1403. result.m[2] = 0;
  1404. result.m[3] = 0;
  1405. result.m[4] = 0;
  1406. result.m[7] = 0;
  1407. result.m[8] = 0;
  1408. result.m[11] = 0;
  1409. result.m[12] = 0;
  1410. result.m[13] = 0;
  1411. result.m[14] = 0;
  1412. };
  1413. Matrix.RotationY = function (angle) {
  1414. var result = new Matrix();
  1415. Matrix.RotationYToRef(angle, result);
  1416. return result;
  1417. };
  1418. Matrix.RotationYToRef = function (angle, result) {
  1419. var s = Math.sin(angle);
  1420. var c = Math.cos(angle);
  1421. result.m[5] = 1.0;
  1422. result.m[15] = 1.0;
  1423. result.m[0] = c;
  1424. result.m[2] = -s;
  1425. result.m[8] = s;
  1426. result.m[10] = c;
  1427. result.m[1] = 0;
  1428. result.m[3] = 0;
  1429. result.m[4] = 0;
  1430. result.m[6] = 0;
  1431. result.m[7] = 0;
  1432. result.m[9] = 0;
  1433. result.m[11] = 0;
  1434. result.m[12] = 0;
  1435. result.m[13] = 0;
  1436. result.m[14] = 0;
  1437. };
  1438. Matrix.RotationZ = function (angle) {
  1439. var result = new Matrix();
  1440. Matrix.RotationZToRef(angle, result);
  1441. return result;
  1442. };
  1443. Matrix.RotationZToRef = function (angle, result) {
  1444. var s = Math.sin(angle);
  1445. var c = Math.cos(angle);
  1446. result.m[10] = 1.0;
  1447. result.m[15] = 1.0;
  1448. result.m[0] = c;
  1449. result.m[1] = s;
  1450. result.m[4] = -s;
  1451. result.m[5] = c;
  1452. result.m[2] = 0;
  1453. result.m[3] = 0;
  1454. result.m[6] = 0;
  1455. result.m[7] = 0;
  1456. result.m[8] = 0;
  1457. result.m[9] = 0;
  1458. result.m[11] = 0;
  1459. result.m[12] = 0;
  1460. result.m[13] = 0;
  1461. result.m[14] = 0;
  1462. };
  1463. Matrix.RotationAxis = function (axis, angle) {
  1464. var s = Math.sin(-angle);
  1465. var c = Math.cos(-angle);
  1466. var c1 = 1 - c;
  1467. axis.normalize();
  1468. var result = Matrix.Zero();
  1469. result.m[0] = (axis.x * axis.x) * c1 + c;
  1470. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  1471. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  1472. result.m[3] = 0.0;
  1473. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  1474. result.m[5] = (axis.y * axis.y) * c1 + c;
  1475. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  1476. result.m[7] = 0.0;
  1477. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  1478. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  1479. result.m[10] = (axis.z * axis.z) * c1 + c;
  1480. result.m[11] = 0.0;
  1481. result.m[15] = 1.0;
  1482. return result;
  1483. };
  1484. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1485. var result = new Matrix();
  1486. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1487. return result;
  1488. };
  1489. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1490. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  1491. this._tempQuaternion.toRotationMatrix(result);
  1492. };
  1493. Matrix.Scaling = function (x, y, z) {
  1494. var result = Matrix.Zero();
  1495. Matrix.ScalingToRef(x, y, z, result);
  1496. return result;
  1497. };
  1498. Matrix.ScalingToRef = function (x, y, z, result) {
  1499. result.m[0] = x;
  1500. result.m[1] = 0;
  1501. result.m[2] = 0;
  1502. result.m[3] = 0;
  1503. result.m[4] = 0;
  1504. result.m[5] = y;
  1505. result.m[6] = 0;
  1506. result.m[7] = 0;
  1507. result.m[8] = 0;
  1508. result.m[9] = 0;
  1509. result.m[10] = z;
  1510. result.m[11] = 0;
  1511. result.m[12] = 0;
  1512. result.m[13] = 0;
  1513. result.m[14] = 0;
  1514. result.m[15] = 1.0;
  1515. };
  1516. Matrix.Translation = function (x, y, z) {
  1517. var result = Matrix.Identity();
  1518. Matrix.TranslationToRef(x, y, z, result);
  1519. return result;
  1520. };
  1521. Matrix.TranslationToRef = function (x, y, z, result) {
  1522. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  1523. };
  1524. Matrix.LookAtLH = function (eye, target, up) {
  1525. var result = Matrix.Zero();
  1526. Matrix.LookAtLHToRef(eye, target, up, result);
  1527. return result;
  1528. };
  1529. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  1530. target.subtractToRef(eye, this._zAxis);
  1531. this._zAxis.normalize();
  1532. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  1533. this._xAxis.normalize();
  1534. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  1535. this._yAxis.normalize();
  1536. var ex = -Vector3.Dot(this._xAxis, eye);
  1537. var ey = -Vector3.Dot(this._yAxis, eye);
  1538. var ez = -Vector3.Dot(this._zAxis, eye);
  1539. 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);
  1540. };
  1541. Matrix.OrthoLH = function (width, height, znear, zfar) {
  1542. var hw = 2.0 / width;
  1543. var hh = 2.0 / height;
  1544. var id = 1.0 / (zfar - znear);
  1545. var nid = znear / (znear - zfar);
  1546. return Matrix.FromValues(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1);
  1547. };
  1548. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  1549. var matrix = Matrix.Zero();
  1550. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  1551. return matrix;
  1552. };
  1553. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  1554. result.m[0] = 2.0 / (right - left);
  1555. result.m[1] = result.m[2] = result.m[3] = 0;
  1556. result.m[5] = 2.0 / (top - bottom);
  1557. result.m[4] = result.m[6] = result.m[7] = 0;
  1558. result.m[10] = -1.0 / (znear - zfar);
  1559. result.m[8] = result.m[9] = result.m[11] = 0;
  1560. result.m[12] = (left + right) / (left - right);
  1561. result.m[13] = (top + bottom) / (bottom - top);
  1562. result.m[14] = znear / (znear - zfar);
  1563. result.m[15] = 1.0;
  1564. };
  1565. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  1566. var matrix = Matrix.Zero();
  1567. matrix.m[0] = (2.0 * znear) / width;
  1568. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  1569. matrix.m[5] = (2.0 * znear) / height;
  1570. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  1571. matrix.m[10] = -zfar / (znear - zfar);
  1572. matrix.m[8] = matrix.m[9] = 0.0;
  1573. matrix.m[11] = 1.0;
  1574. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  1575. matrix.m[14] = (znear * zfar) / (znear - zfar);
  1576. return matrix;
  1577. };
  1578. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  1579. var matrix = Matrix.Zero();
  1580. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  1581. return matrix;
  1582. };
  1583. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result) {
  1584. var tan = 1.0 / (Math.tan(fov * 0.5));
  1585. result.m[0] = tan / aspect;
  1586. result.m[1] = result.m[2] = result.m[3] = 0.0;
  1587. result.m[5] = tan;
  1588. result.m[4] = result.m[6] = result.m[7] = 0.0;
  1589. result.m[8] = result.m[9] = 0.0;
  1590. result.m[10] = -zfar / (znear - zfar);
  1591. result.m[11] = 1.0;
  1592. result.m[12] = result.m[13] = result.m[15] = 0.0;
  1593. result.m[14] = (znear * zfar) / (znear - zfar);
  1594. };
  1595. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  1596. var cw = viewport.width;
  1597. var ch = viewport.height;
  1598. var cx = viewport.x;
  1599. var cy = viewport.y;
  1600. 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);
  1601. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  1602. };
  1603. Matrix.Transpose = function (matrix) {
  1604. var result = new Matrix();
  1605. result.m[0] = matrix.m[0];
  1606. result.m[1] = matrix.m[4];
  1607. result.m[2] = matrix.m[8];
  1608. result.m[3] = matrix.m[12];
  1609. result.m[4] = matrix.m[1];
  1610. result.m[5] = matrix.m[5];
  1611. result.m[6] = matrix.m[9];
  1612. result.m[7] = matrix.m[13];
  1613. result.m[8] = matrix.m[2];
  1614. result.m[9] = matrix.m[6];
  1615. result.m[10] = matrix.m[10];
  1616. result.m[11] = matrix.m[14];
  1617. result.m[12] = matrix.m[3];
  1618. result.m[13] = matrix.m[7];
  1619. result.m[14] = matrix.m[11];
  1620. result.m[15] = matrix.m[15];
  1621. return result;
  1622. };
  1623. Matrix.Reflection = function (plane) {
  1624. var matrix = new Matrix();
  1625. Matrix.ReflectionToRef(plane, matrix);
  1626. return matrix;
  1627. };
  1628. Matrix.ReflectionToRef = function (plane, result) {
  1629. plane.normalize();
  1630. var x = plane.normal.x;
  1631. var y = plane.normal.y;
  1632. var z = plane.normal.z;
  1633. var temp = -2 * x;
  1634. var temp2 = -2 * y;
  1635. var temp3 = -2 * z;
  1636. result.m[0] = (temp * x) + 1;
  1637. result.m[1] = temp2 * x;
  1638. result.m[2] = temp3 * x;
  1639. result.m[3] = 0.0;
  1640. result.m[4] = temp * y;
  1641. result.m[5] = (temp2 * y) + 1;
  1642. result.m[6] = temp3 * y;
  1643. result.m[7] = 0.0;
  1644. result.m[8] = temp * z;
  1645. result.m[9] = temp2 * z;
  1646. result.m[10] = (temp3 * z) + 1;
  1647. result.m[11] = 0.0;
  1648. result.m[12] = temp * plane.d;
  1649. result.m[13] = temp2 * plane.d;
  1650. result.m[14] = temp3 * plane.d;
  1651. result.m[15] = 1.0;
  1652. };
  1653. Matrix._tempQuaternion = new Quaternion();
  1654. Matrix._xAxis = Vector3.Zero();
  1655. Matrix._yAxis = Vector3.Zero();
  1656. Matrix._zAxis = Vector3.Zero();
  1657. return Matrix;
  1658. })();
  1659. BABYLON.Matrix = Matrix;
  1660. var Plane = (function () {
  1661. function Plane(a, b, c, d) {
  1662. this.normal = new Vector3(a, b, c);
  1663. this.d = d;
  1664. }
  1665. Plane.prototype.asArray = function () {
  1666. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  1667. };
  1668. Plane.prototype.clone = function () {
  1669. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  1670. };
  1671. Plane.prototype.normalize = function () {
  1672. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  1673. var magnitude = 0;
  1674. if (norm != 0) {
  1675. magnitude = 1.0 / norm;
  1676. }
  1677. this.normal.x *= magnitude;
  1678. this.normal.y *= magnitude;
  1679. this.normal.z *= magnitude;
  1680. this.d *= magnitude;
  1681. };
  1682. Plane.prototype.transform = function (transformation) {
  1683. var transposedMatrix = BABYLON.Matrix.Transpose(transformation);
  1684. var x = this.normal.x;
  1685. var y = this.normal.y;
  1686. var z = this.normal.z;
  1687. var d = this.d;
  1688. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  1689. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  1690. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  1691. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  1692. return new BABYLON.Plane(normalX, normalY, normalZ, finalD);
  1693. };
  1694. Plane.prototype.dotCoordinate = function (point) {
  1695. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  1696. };
  1697. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  1698. var x1 = point2.x - point1.x;
  1699. var y1 = point2.y - point1.y;
  1700. var z1 = point2.z - point1.z;
  1701. var x2 = point3.x - point1.x;
  1702. var y2 = point3.y - point1.y;
  1703. var z2 = point3.z - point1.z;
  1704. var yz = (y1 * z2) - (z1 * y2);
  1705. var xz = (z1 * x2) - (x1 * z2);
  1706. var xy = (x1 * y2) - (y1 * x2);
  1707. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  1708. var invPyth;
  1709. if (pyth != 0) {
  1710. invPyth = 1.0 / pyth;
  1711. } else {
  1712. invPyth = 0;
  1713. }
  1714. this.normal.x = yz * invPyth;
  1715. this.normal.y = xz * invPyth;
  1716. this.normal.z = xy * invPyth;
  1717. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  1718. };
  1719. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  1720. var dot = Vector3.Dot(this.normal, direction);
  1721. return (dot <= epsilon);
  1722. };
  1723. Plane.prototype.signedDistanceTo = function (point) {
  1724. return Vector3.Dot(point, this.normal) + this.d;
  1725. };
  1726. Plane.FromArray = function (array) {
  1727. return new BABYLON.Plane(array[0], array[1], array[2], array[3]);
  1728. };
  1729. Plane.FromPoints = function (point1, point2, point3) {
  1730. var result = new BABYLON.Plane(0, 0, 0, 0);
  1731. result.copyFromPoints(point1, point2, point3);
  1732. return result;
  1733. };
  1734. Plane.FromPositionAndNormal = function (origin, normal) {
  1735. var result = new BABYLON.Plane(0, 0, 0, 0);
  1736. normal.normalize();
  1737. result.normal = normal;
  1738. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  1739. return result;
  1740. };
  1741. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  1742. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  1743. return Vector3.Dot(point, normal) + d;
  1744. };
  1745. return Plane;
  1746. })();
  1747. BABYLON.Plane = Plane;
  1748. var Viewport = (function () {
  1749. function Viewport(x, y, width, height) {
  1750. this.x = x;
  1751. this.y = y;
  1752. this.width = width;
  1753. this.height = height;
  1754. }
  1755. Viewport.prototype.toGlobal = function (engine) {
  1756. var width = engine.getRenderWidth();
  1757. var height = engine.getRenderHeight();
  1758. return new Viewport(this.x * width, this.y * height, this.width * width, this.height * height);
  1759. };
  1760. return Viewport;
  1761. })();
  1762. BABYLON.Viewport = Viewport;
  1763. var Frustum = (function () {
  1764. function Frustum() {
  1765. }
  1766. Frustum.GetPlanes = function (transform) {
  1767. var frustumPlanes = [];
  1768. for (var index = 0; index < 6; index++) {
  1769. frustumPlanes.push(new Plane(0, 0, 0, 0));
  1770. }
  1771. Frustum.GetPlanesToRef(transform, frustumPlanes);
  1772. return frustumPlanes;
  1773. };
  1774. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  1775. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  1776. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  1777. frustumPlanes[0].normal.z = transform.m[10] + transform.m[10];
  1778. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  1779. frustumPlanes[0].normalize();
  1780. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  1781. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  1782. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  1783. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  1784. frustumPlanes[1].normalize();
  1785. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  1786. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  1787. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  1788. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  1789. frustumPlanes[2].normalize();
  1790. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  1791. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  1792. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  1793. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  1794. frustumPlanes[3].normalize();
  1795. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  1796. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  1797. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  1798. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  1799. frustumPlanes[4].normalize();
  1800. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  1801. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  1802. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  1803. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  1804. frustumPlanes[5].normalize();
  1805. };
  1806. return Frustum;
  1807. })();
  1808. BABYLON.Frustum = Frustum;
  1809. var Ray = (function () {
  1810. function Ray(origin, direction, length) {
  1811. if (typeof length === "undefined") { length = Number.MAX_VALUE; }
  1812. this.origin = origin;
  1813. this.direction = direction;
  1814. this.length = length;
  1815. }
  1816. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  1817. var d = 0.0;
  1818. var maxValue = Number.MAX_VALUE;
  1819. if (Math.abs(this.direction.x) < 0.0000001) {
  1820. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  1821. return false;
  1822. }
  1823. } else {
  1824. var inv = 1.0 / this.direction.x;
  1825. var min = (minimum.x - this.origin.x) * inv;
  1826. var max = (maximum.x - this.origin.x) * inv;
  1827. if (min > max) {
  1828. var temp = min;
  1829. min = max;
  1830. max = temp;
  1831. }
  1832. d = Math.max(min, d);
  1833. maxValue = Math.min(max, maxValue);
  1834. if (d > maxValue) {
  1835. return false;
  1836. }
  1837. }
  1838. if (Math.abs(this.direction.y) < 0.0000001) {
  1839. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  1840. return false;
  1841. }
  1842. } else {
  1843. inv = 1.0 / this.direction.y;
  1844. min = (minimum.y - this.origin.y) * inv;
  1845. max = (maximum.y - this.origin.y) * inv;
  1846. if (min > max) {
  1847. temp = min;
  1848. min = max;
  1849. max = temp;
  1850. }
  1851. d = Math.max(min, d);
  1852. maxValue = Math.min(max, maxValue);
  1853. if (d > maxValue) {
  1854. return false;
  1855. }
  1856. }
  1857. if (Math.abs(this.direction.z) < 0.0000001) {
  1858. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  1859. return false;
  1860. }
  1861. } else {
  1862. inv = 1.0 / this.direction.z;
  1863. min = (minimum.z - this.origin.z) * inv;
  1864. max = (maximum.z - this.origin.z) * inv;
  1865. if (min > max) {
  1866. temp = min;
  1867. min = max;
  1868. max = temp;
  1869. }
  1870. d = Math.max(min, d);
  1871. maxValue = Math.min(max, maxValue);
  1872. if (d > maxValue) {
  1873. return false;
  1874. }
  1875. }
  1876. return true;
  1877. };
  1878. Ray.prototype.intersectsBox = function (box) {
  1879. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  1880. };
  1881. Ray.prototype.intersectsSphere = function (sphere) {
  1882. var x = sphere.center.x - this.origin.x;
  1883. var y = sphere.center.y - this.origin.y;
  1884. var z = sphere.center.z - this.origin.z;
  1885. var pyth = (x * x) + (y * y) + (z * z);
  1886. var rr = sphere.radius * sphere.radius;
  1887. if (pyth <= rr) {
  1888. return true;
  1889. }
  1890. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  1891. if (dot < 0.0) {
  1892. return false;
  1893. }
  1894. var temp = pyth - (dot * dot);
  1895. return temp <= rr;
  1896. };
  1897. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  1898. if (!this._edge1) {
  1899. this._edge1 = BABYLON.Vector3.Zero();
  1900. this._edge2 = BABYLON.Vector3.Zero();
  1901. this._pvec = BABYLON.Vector3.Zero();
  1902. this._tvec = BABYLON.Vector3.Zero();
  1903. this._qvec = BABYLON.Vector3.Zero();
  1904. }
  1905. vertex1.subtractToRef(vertex0, this._edge1);
  1906. vertex2.subtractToRef(vertex0, this._edge2);
  1907. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  1908. var det = Vector3.Dot(this._edge1, this._pvec);
  1909. if (det === 0) {
  1910. return null;
  1911. }
  1912. var invdet = 1 / det;
  1913. this.origin.subtractToRef(vertex0, this._tvec);
  1914. var bu = Vector3.Dot(this._tvec, this._pvec) * invdet;
  1915. if (bu < 0 || bu > 1.0) {
  1916. return null;
  1917. }
  1918. Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  1919. var bv = Vector3.Dot(this.direction, this._qvec) * invdet;
  1920. if (bv < 0 || bu + bv > 1.0) {
  1921. return null;
  1922. }
  1923. var distance = Vector3.Dot(this._edge2, this._qvec) * invdet;
  1924. if (distance > this.length) {
  1925. return null;
  1926. }
  1927. return new BABYLON.IntersectionInfo(bu, bv, distance);
  1928. };
  1929. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  1930. var start = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  1931. var end = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  1932. var direction = end.subtract(start);
  1933. direction.normalize();
  1934. return new Ray(start, direction);
  1935. };
  1936. /**
  1937. * Function will create a new transformed ray starting from origin and ending at the end point. Ray's length will be set, and ray will be
  1938. * transformed to the given world matrix.
  1939. * @param origin The origin point
  1940. * @param end The end point
  1941. * @param world a matrix to transform the ray to. Default is the identity matrix.
  1942. */
  1943. Ray.CreateNewFromTo = function (origin, end, world) {
  1944. if (typeof world === "undefined") { world = BABYLON.Matrix.Identity(); }
  1945. var direction = end.subtract(origin);
  1946. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  1947. direction.normalize();
  1948. return Ray.Transform(new Ray(origin, direction, length), world);
  1949. };
  1950. Ray.Transform = function (ray, matrix) {
  1951. var newOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, matrix);
  1952. var newDirection = BABYLON.Vector3.TransformNormal(ray.direction, matrix);
  1953. return new Ray(newOrigin, newDirection, ray.length);
  1954. };
  1955. return Ray;
  1956. })();
  1957. BABYLON.Ray = Ray;
  1958. (function (Space) {
  1959. Space[Space["LOCAL"] = 0] = "LOCAL";
  1960. Space[Space["WORLD"] = 1] = "WORLD";
  1961. })(BABYLON.Space || (BABYLON.Space = {}));
  1962. var Space = BABYLON.Space;
  1963. var Axis = (function () {
  1964. function Axis() {
  1965. }
  1966. Axis.X = new BABYLON.Vector3(1, 0, 0);
  1967. Axis.Y = new BABYLON.Vector3(0, 1, 0);
  1968. Axis.Z = new BABYLON.Vector3(0, 0, 1);
  1969. return Axis;
  1970. })();
  1971. BABYLON.Axis = Axis;
  1972. ;
  1973. var BezierCurve = (function () {
  1974. function BezierCurve() {
  1975. }
  1976. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  1977. var f0 = 1 - 3 * x2 + 3 * x1;
  1978. var f1 = 3 * x2 - 6 * x1;
  1979. var f2 = 3 * x1;
  1980. var refinedT = t;
  1981. for (var i = 0; i < 5; i++) {
  1982. var refinedT2 = refinedT * refinedT;
  1983. var refinedT3 = refinedT2 * refinedT;
  1984. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  1985. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  1986. refinedT -= (x - t) * slope;
  1987. refinedT = Math.min(1, Math.max(0, refinedT));
  1988. }
  1989. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 + 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 + Math.pow(refinedT, 3);
  1990. };
  1991. return BezierCurve;
  1992. })();
  1993. BABYLON.BezierCurve = BezierCurve;
  1994. })(BABYLON || (BABYLON = {}));
  1995. var BABYLON;
  1996. (function (BABYLON) {
  1997. var screenshotCanvas;
  1998. var fpsRange = 60;
  1999. var previousFramesDuration = [];
  2000. var fps = 60;
  2001. var deltaTime = 0;
  2002. var cloneValue = function (source, destinationObject) {
  2003. if (!source)
  2004. return null;
  2005. if (source instanceof BABYLON.Mesh) {
  2006. return null;
  2007. }
  2008. if (source instanceof BABYLON.SubMesh) {
  2009. return source.clone(destinationObject);
  2010. } else if (source.clone) {
  2011. return source.clone();
  2012. }
  2013. return null;
  2014. };
  2015. var Tools = (function () {
  2016. function Tools() {
  2017. }
  2018. Tools.GetFilename = function (path) {
  2019. var index = path.lastIndexOf("/");
  2020. if (index < 0)
  2021. return path;
  2022. return path.substring(index + 1);
  2023. };
  2024. Tools.GetDOMTextContent = function (element) {
  2025. var result = "";
  2026. var child = element.firstChild;
  2027. while (child) {
  2028. if (child.nodeType == 3) {
  2029. result += child.textContent;
  2030. }
  2031. child = child.nextSibling;
  2032. }
  2033. return result;
  2034. };
  2035. Tools.ToDegrees = function (angle) {
  2036. return angle * 180 / Math.PI;
  2037. };
  2038. Tools.ToRadians = function (angle) {
  2039. return angle * Math.PI / 180;
  2040. };
  2041. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount) {
  2042. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  2043. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  2044. for (var index = indexStart; index < indexStart + indexCount; index++) {
  2045. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  2046. minimum = BABYLON.Vector3.Minimize(current, minimum);
  2047. maximum = BABYLON.Vector3.Maximize(current, maximum);
  2048. }
  2049. return {
  2050. minimum: minimum,
  2051. maximum: maximum
  2052. };
  2053. };
  2054. Tools.ExtractMinAndMax = function (positions, start, count) {
  2055. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  2056. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  2057. for (var index = start; index < start + count; index++) {
  2058. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  2059. minimum = BABYLON.Vector3.Minimize(current, minimum);
  2060. maximum = BABYLON.Vector3.Maximize(current, maximum);
  2061. }
  2062. return {
  2063. minimum: minimum,
  2064. maximum: maximum
  2065. };
  2066. };
  2067. Tools.MakeArray = function (obj, allowsNullUndefined) {
  2068. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  2069. return undefined;
  2070. return Array.isArray(obj) ? obj : [obj];
  2071. };
  2072. Tools.GetPointerPrefix = function () {
  2073. var eventPrefix = "pointer";
  2074. if (!navigator.pointerEnabled) {
  2075. eventPrefix = "mouse";
  2076. }
  2077. return eventPrefix;
  2078. };
  2079. Tools.QueueNewFrame = function (func) {
  2080. if (window.requestAnimationFrame)
  2081. window.requestAnimationFrame(func);
  2082. else if (window.msRequestAnimationFrame)
  2083. window.msRequestAnimationFrame(func);
  2084. else if (window.webkitRequestAnimationFrame)
  2085. window.webkitRequestAnimationFrame(func);
  2086. else if (window.mozRequestAnimationFrame)
  2087. window.mozRequestAnimationFrame(func);
  2088. else if (window.oRequestAnimationFrame)
  2089. window.oRequestAnimationFrame(func);
  2090. else {
  2091. window.setTimeout(func, 16);
  2092. }
  2093. };
  2094. Tools.RequestFullscreen = function (element) {
  2095. if (element.requestFullscreen)
  2096. element.requestFullscreen();
  2097. else if (element.msRequestFullscreen)
  2098. element.msRequestFullscreen();
  2099. else if (element.webkitRequestFullscreen)
  2100. element.webkitRequestFullscreen();
  2101. else if (element.mozRequestFullScreen)
  2102. element.mozRequestFullScreen();
  2103. };
  2104. Tools.ExitFullscreen = function () {
  2105. if (document.exitFullscreen) {
  2106. document.exitFullscreen();
  2107. } else if (document.mozCancelFullScreen) {
  2108. document.mozCancelFullScreen();
  2109. } else if (document.webkitCancelFullScreen) {
  2110. document.webkitCancelFullScreen();
  2111. } else if (document.msCancelFullScreen) {
  2112. document.msCancelFullScreen();
  2113. }
  2114. };
  2115. Tools.CleanUrl = function (url) {
  2116. url = url.replace(/#/mg, "%23");
  2117. return url;
  2118. };
  2119. Tools.LoadImage = function (url, onload, onerror, database) {
  2120. url = Tools.CleanUrl(url);
  2121. var img = new Image();
  2122. if (url.substr(0, 5) != "data:")
  2123. img.crossOrigin = 'anonymous';
  2124. img.onload = function () {
  2125. onload(img);
  2126. };
  2127. img.onerror = function (err) {
  2128. onerror(img, err);
  2129. };
  2130. var noIndexedDB = function () {
  2131. img.src = url;
  2132. };
  2133. var loadFromIndexedDB = function () {
  2134. database.loadImageFromDB(url, img);
  2135. };
  2136. if (database && database.enableTexturesOffline && BABYLON.Database.isUASupportingBlobStorage) {
  2137. database.openAsync(loadFromIndexedDB, noIndexedDB);
  2138. } else {
  2139. if (url.indexOf("file:") === -1) {
  2140. noIndexedDB();
  2141. } else {
  2142. try {
  2143. var textureName = url.substring(5);
  2144. var blobURL;
  2145. try {
  2146. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  2147. } catch (ex) {
  2148. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  2149. }
  2150. img.src = blobURL;
  2151. } catch (e) {
  2152. Tools.Log("Error while trying to load texture: " + textureName);
  2153. img.src = null;
  2154. }
  2155. }
  2156. }
  2157. return img;
  2158. };
  2159. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  2160. url = Tools.CleanUrl(url);
  2161. var noIndexedDB = function () {
  2162. var request = new XMLHttpRequest();
  2163. var loadUrl = Tools.BaseUrl + url;
  2164. request.open('GET', loadUrl, true);
  2165. if (useArrayBuffer) {
  2166. request.responseType = "arraybuffer";
  2167. }
  2168. request.onprogress = progressCallBack;
  2169. request.onreadystatechange = function () {
  2170. if (request.readyState == 4) {
  2171. if (request.status == 200 || BABYLON.Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  2172. callback(!useArrayBuffer ? request.responseText : request.response);
  2173. } else {
  2174. if (onError) {
  2175. onError();
  2176. } else {
  2177. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  2178. }
  2179. }
  2180. }
  2181. };
  2182. request.send(null);
  2183. };
  2184. var loadFromIndexedDB = function () {
  2185. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  2186. };
  2187. if (url.indexOf("file:") !== -1) {
  2188. var fileName = url.substring(5);
  2189. BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, true);
  2190. } else {
  2191. if (database && database.enableSceneOffline) {
  2192. database.openAsync(loadFromIndexedDB, noIndexedDB);
  2193. } else {
  2194. noIndexedDB();
  2195. }
  2196. }
  2197. };
  2198. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  2199. var reader = new FileReader();
  2200. reader.onload = function (e) {
  2201. callback(e.target.result);
  2202. };
  2203. reader.onprogress = progressCallback;
  2204. reader.readAsDataURL(fileToLoad);
  2205. };
  2206. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  2207. var reader = new FileReader();
  2208. reader.onload = function (e) {
  2209. callback(e.target.result);
  2210. };
  2211. reader.onprogress = progressCallBack;
  2212. if (!useArrayBuffer) {
  2213. reader.readAsText(fileToLoad);
  2214. } else {
  2215. reader.readAsArrayBuffer(fileToLoad);
  2216. }
  2217. };
  2218. Tools.CheckExtends = function (v, min, max) {
  2219. if (v.x < min.x)
  2220. min.x = v.x;
  2221. if (v.y < min.y)
  2222. min.y = v.y;
  2223. if (v.z < min.z)
  2224. min.z = v.z;
  2225. if (v.x > max.x)
  2226. max.x = v.x;
  2227. if (v.y > max.y)
  2228. max.y = v.y;
  2229. if (v.z > max.z)
  2230. max.z = v.z;
  2231. };
  2232. Tools.WithinEpsilon = function (a, b) {
  2233. var num = a - b;
  2234. return -1.401298E-45 <= num && num <= 1.401298E-45;
  2235. };
  2236. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  2237. for (var prop in source) {
  2238. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  2239. continue;
  2240. }
  2241. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  2242. continue;
  2243. }
  2244. var sourceValue = source[prop];
  2245. var typeOfSourceValue = typeof sourceValue;
  2246. if (typeOfSourceValue == "function") {
  2247. continue;
  2248. }
  2249. if (typeOfSourceValue == "object") {
  2250. if (sourceValue instanceof Array) {
  2251. destination[prop] = [];
  2252. if (sourceValue.length > 0) {
  2253. if (typeof sourceValue[0] == "object") {
  2254. for (var index = 0; index < sourceValue.length; index++) {
  2255. var clonedValue = cloneValue(sourceValue[index], destination);
  2256. if (destination[prop].indexOf(clonedValue) === -1) {
  2257. destination[prop].push(clonedValue);
  2258. }
  2259. }
  2260. } else {
  2261. destination[prop] = sourceValue.slice(0);
  2262. }
  2263. }
  2264. } else {
  2265. destination[prop] = cloneValue(sourceValue, destination);
  2266. }
  2267. } else {
  2268. destination[prop] = sourceValue;
  2269. }
  2270. }
  2271. };
  2272. Tools.IsEmpty = function (obj) {
  2273. for (var i in obj) {
  2274. return false;
  2275. }
  2276. return true;
  2277. };
  2278. Tools.RegisterTopRootEvents = function (events) {
  2279. for (var index = 0; index < events.length; index++) {
  2280. var event = events[index];
  2281. window.addEventListener(event.name, event.handler, false);
  2282. try {
  2283. if (window.parent) {
  2284. window.parent.addEventListener(event.name, event.handler, false);
  2285. }
  2286. } catch (e) {
  2287. }
  2288. }
  2289. };
  2290. Tools.UnregisterTopRootEvents = function (events) {
  2291. for (var index = 0; index < events.length; index++) {
  2292. var event = events[index];
  2293. window.removeEventListener(event.name, event.handler);
  2294. try {
  2295. if (window.parent) {
  2296. window.parent.removeEventListener(event.name, event.handler);
  2297. }
  2298. } catch (e) {
  2299. }
  2300. }
  2301. };
  2302. Tools.GetFps = function () {
  2303. return fps;
  2304. };
  2305. Tools.GetDeltaTime = function () {
  2306. return deltaTime;
  2307. };
  2308. Tools._MeasureFps = function () {
  2309. previousFramesDuration.push(Tools.Now);
  2310. var length = previousFramesDuration.length;
  2311. if (length >= 2) {
  2312. deltaTime = previousFramesDuration[length - 1] - previousFramesDuration[length - 2];
  2313. }
  2314. if (length >= fpsRange) {
  2315. if (length > fpsRange) {
  2316. previousFramesDuration.splice(0, 1);
  2317. length = previousFramesDuration.length;
  2318. }
  2319. var sum = 0;
  2320. for (var id = 0; id < length - 1; id++) {
  2321. sum += previousFramesDuration[id + 1] - previousFramesDuration[id];
  2322. }
  2323. fps = 1000.0 / (sum / (length - 1));
  2324. }
  2325. };
  2326. Tools.CreateScreenshot = function (engine, camera, size) {
  2327. var width;
  2328. var height;
  2329. var scene = camera.getScene();
  2330. var previousCamera = null;
  2331. if (scene.activeCamera !== camera) {
  2332. previousCamera = scene.activeCamera;
  2333. scene.activeCamera = camera;
  2334. }
  2335. if (size.precision) {
  2336. width = Math.round(engine.getRenderWidth() * size.precision);
  2337. height = Math.round(width / engine.getAspectRatio(camera));
  2338. size = { width: width, height: height };
  2339. } else if (size.width && size.height) {
  2340. width = size.width;
  2341. height = size.height;
  2342. } else if (size.width && !size.height) {
  2343. width = size.width;
  2344. height = Math.round(width / engine.getAspectRatio(camera));
  2345. size = { width: width, height: height };
  2346. } else if (size.height && !size.width) {
  2347. height = size.height;
  2348. width = Math.round(height * engine.getAspectRatio(camera));
  2349. size = { width: width, height: height };
  2350. } else if (!isNaN(size)) {
  2351. height = size;
  2352. width = size;
  2353. } else {
  2354. Tools.Error("Invalid 'size' parameter !");
  2355. return;
  2356. }
  2357. var texture = new BABYLON.RenderTargetTexture("screenShot", size, engine.scenes[0], false, false);
  2358. texture.renderList = engine.scenes[0].meshes;
  2359. texture.onAfterRender = function () {
  2360. var numberOfChannelsByLine = width * 4;
  2361. var halfHeight = height / 2;
  2362. var data = engine.readPixels(0, 0, width, height);
  2363. for (var i = 0; i < halfHeight; i++) {
  2364. for (var j = 0; j < numberOfChannelsByLine; j++) {
  2365. var currentCell = j + i * numberOfChannelsByLine;
  2366. var targetLine = height - i - 1;
  2367. var targetCell = j + targetLine * numberOfChannelsByLine;
  2368. var temp = data[currentCell];
  2369. data[currentCell] = data[targetCell];
  2370. data[targetCell] = temp;
  2371. }
  2372. }
  2373. if (!screenshotCanvas) {
  2374. screenshotCanvas = document.createElement('canvas');
  2375. }
  2376. screenshotCanvas.width = width;
  2377. screenshotCanvas.height = height;
  2378. var context = screenshotCanvas.getContext('2d');
  2379. var imageData = context.createImageData(width, height);
  2380. imageData.data.set(data);
  2381. context.putImageData(imageData, 0, 0);
  2382. var base64Image = screenshotCanvas.toDataURL();
  2383. if (("download" in document.createElement("a"))) {
  2384. var a = window.document.createElement("a");
  2385. a.href = base64Image;
  2386. var date = new Date();
  2387. var stringDate = date.getFullYear() + "/" + date.getMonth() + "/" + date.getDate() + "-" + date.getHours() + ":" + date.getMinutes();
  2388. a.setAttribute("download", "screenshot-" + stringDate + ".png");
  2389. window.document.body.appendChild(a);
  2390. a.addEventListener("click", function () {
  2391. a.parentElement.removeChild(a);
  2392. });
  2393. a.click();
  2394. } else {
  2395. var newWindow = window.open("");
  2396. var img = newWindow.document.createElement("img");
  2397. img.src = base64Image;
  2398. newWindow.document.body.appendChild(img);
  2399. }
  2400. };
  2401. texture.render(true);
  2402. texture.dispose();
  2403. if (previousCamera) {
  2404. scene.activeCamera = previousCamera;
  2405. }
  2406. };
  2407. Tools.ValidateXHRData = function (xhr, dataType) {
  2408. if (typeof dataType === "undefined") { dataType = 7; }
  2409. try {
  2410. if (dataType & 1) {
  2411. if (xhr.responseText && xhr.responseText.length > 0) {
  2412. return true;
  2413. } else if (dataType === 1) {
  2414. return false;
  2415. }
  2416. }
  2417. if (dataType & 2) {
  2418. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  2419. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  2420. return true;
  2421. } else if (dataType === 2) {
  2422. return false;
  2423. }
  2424. }
  2425. if (dataType & 4) {
  2426. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  2427. if (ddsHeader[0] == 68 && ddsHeader[1] == 68 && ddsHeader[2] == 83) {
  2428. return true;
  2429. } else {
  2430. return false;
  2431. }
  2432. }
  2433. } catch (e) {
  2434. }
  2435. return false;
  2436. };
  2437. Object.defineProperty(Tools, "NoneLogLevel", {
  2438. get: function () {
  2439. return Tools._NoneLogLevel;
  2440. },
  2441. enumerable: true,
  2442. configurable: true
  2443. });
  2444. Object.defineProperty(Tools, "MessageLogLevel", {
  2445. get: function () {
  2446. return Tools._MessageLogLevel;
  2447. },
  2448. enumerable: true,
  2449. configurable: true
  2450. });
  2451. Object.defineProperty(Tools, "WarningLogLevel", {
  2452. get: function () {
  2453. return Tools._WarningLogLevel;
  2454. },
  2455. enumerable: true,
  2456. configurable: true
  2457. });
  2458. Object.defineProperty(Tools, "ErrorLogLevel", {
  2459. get: function () {
  2460. return Tools._ErrorLogLevel;
  2461. },
  2462. enumerable: true,
  2463. configurable: true
  2464. });
  2465. Object.defineProperty(Tools, "AllLogLevel", {
  2466. get: function () {
  2467. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  2468. },
  2469. enumerable: true,
  2470. configurable: true
  2471. });
  2472. Tools._FormatMessage = function (message) {
  2473. var padStr = function (i) {
  2474. return (i < 10) ? "0" + i : "" + i;
  2475. };
  2476. var date = new Date();
  2477. return "BJS - [" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  2478. };
  2479. Tools._LogDisabled = function (message) {
  2480. };
  2481. Tools._LogEnabled = function (message) {
  2482. console.log(Tools._FormatMessage(message));
  2483. };
  2484. Tools._WarnDisabled = function (message) {
  2485. };
  2486. Tools._WarnEnabled = function (message) {
  2487. console.warn(Tools._FormatMessage(message));
  2488. };
  2489. Tools._ErrorDisabled = function (message) {
  2490. };
  2491. Tools._ErrorEnabled = function (message) {
  2492. console.error(Tools._FormatMessage(message));
  2493. };
  2494. Object.defineProperty(Tools, "LogLevels", {
  2495. set: function (level) {
  2496. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  2497. Tools.Log = Tools._LogEnabled;
  2498. } else {
  2499. Tools.Log = Tools._LogDisabled;
  2500. }
  2501. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  2502. Tools.Warn = Tools._WarnEnabled;
  2503. } else {
  2504. Tools.Warn = Tools._WarnDisabled;
  2505. }
  2506. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  2507. Tools.Error = Tools._ErrorEnabled;
  2508. } else {
  2509. Tools.Error = Tools._ErrorDisabled;
  2510. }
  2511. },
  2512. enumerable: true,
  2513. configurable: true
  2514. });
  2515. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  2516. get: function () {
  2517. return Tools._PerformanceNoneLogLevel;
  2518. },
  2519. enumerable: true,
  2520. configurable: true
  2521. });
  2522. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  2523. get: function () {
  2524. return Tools._PerformanceUserMarkLogLevel;
  2525. },
  2526. enumerable: true,
  2527. configurable: true
  2528. });
  2529. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  2530. get: function () {
  2531. return Tools._PerformanceConsoleLogLevel;
  2532. },
  2533. enumerable: true,
  2534. configurable: true
  2535. });
  2536. Object.defineProperty(Tools, "PerformanceLogLevel", {
  2537. set: function (level) {
  2538. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  2539. Tools.StartPerformanceCounter = Tools._StartUserMark;
  2540. Tools.EndPerformanceCounter = Tools._EndUserMark;
  2541. return;
  2542. }
  2543. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  2544. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  2545. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  2546. return;
  2547. }
  2548. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  2549. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  2550. },
  2551. enumerable: true,
  2552. configurable: true
  2553. });
  2554. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  2555. };
  2556. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  2557. };
  2558. Tools._StartUserMark = function (counterName, condition) {
  2559. if (typeof condition === "undefined") { condition = true; }
  2560. if (!condition || !Tools._performance.mark) {
  2561. return;
  2562. }
  2563. Tools._performance.mark(counterName + "-Begin");
  2564. };
  2565. Tools._EndUserMark = function (counterName, condition) {
  2566. if (typeof condition === "undefined") { condition = true; }
  2567. if (!condition || !Tools._performance.mark) {
  2568. return;
  2569. }
  2570. Tools._performance.mark(counterName + "-End");
  2571. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  2572. };
  2573. Tools._StartPerformanceConsole = function (counterName, condition) {
  2574. if (typeof condition === "undefined") { condition = true; }
  2575. if (!condition) {
  2576. return;
  2577. }
  2578. Tools._StartUserMark(counterName, condition);
  2579. if (console.time) {
  2580. console.time(counterName);
  2581. }
  2582. };
  2583. Tools._EndPerformanceConsole = function (counterName, condition) {
  2584. if (typeof condition === "undefined") { condition = true; }
  2585. if (!condition) {
  2586. return;
  2587. }
  2588. Tools._EndUserMark(counterName, condition);
  2589. if (console.time) {
  2590. console.timeEnd(counterName);
  2591. }
  2592. };
  2593. Object.defineProperty(Tools, "Now", {
  2594. get: function () {
  2595. if (window.performance && window.performance.now) {
  2596. return window.performance.now();
  2597. }
  2598. return new Date().getTime();
  2599. },
  2600. enumerable: true,
  2601. configurable: true
  2602. });
  2603. Tools.BaseUrl = "";
  2604. Tools.GetExponantOfTwo = function (value, max) {
  2605. var count = 1;
  2606. do {
  2607. count *= 2;
  2608. } while(count < value);
  2609. if (count > max)
  2610. count = max;
  2611. return count;
  2612. };
  2613. Tools._NoneLogLevel = 0;
  2614. Tools._MessageLogLevel = 1;
  2615. Tools._WarningLogLevel = 2;
  2616. Tools._ErrorLogLevel = 4;
  2617. Tools.Log = Tools._LogEnabled;
  2618. Tools.Warn = Tools._WarnEnabled;
  2619. Tools.Error = Tools._ErrorEnabled;
  2620. Tools._PerformanceNoneLogLevel = 0;
  2621. Tools._PerformanceUserMarkLogLevel = 1;
  2622. Tools._PerformanceConsoleLogLevel = 2;
  2623. Tools._performance = window.performance;
  2624. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  2625. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  2626. return Tools;
  2627. })();
  2628. BABYLON.Tools = Tools;
  2629. })(BABYLON || (BABYLON = {}));
  2630. var BABYLON;
  2631. (function (BABYLON) {
  2632. var _DepthCullingState = (function () {
  2633. function _DepthCullingState() {
  2634. this._isDepthTestDirty = false;
  2635. this._isDepthMaskDirty = false;
  2636. this._isDepthFuncDirty = false;
  2637. this._isCullFaceDirty = false;
  2638. this._isCullDirty = false;
  2639. }
  2640. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  2641. get: function () {
  2642. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty;
  2643. },
  2644. enumerable: true,
  2645. configurable: true
  2646. });
  2647. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  2648. get: function () {
  2649. return this._cullFace;
  2650. },
  2651. set: function (value) {
  2652. if (this._cullFace === value) {
  2653. return;
  2654. }
  2655. this._cullFace = value;
  2656. this._isCullFaceDirty = true;
  2657. },
  2658. enumerable: true,
  2659. configurable: true
  2660. });
  2661. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  2662. get: function () {
  2663. return this._cull;
  2664. },
  2665. set: function (value) {
  2666. if (this._cull === value) {
  2667. return;
  2668. }
  2669. this._cull = value;
  2670. this._isCullDirty = true;
  2671. },
  2672. enumerable: true,
  2673. configurable: true
  2674. });
  2675. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  2676. get: function () {
  2677. return this._depthFunc;
  2678. },
  2679. set: function (value) {
  2680. if (this._depthFunc === value) {
  2681. return;
  2682. }
  2683. this._depthFunc = value;
  2684. this._isDepthFuncDirty = true;
  2685. },
  2686. enumerable: true,
  2687. configurable: true
  2688. });
  2689. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  2690. get: function () {
  2691. return this._depthMask;
  2692. },
  2693. set: function (value) {
  2694. if (this._depthMask === value) {
  2695. return;
  2696. }
  2697. this._depthMask = value;
  2698. this._isDepthMaskDirty = true;
  2699. },
  2700. enumerable: true,
  2701. configurable: true
  2702. });
  2703. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  2704. get: function () {
  2705. return this._depthTest;
  2706. },
  2707. set: function (value) {
  2708. if (this._depthTest === value) {
  2709. return;
  2710. }
  2711. this._depthTest = value;
  2712. this._isDepthTestDirty = true;
  2713. },
  2714. enumerable: true,
  2715. configurable: true
  2716. });
  2717. _DepthCullingState.prototype.reset = function () {
  2718. this._depthMask = true;
  2719. this._depthTest = true;
  2720. this._depthFunc = null;
  2721. this._cull = null;
  2722. this._cullFace = null;
  2723. this._isDepthTestDirty = true;
  2724. this._isDepthMaskDirty = true;
  2725. this._isDepthFuncDirty = false;
  2726. this._isCullFaceDirty = false;
  2727. this._isCullDirty = false;
  2728. };
  2729. _DepthCullingState.prototype.apply = function (gl) {
  2730. if (!this.isDirty) {
  2731. return;
  2732. }
  2733. if (this._isCullDirty) {
  2734. if (this.cull === true) {
  2735. gl.enable(gl.CULL_FACE);
  2736. } else if (this.cull === false) {
  2737. gl.disable(gl.CULL_FACE);
  2738. }
  2739. this._isCullDirty = false;
  2740. }
  2741. if (this._isCullFaceDirty) {
  2742. gl.cullFace(this.cullFace);
  2743. this._isCullFaceDirty = false;
  2744. }
  2745. if (this._isDepthMaskDirty) {
  2746. gl.depthMask(this.depthMask);
  2747. this._isDepthMaskDirty = false;
  2748. }
  2749. if (this._isDepthTestDirty) {
  2750. if (this.depthTest === true) {
  2751. gl.enable(gl.DEPTH_TEST);
  2752. } else if (this.depthTest === false) {
  2753. gl.disable(gl.DEPTH_TEST);
  2754. }
  2755. this._isDepthTestDirty = false;
  2756. }
  2757. if (this._isDepthFuncDirty) {
  2758. gl.depthFunc(this.depthFunc);
  2759. this._isDepthFuncDirty = false;
  2760. }
  2761. };
  2762. return _DepthCullingState;
  2763. })();
  2764. BABYLON._DepthCullingState = _DepthCullingState;
  2765. var _AlphaState = (function () {
  2766. function _AlphaState() {
  2767. this._isAlphaBlendDirty = false;
  2768. this._isBlendFunctionParametersDirty = false;
  2769. this._alphaBlend = false;
  2770. this._blendFunctionParameters = new Array(4);
  2771. }
  2772. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  2773. get: function () {
  2774. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  2775. },
  2776. enumerable: true,
  2777. configurable: true
  2778. });
  2779. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  2780. get: function () {
  2781. return this._alphaBlend;
  2782. },
  2783. set: function (value) {
  2784. if (this._alphaBlend === value) {
  2785. return;
  2786. }
  2787. this._alphaBlend = value;
  2788. this._isAlphaBlendDirty = true;
  2789. },
  2790. enumerable: true,
  2791. configurable: true
  2792. });
  2793. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  2794. if (this._blendFunctionParameters[0] === value0 && this._blendFunctionParameters[1] === value1 && this._blendFunctionParameters[2] === value2 && this._blendFunctionParameters[3] === value3) {
  2795. return;
  2796. }
  2797. this._blendFunctionParameters[0] = value0;
  2798. this._blendFunctionParameters[1] = value1;
  2799. this._blendFunctionParameters[2] = value2;
  2800. this._blendFunctionParameters[3] = value3;
  2801. this._isBlendFunctionParametersDirty = true;
  2802. };
  2803. _AlphaState.prototype.reset = function () {
  2804. this._alphaBlend = false;
  2805. this._blendFunctionParameters[0] = null;
  2806. this._blendFunctionParameters[1] = null;
  2807. this._blendFunctionParameters[2] = null;
  2808. this._blendFunctionParameters[3] = null;
  2809. this._isAlphaBlendDirty = true;
  2810. this._isBlendFunctionParametersDirty = false;
  2811. };
  2812. _AlphaState.prototype.apply = function (gl) {
  2813. if (!this.isDirty) {
  2814. return;
  2815. }
  2816. if (this._isAlphaBlendDirty) {
  2817. if (this._alphaBlend === true) {
  2818. gl.enable(gl.BLEND);
  2819. } else if (this._alphaBlend === false) {
  2820. gl.disable(gl.BLEND);
  2821. }
  2822. this._isAlphaBlendDirty = false;
  2823. }
  2824. if (this._isBlendFunctionParametersDirty) {
  2825. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  2826. this._isBlendFunctionParametersDirty = false;
  2827. }
  2828. };
  2829. return _AlphaState;
  2830. })();
  2831. BABYLON._AlphaState = _AlphaState;
  2832. var compileShader = function (gl, source, type, defines) {
  2833. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  2834. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  2835. gl.compileShader(shader);
  2836. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  2837. throw new Error(gl.getShaderInfoLog(shader));
  2838. }
  2839. return shader;
  2840. };
  2841. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  2842. var magFilter = gl.NEAREST;
  2843. var minFilter = gl.NEAREST;
  2844. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  2845. magFilter = gl.LINEAR;
  2846. if (generateMipMaps) {
  2847. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  2848. } else {
  2849. minFilter = gl.LINEAR;
  2850. }
  2851. } else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  2852. magFilter = gl.LINEAR;
  2853. if (generateMipMaps) {
  2854. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  2855. } else {
  2856. minFilter = gl.LINEAR;
  2857. }
  2858. } else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  2859. magFilter = gl.NEAREST;
  2860. if (generateMipMaps) {
  2861. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  2862. } else {
  2863. minFilter = gl.NEAREST;
  2864. }
  2865. }
  2866. return {
  2867. min: minFilter,
  2868. mag: magFilter
  2869. };
  2870. };
  2871. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  2872. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  2873. var engine = scene.getEngine();
  2874. var potWidth = BABYLON.Tools.GetExponantOfTwo(width, engine.getCaps().maxTextureSize);
  2875. var potHeight = BABYLON.Tools.GetExponantOfTwo(height, engine.getCaps().maxTextureSize);
  2876. gl.bindTexture(gl.TEXTURE_2D, texture);
  2877. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  2878. processFunction(potWidth, potHeight);
  2879. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  2880. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  2881. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  2882. if (!noMipmap && !isCompressed) {
  2883. gl.generateMipmap(gl.TEXTURE_2D);
  2884. }
  2885. gl.bindTexture(gl.TEXTURE_2D, null);
  2886. engine._activeTexturesCache = [];
  2887. texture._baseWidth = width;
  2888. texture._baseHeight = height;
  2889. texture._width = potWidth;
  2890. texture._height = potHeight;
  2891. texture.isReady = true;
  2892. scene._removePendingData(texture);
  2893. };
  2894. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  2895. var img;
  2896. var onload = function () {
  2897. loadedImages[index] = img;
  2898. loadedImages._internalCount++;
  2899. scene._removePendingData(img);
  2900. if (loadedImages._internalCount == 6) {
  2901. onfinish(loadedImages);
  2902. }
  2903. };
  2904. var onerror = function () {
  2905. scene._removePendingData(img);
  2906. };
  2907. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  2908. scene._addPendingData(img);
  2909. };
  2910. var cascadeLoad = function (rootUrl, scene, onfinish, extensions) {
  2911. var loadedImages = [];
  2912. loadedImages._internalCount = 0;
  2913. for (var index = 0; index < 6; index++) {
  2914. partialLoad(rootUrl + extensions[index], index, loadedImages, scene, onfinish);
  2915. }
  2916. };
  2917. var EngineCapabilities = (function () {
  2918. function EngineCapabilities() {
  2919. }
  2920. return EngineCapabilities;
  2921. })();
  2922. BABYLON.EngineCapabilities = EngineCapabilities;
  2923. var Engine = (function () {
  2924. function Engine(canvas, antialias, options) {
  2925. var _this = this;
  2926. this.isFullscreen = false;
  2927. this.isPointerLock = false;
  2928. this.forceWireframe = false;
  2929. this.cullBackFaces = true;
  2930. this.renderEvenInBackground = true;
  2931. this.scenes = new Array();
  2932. this._windowIsBackground = false;
  2933. this._runningLoop = false;
  2934. this._loadingDivBackgroundColor = "black";
  2935. this._depthCullingState = new _DepthCullingState();
  2936. this._alphaState = new _AlphaState();
  2937. this._loadedTexturesCache = new Array();
  2938. this._activeTexturesCache = new Array();
  2939. this._compiledEffects = {};
  2940. this._uintIndicesCurrentlySet = false;
  2941. this._renderingCanvas = canvas;
  2942. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  2943. options = options || {};
  2944. options.antialias = antialias;
  2945. try {
  2946. this._gl = canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options);
  2947. } catch (e) {
  2948. throw new Error("WebGL not supported");
  2949. }
  2950. if (!this._gl) {
  2951. throw new Error("WebGL not supported");
  2952. }
  2953. this._onBlur = function () {
  2954. _this._windowIsBackground = true;
  2955. };
  2956. this._onFocus = function () {
  2957. _this._windowIsBackground = false;
  2958. };
  2959. window.addEventListener("blur", this._onBlur);
  2960. window.addEventListener("focus", this._onFocus);
  2961. this._workingCanvas = document.createElement("canvas");
  2962. this._workingContext = this._workingCanvas.getContext("2d");
  2963. this._hardwareScalingLevel = 1.0 / (window.devicePixelRatio || 1.0);
  2964. this.resize();
  2965. this._caps = new EngineCapabilities();
  2966. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  2967. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  2968. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  2969. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  2970. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  2971. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  2972. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  2973. 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');
  2974. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  2975. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  2976. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  2977. this.setDepthBuffer(true);
  2978. this.setDepthFunctionToLessOrEqual();
  2979. this.setDepthWrite(true);
  2980. this._onFullscreenChange = function () {
  2981. if (document.fullscreen !== undefined) {
  2982. _this.isFullscreen = document.fullscreen;
  2983. } else if (document.mozFullScreen !== undefined) {
  2984. _this.isFullscreen = document.mozFullScreen;
  2985. } else if (document.webkitIsFullScreen !== undefined) {
  2986. _this.isFullscreen = document.webkitIsFullScreen;
  2987. } else if (document.msIsFullScreen !== undefined) {
  2988. _this.isFullscreen = document.msIsFullScreen;
  2989. }
  2990. if (_this.isFullscreen && _this._pointerLockRequested) {
  2991. canvas.requestPointerLock = canvas.requestPointerLock || canvas.msRequestPointerLock || canvas.mozRequestPointerLock || canvas.webkitRequestPointerLock;
  2992. if (canvas.requestPointerLock) {
  2993. canvas.requestPointerLock();
  2994. }
  2995. }
  2996. };
  2997. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  2998. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  2999. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  3000. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  3001. this._onPointerLockChange = function () {
  3002. _this.isPointerLock = (document.mozPointerLockElement === canvas || document.webkitPointerLockElement === canvas || document.msPointerLockElement === canvas || document.pointerLockElement === canvas);
  3003. };
  3004. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  3005. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  3006. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  3007. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  3008. this._audioEngine = new BABYLON.AudioEngine();
  3009. }
  3010. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  3011. get: function () {
  3012. return Engine._ALPHA_DISABLE;
  3013. },
  3014. enumerable: true,
  3015. configurable: true
  3016. });
  3017. Object.defineProperty(Engine, "ALPHA_ADD", {
  3018. get: function () {
  3019. return Engine._ALPHA_ADD;
  3020. },
  3021. enumerable: true,
  3022. configurable: true
  3023. });
  3024. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  3025. get: function () {
  3026. return Engine._ALPHA_COMBINE;
  3027. },
  3028. enumerable: true,
  3029. configurable: true
  3030. });
  3031. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  3032. get: function () {
  3033. return Engine._DELAYLOADSTATE_NONE;
  3034. },
  3035. enumerable: true,
  3036. configurable: true
  3037. });
  3038. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  3039. get: function () {
  3040. return Engine._DELAYLOADSTATE_LOADED;
  3041. },
  3042. enumerable: true,
  3043. configurable: true
  3044. });
  3045. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  3046. get: function () {
  3047. return Engine._DELAYLOADSTATE_LOADING;
  3048. },
  3049. enumerable: true,
  3050. configurable: true
  3051. });
  3052. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  3053. get: function () {
  3054. return Engine._DELAYLOADSTATE_NOTLOADED;
  3055. },
  3056. enumerable: true,
  3057. configurable: true
  3058. });
  3059. Object.defineProperty(Engine, "Version", {
  3060. get: function () {
  3061. return "2.0.0";
  3062. },
  3063. enumerable: true,
  3064. configurable: true
  3065. });
  3066. Engine.prototype.getAudioEngine = function () {
  3067. return this._audioEngine;
  3068. };
  3069. Engine.prototype.getAspectRatio = function (camera) {
  3070. var viewport = camera.viewport;
  3071. return (this.getRenderWidth() * viewport.width) / (this.getRenderHeight() * viewport.height);
  3072. };
  3073. Engine.prototype.getRenderWidth = function () {
  3074. if (this._currentRenderTarget) {
  3075. return this._currentRenderTarget._width;
  3076. }
  3077. return this._renderingCanvas.width;
  3078. };
  3079. Engine.prototype.getRenderHeight = function () {
  3080. if (this._currentRenderTarget) {
  3081. return this._currentRenderTarget._height;
  3082. }
  3083. return this._renderingCanvas.height;
  3084. };
  3085. Engine.prototype.getRenderingCanvas = function () {
  3086. return this._renderingCanvas;
  3087. };
  3088. Engine.prototype.getRenderingCanvasClientRect = function () {
  3089. return this._renderingCanvas.getBoundingClientRect();
  3090. };
  3091. Engine.prototype.setHardwareScalingLevel = function (level) {
  3092. this._hardwareScalingLevel = level;
  3093. this.resize();
  3094. };
  3095. Engine.prototype.getHardwareScalingLevel = function () {
  3096. return this._hardwareScalingLevel;
  3097. };
  3098. Engine.prototype.getLoadedTexturesCache = function () {
  3099. return this._loadedTexturesCache;
  3100. };
  3101. Engine.prototype.getCaps = function () {
  3102. return this._caps;
  3103. };
  3104. Engine.prototype.setDepthFunctionToGreater = function () {
  3105. this._depthCullingState.depthFunc = this._gl.GREATER;
  3106. };
  3107. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  3108. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  3109. };
  3110. Engine.prototype.setDepthFunctionToLess = function () {
  3111. this._depthCullingState.depthFunc = this._gl.LESS;
  3112. };
  3113. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  3114. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  3115. };
  3116. Engine.prototype.stopRenderLoop = function () {
  3117. this._renderFunction = null;
  3118. this._runningLoop = false;
  3119. };
  3120. Engine.prototype._renderLoop = function () {
  3121. var _this = this;
  3122. var shouldRender = true;
  3123. if (!this.renderEvenInBackground && this._windowIsBackground) {
  3124. shouldRender = false;
  3125. }
  3126. if (shouldRender) {
  3127. this.beginFrame();
  3128. if (this._renderFunction) {
  3129. this._renderFunction();
  3130. }
  3131. this.endFrame();
  3132. }
  3133. if (this._runningLoop) {
  3134. BABYLON.Tools.QueueNewFrame(function () {
  3135. _this._renderLoop();
  3136. });
  3137. }
  3138. };
  3139. Engine.prototype.runRenderLoop = function (renderFunction) {
  3140. var _this = this;
  3141. this._runningLoop = true;
  3142. this._renderFunction = renderFunction;
  3143. BABYLON.Tools.QueueNewFrame(function () {
  3144. _this._renderLoop();
  3145. });
  3146. };
  3147. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  3148. if (this.isFullscreen) {
  3149. BABYLON.Tools.ExitFullscreen();
  3150. } else {
  3151. this._pointerLockRequested = requestPointerLock;
  3152. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  3153. }
  3154. };
  3155. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  3156. this.applyStates();
  3157. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  3158. if (this._depthCullingState.depthMask) {
  3159. this._gl.clearDepth(1.0);
  3160. }
  3161. var mode = 0;
  3162. if (backBuffer)
  3163. mode |= this._gl.COLOR_BUFFER_BIT;
  3164. if (depthStencil && this._depthCullingState.depthMask)
  3165. mode |= this._gl.DEPTH_BUFFER_BIT;
  3166. this._gl.clear(mode);
  3167. };
  3168. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  3169. var width = requiredWidth || this._renderingCanvas.width;
  3170. var height = requiredHeight || this._renderingCanvas.height;
  3171. var x = viewport.x || 0;
  3172. var y = viewport.y || 0;
  3173. this._cachedViewport = viewport;
  3174. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  3175. };
  3176. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  3177. this._cachedViewport = null;
  3178. this._gl.viewport(x, y, width, height);
  3179. };
  3180. Engine.prototype.beginFrame = function () {
  3181. BABYLON.Tools._MeasureFps();
  3182. };
  3183. Engine.prototype.endFrame = function () {
  3184. this.flushFramebuffer();
  3185. };
  3186. Engine.prototype.resize = function () {
  3187. this.setSize(this._renderingCanvas.clientWidth / this._hardwareScalingLevel, this._renderingCanvas.clientHeight / this._hardwareScalingLevel);
  3188. };
  3189. Engine.prototype.setSize = function (width, height) {
  3190. this._renderingCanvas.width = width;
  3191. this._renderingCanvas.height = height;
  3192. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  3193. };
  3194. Engine.prototype.bindFramebuffer = function (texture) {
  3195. this._currentRenderTarget = texture;
  3196. var gl = this._gl;
  3197. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  3198. this._gl.viewport(0, 0, texture._width, texture._height);
  3199. this.wipeCaches();
  3200. };
  3201. Engine.prototype.unBindFramebuffer = function (texture) {
  3202. this._currentRenderTarget = null;
  3203. if (texture.generateMipMaps) {
  3204. var gl = this._gl;
  3205. gl.bindTexture(gl.TEXTURE_2D, texture);
  3206. gl.generateMipmap(gl.TEXTURE_2D);
  3207. gl.bindTexture(gl.TEXTURE_2D, null);
  3208. }
  3209. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  3210. };
  3211. Engine.prototype.flushFramebuffer = function () {
  3212. this._gl.flush();
  3213. };
  3214. Engine.prototype.restoreDefaultFramebuffer = function () {
  3215. this._currentRenderTarget = null;
  3216. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  3217. this.setViewport(this._cachedViewport);
  3218. this.wipeCaches();
  3219. };
  3220. Engine.prototype._resetVertexBufferBinding = function () {
  3221. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  3222. this._cachedVertexBuffers = null;
  3223. };
  3224. Engine.prototype.createVertexBuffer = function (vertices) {
  3225. var vbo = this._gl.createBuffer();
  3226. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  3227. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  3228. this._resetVertexBufferBinding();
  3229. vbo.references = 1;
  3230. return vbo;
  3231. };
  3232. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  3233. var vbo = this._gl.createBuffer();
  3234. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  3235. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  3236. this._resetVertexBufferBinding();
  3237. vbo.references = 1;
  3238. return vbo;
  3239. };
  3240. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, length) {
  3241. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  3242. if (vertices instanceof Float32Array) {
  3243. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices);
  3244. } else {
  3245. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices));
  3246. }
  3247. this._resetVertexBufferBinding();
  3248. };
  3249. Engine.prototype._resetIndexBufferBinding = function () {
  3250. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  3251. this._cachedIndexBuffer = null;
  3252. };
  3253. Engine.prototype.createIndexBuffer = function (indices) {
  3254. var vbo = this._gl.createBuffer();
  3255. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  3256. var arrayBuffer;
  3257. var need32Bits = false;
  3258. if (this._caps.uintIndices) {
  3259. for (var index = 0; index < indices.length; index++) {
  3260. if (indices[index] > 65535) {
  3261. need32Bits = true;
  3262. break;
  3263. }
  3264. }
  3265. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  3266. } else {
  3267. arrayBuffer = new Uint16Array(indices);
  3268. }
  3269. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  3270. this._resetIndexBufferBinding();
  3271. vbo.references = 1;
  3272. vbo.is32Bits = need32Bits;
  3273. return vbo;
  3274. };
  3275. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  3276. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  3277. this._cachedVertexBuffers = vertexBuffer;
  3278. this._cachedEffectForVertexBuffers = effect;
  3279. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  3280. var offset = 0;
  3281. for (var index = 0; index < vertexDeclaration.length; index++) {
  3282. var order = effect.getAttributeLocation(index);
  3283. if (order >= 0) {
  3284. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  3285. }
  3286. offset += vertexDeclaration[index] * 4;
  3287. }
  3288. }
  3289. if (this._cachedIndexBuffer !== indexBuffer) {
  3290. this._cachedIndexBuffer = indexBuffer;
  3291. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  3292. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  3293. }
  3294. };
  3295. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  3296. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  3297. this._cachedVertexBuffers = vertexBuffers;
  3298. this._cachedEffectForVertexBuffers = effect;
  3299. var attributes = effect.getAttributesNames();
  3300. for (var index = 0; index < attributes.length; index++) {
  3301. var order = effect.getAttributeLocation(index);
  3302. if (order >= 0) {
  3303. var vertexBuffer = vertexBuffers[attributes[index]];
  3304. if (!vertexBuffer) {
  3305. continue;
  3306. }
  3307. var stride = vertexBuffer.getStrideSize();
  3308. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  3309. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  3310. }
  3311. }
  3312. }
  3313. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  3314. this._cachedIndexBuffer = indexBuffer;
  3315. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  3316. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  3317. }
  3318. };
  3319. Engine.prototype._releaseBuffer = function (buffer) {
  3320. buffer.references--;
  3321. if (buffer.references === 0) {
  3322. this._gl.deleteBuffer(buffer);
  3323. return true;
  3324. }
  3325. return false;
  3326. };
  3327. Engine.prototype.createInstancesBuffer = function (capacity) {
  3328. var buffer = this._gl.createBuffer();
  3329. buffer.capacity = capacity;
  3330. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  3331. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  3332. return buffer;
  3333. };
  3334. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  3335. this._gl.deleteBuffer(buffer);
  3336. };
  3337. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  3338. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  3339. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  3340. for (var index = 0; index < 4; index++) {
  3341. var offsetLocation = offsetLocations[index];
  3342. this._gl.enableVertexAttribArray(offsetLocation);
  3343. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  3344. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  3345. }
  3346. };
  3347. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  3348. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  3349. for (var index = 0; index < 4; index++) {
  3350. var offsetLocation = offsetLocations[index];
  3351. this._gl.disableVertexAttribArray(offsetLocation);
  3352. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  3353. }
  3354. };
  3355. Engine.prototype.applyStates = function () {
  3356. this._depthCullingState.apply(this._gl);
  3357. this._alphaState.apply(this._gl);
  3358. };
  3359. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  3360. this.applyStates();
  3361. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  3362. if (instancesCount) {
  3363. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * 2, instancesCount);
  3364. return;
  3365. }
  3366. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * 2);
  3367. };
  3368. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  3369. this.applyStates();
  3370. if (instancesCount) {
  3371. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  3372. return;
  3373. }
  3374. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  3375. };
  3376. Engine.prototype._releaseEffect = function (effect) {
  3377. if (this._compiledEffects[effect._key]) {
  3378. delete this._compiledEffects[effect._key];
  3379. if (effect.getProgram()) {
  3380. this._gl.deleteProgram(effect.getProgram());
  3381. }
  3382. }
  3383. };
  3384. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  3385. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  3386. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  3387. var name = vertex + "+" + fragment + "@" + defines;
  3388. if (this._compiledEffects[name]) {
  3389. return this._compiledEffects[name];
  3390. }
  3391. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  3392. effect._key = name;
  3393. this._compiledEffects[name] = effect;
  3394. return effect;
  3395. };
  3396. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  3397. if (typeof uniformsNames === "undefined") { uniformsNames = []; }
  3398. if (typeof samplers === "undefined") { samplers = []; }
  3399. if (typeof defines === "undefined") { defines = ""; }
  3400. return this.createEffect({
  3401. vertex: "particles",
  3402. fragmentElement: fragmentName
  3403. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  3404. };
  3405. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  3406. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  3407. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  3408. var shaderProgram = this._gl.createProgram();
  3409. this._gl.attachShader(shaderProgram, vertexShader);
  3410. this._gl.attachShader(shaderProgram, fragmentShader);
  3411. this._gl.linkProgram(shaderProgram);
  3412. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  3413. if (!linked) {
  3414. var error = this._gl.getProgramInfoLog(shaderProgram);
  3415. if (error) {
  3416. throw new Error(error);
  3417. }
  3418. }
  3419. this._gl.deleteShader(vertexShader);
  3420. this._gl.deleteShader(fragmentShader);
  3421. return shaderProgram;
  3422. };
  3423. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  3424. var results = [];
  3425. for (var index = 0; index < uniformsNames.length; index++) {
  3426. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  3427. }
  3428. return results;
  3429. };
  3430. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  3431. var results = [];
  3432. for (var index = 0; index < attributesNames.length; index++) {
  3433. try {
  3434. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  3435. } catch (e) {
  3436. results.push(-1);
  3437. }
  3438. }
  3439. return results;
  3440. };
  3441. Engine.prototype.enableEffect = function (effect) {
  3442. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  3443. if (effect && effect.onBind) {
  3444. effect.onBind(effect);
  3445. }
  3446. return;
  3447. }
  3448. this._vertexAttribArrays = this._vertexAttribArrays || [];
  3449. this._gl.useProgram(effect.getProgram());
  3450. for (var i in this._vertexAttribArrays) {
  3451. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  3452. continue;
  3453. }
  3454. this._vertexAttribArrays[i] = false;
  3455. this._gl.disableVertexAttribArray(i);
  3456. }
  3457. var attributesCount = effect.getAttributesCount();
  3458. for (var index = 0; index < attributesCount; index++) {
  3459. var order = effect.getAttributeLocation(index);
  3460. if (order >= 0) {
  3461. this._vertexAttribArrays[order] = true;
  3462. this._gl.enableVertexAttribArray(order);
  3463. }
  3464. }
  3465. this._currentEffect = effect;
  3466. if (effect.onBind) {
  3467. effect.onBind(effect);
  3468. }
  3469. };
  3470. Engine.prototype.setArray = function (uniform, array) {
  3471. if (!uniform)
  3472. return;
  3473. this._gl.uniform1fv(uniform, array);
  3474. };
  3475. Engine.prototype.setMatrices = function (uniform, matrices) {
  3476. if (!uniform)
  3477. return;
  3478. this._gl.uniformMatrix4fv(uniform, false, matrices);
  3479. };
  3480. Engine.prototype.setMatrix = function (uniform, matrix) {
  3481. if (!uniform)
  3482. return;
  3483. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  3484. };
  3485. Engine.prototype.setFloat = function (uniform, value) {
  3486. if (!uniform)
  3487. return;
  3488. this._gl.uniform1f(uniform, value);
  3489. };
  3490. Engine.prototype.setFloat2 = function (uniform, x, y) {
  3491. if (!uniform)
  3492. return;
  3493. this._gl.uniform2f(uniform, x, y);
  3494. };
  3495. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  3496. if (!uniform)
  3497. return;
  3498. this._gl.uniform3f(uniform, x, y, z);
  3499. };
  3500. Engine.prototype.setBool = function (uniform, bool) {
  3501. if (!uniform)
  3502. return;
  3503. this._gl.uniform1i(uniform, bool);
  3504. };
  3505. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  3506. if (!uniform)
  3507. return;
  3508. this._gl.uniform4f(uniform, x, y, z, w);
  3509. };
  3510. Engine.prototype.setColor3 = function (uniform, color3) {
  3511. if (!uniform)
  3512. return;
  3513. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  3514. };
  3515. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  3516. if (!uniform)
  3517. return;
  3518. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  3519. };
  3520. Engine.prototype.setState = function (culling, force) {
  3521. if (this._depthCullingState.cull !== culling || force) {
  3522. if (culling) {
  3523. this._depthCullingState.cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  3524. this._depthCullingState.cull = true;
  3525. } else {
  3526. this._depthCullingState.cull = false;
  3527. }
  3528. }
  3529. };
  3530. Engine.prototype.setDepthBuffer = function (enable) {
  3531. this._depthCullingState.depthTest = enable;
  3532. };
  3533. Engine.prototype.getDepthWrite = function () {
  3534. return this._depthCullingState.depthMask;
  3535. };
  3536. Engine.prototype.setDepthWrite = function (enable) {
  3537. this._depthCullingState.depthMask = enable;
  3538. };
  3539. Engine.prototype.setColorWrite = function (enable) {
  3540. this._gl.colorMask(enable, enable, enable, enable);
  3541. };
  3542. Engine.prototype.setAlphaMode = function (mode) {
  3543. switch (mode) {
  3544. case BABYLON.Engine.ALPHA_DISABLE:
  3545. this.setDepthWrite(true);
  3546. this._alphaState.alphaBlend = false;
  3547. break;
  3548. case BABYLON.Engine.ALPHA_COMBINE:
  3549. this.setDepthWrite(false);
  3550. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  3551. this._alphaState.alphaBlend = true;
  3552. break;
  3553. case BABYLON.Engine.ALPHA_ADD:
  3554. this.setDepthWrite(false);
  3555. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  3556. this._alphaState.alphaBlend = true;
  3557. break;
  3558. }
  3559. };
  3560. Engine.prototype.setAlphaTesting = function (enable) {
  3561. this._alphaTest = enable;
  3562. };
  3563. Engine.prototype.getAlphaTesting = function () {
  3564. return this._alphaTest;
  3565. };
  3566. Engine.prototype.wipeCaches = function () {
  3567. this._activeTexturesCache = [];
  3568. this._currentEffect = null;
  3569. this._depthCullingState.reset();
  3570. this._alphaState.reset();
  3571. this._cachedVertexBuffers = null;
  3572. this._cachedIndexBuffer = null;
  3573. this._cachedEffectForVertexBuffers = null;
  3574. };
  3575. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  3576. var gl = this._gl;
  3577. gl.bindTexture(gl.TEXTURE_2D, texture);
  3578. var magFilter = gl.NEAREST;
  3579. var minFilter = gl.NEAREST;
  3580. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  3581. magFilter = gl.LINEAR;
  3582. minFilter = gl.LINEAR;
  3583. } else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  3584. magFilter = gl.LINEAR;
  3585. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  3586. }
  3587. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  3588. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  3589. gl.bindTexture(gl.TEXTURE_2D, null);
  3590. };
  3591. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  3592. var _this = this;
  3593. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  3594. if (typeof onLoad === "undefined") { onLoad = null; }
  3595. if (typeof onError === "undefined") { onError = null; }
  3596. if (typeof buffer === "undefined") { buffer = null; }
  3597. var texture = this._gl.createTexture();
  3598. var extension;
  3599. var fromData = false;
  3600. if (url.substr(0, 5) === "data:") {
  3601. fromData = true;
  3602. }
  3603. if (!fromData)
  3604. extension = url.substr(url.length - 4, 4).toLowerCase();
  3605. else {
  3606. var oldUrl = url;
  3607. fromData = oldUrl.split(':');
  3608. url = oldUrl;
  3609. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  3610. }
  3611. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  3612. var isTGA = (extension === ".tga");
  3613. scene._addPendingData(texture);
  3614. texture.url = url;
  3615. texture.noMipmap = noMipmap;
  3616. texture.references = 1;
  3617. this._loadedTexturesCache.push(texture);
  3618. var onerror = function () {
  3619. scene._removePendingData(texture);
  3620. if (onError) {
  3621. onError();
  3622. }
  3623. };
  3624. if (isTGA) {
  3625. var callback = function (arrayBuffer) {
  3626. var data = new Uint8Array(arrayBuffer);
  3627. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  3628. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  3629. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  3630. if (onLoad) {
  3631. onLoad();
  3632. }
  3633. }, samplingMode);
  3634. };
  3635. if (!(fromData instanceof Array))
  3636. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  3637. callback(arrayBuffer);
  3638. }, onerror, scene.database, true);
  3639. else
  3640. callback(buffer);
  3641. } else if (isDDS) {
  3642. callback = function (data) {
  3643. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  3644. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) == 1);
  3645. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  3646. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  3647. if (onLoad) {
  3648. onLoad();
  3649. }
  3650. }, samplingMode);
  3651. };
  3652. if (!(fromData instanceof Array))
  3653. BABYLON.Tools.LoadFile(url, function (data) {
  3654. callback(data);
  3655. }, onerror, scene.database, true);
  3656. else
  3657. callback(buffer);
  3658. } else {
  3659. var onload = function (img) {
  3660. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  3661. var isPot = (img.width == potWidth && img.height == potHeight);
  3662. if (!isPot) {
  3663. _this._workingCanvas.width = potWidth;
  3664. _this._workingCanvas.height = potHeight;
  3665. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  3666. }
  3667. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  3668. if (onLoad) {
  3669. onLoad();
  3670. }
  3671. }, samplingMode);
  3672. };
  3673. if (!(fromData instanceof Array))
  3674. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  3675. else
  3676. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  3677. }
  3678. return texture;
  3679. };
  3680. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  3681. var texture = this._gl.createTexture();
  3682. width = BABYLON.Tools.GetExponantOfTwo(width, this._caps.maxTextureSize);
  3683. height = BABYLON.Tools.GetExponantOfTwo(height, this._caps.maxTextureSize);
  3684. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  3685. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  3686. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  3687. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  3688. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  3689. this._activeTexturesCache = [];
  3690. texture._baseWidth = width;
  3691. texture._baseHeight = height;
  3692. texture._width = width;
  3693. texture._height = height;
  3694. texture.isReady = false;
  3695. texture.generateMipMaps = generateMipMaps;
  3696. texture.references = 1;
  3697. this._loadedTexturesCache.push(texture);
  3698. return texture;
  3699. };
  3700. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  3701. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  3702. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  3703. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  3704. if (texture.generateMipMaps) {
  3705. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  3706. }
  3707. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  3708. this._activeTexturesCache = [];
  3709. texture.isReady = true;
  3710. };
  3711. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  3712. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  3713. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1);
  3714. if (video.videoWidth !== texture._width || video.videoHeight !== texture._height) {
  3715. if (!texture._workingCanvas) {
  3716. texture._workingCanvas = document.createElement("canvas");
  3717. texture._workingContext = texture._workingCanvas.getContext("2d");
  3718. texture._workingCanvas.width = texture._width;
  3719. texture._workingCanvas.height = texture._height;
  3720. }
  3721. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  3722. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  3723. } else {
  3724. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  3725. }
  3726. if (texture.generateMipMaps) {
  3727. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  3728. }
  3729. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  3730. this._activeTexturesCache = [];
  3731. texture.isReady = true;
  3732. };
  3733. Engine.prototype.createRenderTargetTexture = function (size, options) {
  3734. var generateMipMaps = false;
  3735. var generateDepthBuffer = true;
  3736. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  3737. if (options !== undefined) {
  3738. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipmaps;
  3739. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  3740. if (options.samplingMode !== undefined) {
  3741. samplingMode = options.samplingMode;
  3742. }
  3743. }
  3744. var gl = this._gl;
  3745. var texture = gl.createTexture();
  3746. gl.bindTexture(gl.TEXTURE_2D, texture);
  3747. var width = size.width || size;
  3748. var height = size.height || size;
  3749. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  3750. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  3751. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  3752. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  3753. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  3754. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  3755. var depthBuffer;
  3756. if (generateDepthBuffer) {
  3757. depthBuffer = gl.createRenderbuffer();
  3758. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  3759. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  3760. }
  3761. var framebuffer = gl.createFramebuffer();
  3762. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  3763. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  3764. if (generateDepthBuffer) {
  3765. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  3766. }
  3767. gl.bindTexture(gl.TEXTURE_2D, null);
  3768. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  3769. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  3770. texture._framebuffer = framebuffer;
  3771. if (generateDepthBuffer) {
  3772. texture._depthBuffer = depthBuffer;
  3773. }
  3774. texture._width = width;
  3775. texture._height = height;
  3776. texture.isReady = true;
  3777. texture.generateMipMaps = generateMipMaps;
  3778. texture.references = 1;
  3779. this._activeTexturesCache = [];
  3780. this._loadedTexturesCache.push(texture);
  3781. return texture;
  3782. };
  3783. Engine.prototype.createCubeTexture = function (rootUrl, scene, extensions, noMipmap) {
  3784. var _this = this;
  3785. var gl = this._gl;
  3786. var texture = gl.createTexture();
  3787. texture.isCube = true;
  3788. texture.url = rootUrl;
  3789. texture.references = 1;
  3790. this._loadedTexturesCache.push(texture);
  3791. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  3792. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  3793. if (isDDS) {
  3794. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  3795. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  3796. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  3797. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  3798. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  3799. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  3800. if (!noMipmap && !info.isFourCC && info.mipmapCount == 1) {
  3801. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  3802. }
  3803. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  3804. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  3805. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  3806. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  3807. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  3808. _this._activeTexturesCache = [];
  3809. texture._width = info.width;
  3810. texture._height = info.height;
  3811. texture.isReady = true;
  3812. }, null, null, true);
  3813. } else {
  3814. cascadeLoad(rootUrl, scene, function (imgs) {
  3815. var width = BABYLON.Tools.GetExponantOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  3816. var height = width;
  3817. _this._workingCanvas.width = width;
  3818. _this._workingCanvas.height = height;
  3819. var faces = [
  3820. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  3821. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  3822. ];
  3823. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  3824. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  3825. for (var index = 0; index < faces.length; index++) {
  3826. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  3827. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  3828. }
  3829. if (!noMipmap) {
  3830. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  3831. }
  3832. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  3833. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  3834. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  3835. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  3836. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  3837. _this._activeTexturesCache = [];
  3838. texture._width = width;
  3839. texture._height = height;
  3840. texture.isReady = true;
  3841. }, extensions);
  3842. }
  3843. return texture;
  3844. };
  3845. Engine.prototype._releaseTexture = function (texture) {
  3846. var gl = this._gl;
  3847. if (texture._framebuffer) {
  3848. gl.deleteFramebuffer(texture._framebuffer);
  3849. }
  3850. if (texture._depthBuffer) {
  3851. gl.deleteRenderbuffer(texture._depthBuffer);
  3852. }
  3853. gl.deleteTexture(texture);
  3854. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  3855. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  3856. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  3857. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  3858. this._activeTexturesCache[channel] = null;
  3859. }
  3860. var index = this._loadedTexturesCache.indexOf(texture);
  3861. if (index !== -1) {
  3862. this._loadedTexturesCache.splice(index, 1);
  3863. }
  3864. };
  3865. Engine.prototype.bindSamplers = function (effect) {
  3866. this._gl.useProgram(effect.getProgram());
  3867. var samplers = effect.getSamplers();
  3868. for (var index = 0; index < samplers.length; index++) {
  3869. var uniform = effect.getUniform(samplers[index]);
  3870. this._gl.uniform1i(uniform, index);
  3871. }
  3872. this._currentEffect = null;
  3873. };
  3874. Engine.prototype._bindTexture = function (channel, texture) {
  3875. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  3876. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  3877. this._activeTexturesCache[channel] = null;
  3878. };
  3879. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  3880. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  3881. };
  3882. Engine.prototype.setTexture = function (channel, texture) {
  3883. if (channel < 0) {
  3884. return;
  3885. }
  3886. if (!texture || !texture.isReady()) {
  3887. if (this._activeTexturesCache[channel] != null) {
  3888. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  3889. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  3890. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  3891. this._activeTexturesCache[channel] = null;
  3892. }
  3893. return;
  3894. }
  3895. if (texture instanceof BABYLON.VideoTexture) {
  3896. if (texture.update()) {
  3897. this._activeTexturesCache[channel] = null;
  3898. }
  3899. } else if (texture.delayLoadState == BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  3900. texture.delayLoad();
  3901. return;
  3902. }
  3903. if (this._activeTexturesCache[channel] == texture) {
  3904. return;
  3905. }
  3906. this._activeTexturesCache[channel] = texture;
  3907. var internalTexture = texture.getInternalTexture();
  3908. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  3909. if (internalTexture.isCube) {
  3910. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  3911. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  3912. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  3913. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  3914. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  3915. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  3916. }
  3917. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  3918. } else {
  3919. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  3920. if (internalTexture._cachedWrapU !== texture.wrapU) {
  3921. internalTexture._cachedWrapU = texture.wrapU;
  3922. switch (texture.wrapU) {
  3923. case BABYLON.Texture.WRAP_ADDRESSMODE:
  3924. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  3925. break;
  3926. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  3927. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  3928. break;
  3929. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  3930. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  3931. break;
  3932. }
  3933. }
  3934. if (internalTexture._cachedWrapV !== texture.wrapV) {
  3935. internalTexture._cachedWrapV = texture.wrapV;
  3936. switch (texture.wrapV) {
  3937. case BABYLON.Texture.WRAP_ADDRESSMODE:
  3938. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  3939. break;
  3940. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  3941. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  3942. break;
  3943. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  3944. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  3945. break;
  3946. }
  3947. }
  3948. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  3949. }
  3950. };
  3951. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  3952. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  3953. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== texture.anisotropicFilteringLevel) {
  3954. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(texture.anisotropicFilteringLevel, this._caps.maxAnisotropy));
  3955. texture._cachedAnisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  3956. }
  3957. };
  3958. Engine.prototype.readPixels = function (x, y, width, height) {
  3959. var data = new Uint8Array(height * width * 4);
  3960. this._gl.readPixels(0, 0, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  3961. return data;
  3962. };
  3963. Engine.prototype.dispose = function () {
  3964. this.hideLoadingUI();
  3965. this.stopRenderLoop();
  3966. while (this.scenes.length) {
  3967. this.scenes[0].dispose();
  3968. }
  3969. for (var name in this._compiledEffects) {
  3970. this._gl.deleteProgram(this._compiledEffects[name]._program);
  3971. }
  3972. for (var i in this._vertexAttribArrays) {
  3973. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  3974. continue;
  3975. }
  3976. this._gl.disableVertexAttribArray(i);
  3977. }
  3978. window.removeEventListener("blur", this._onBlur);
  3979. window.removeEventListener("focus", this._onFocus);
  3980. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  3981. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  3982. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  3983. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  3984. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  3985. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  3986. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  3987. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  3988. };
  3989. Engine.prototype.displayLoadingUI = function () {
  3990. var _this = this;
  3991. this._loadingDiv = document.createElement("div");
  3992. this._loadingDiv.style.opacity = "0";
  3993. this._loadingDiv.style.transition = "opacity 1.5s ease";
  3994. this._loadingTextDiv = document.createElement("div");
  3995. this._loadingTextDiv.style.position = "absolute";
  3996. this._loadingTextDiv.style.left = "0";
  3997. this._loadingTextDiv.style.top = "50%";
  3998. this._loadingTextDiv.style.marginTop = "80px";
  3999. this._loadingTextDiv.style.width = "100%";
  4000. this._loadingTextDiv.style.height = "20px";
  4001. this._loadingTextDiv.style.fontFamily = "Arial";
  4002. this._loadingTextDiv.style.fontSize = "14px";
  4003. this._loadingTextDiv.style.color = "white";
  4004. this._loadingTextDiv.style.textAlign = "center";
  4005. this._loadingTextDiv.innerHTML = "Loading";
  4006. this._loadingDiv.appendChild(this._loadingTextDiv);
  4007. var imgBack = new Image();
  4008. 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==";
  4009. imgBack.style.position = "absolute";
  4010. imgBack.style.left = "50%";
  4011. imgBack.style.top = "50%";
  4012. imgBack.style.marginLeft = "-50px";
  4013. imgBack.style.marginTop = "-50px";
  4014. imgBack.style.transition = "transform 1.0s ease";
  4015. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  4016. var deg = 360;
  4017. var onTransitionEnd = function () {
  4018. deg += 360;
  4019. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  4020. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  4021. };
  4022. imgBack.addEventListener("transitionend", onTransitionEnd);
  4023. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  4024. this._loadingDiv.appendChild(imgBack);
  4025. var imgFront = new Image();
  4026. 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=";
  4027. imgFront.style.position = "absolute";
  4028. imgFront.style.left = "50%";
  4029. imgFront.style.top = "50%";
  4030. imgFront.style.marginLeft = "-50px";
  4031. imgFront.style.marginTop = "-50px";
  4032. this._loadingDiv.appendChild(imgFront);
  4033. this._resizeLoadingUI = function () {
  4034. var canvasRect = _this.getRenderingCanvasClientRect();
  4035. _this._loadingDiv.style.position = "absolute";
  4036. _this._loadingDiv.style.left = canvasRect.left + "px";
  4037. _this._loadingDiv.style.top = canvasRect.top + "px";
  4038. _this._loadingDiv.style.width = canvasRect.width + "px";
  4039. _this._loadingDiv.style.height = canvasRect.height + "px";
  4040. };
  4041. this._resizeLoadingUI();
  4042. window.addEventListener("resize", this._resizeLoadingUI);
  4043. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  4044. document.body.appendChild(this._loadingDiv);
  4045. setTimeout(function () {
  4046. _this._loadingDiv.style.opacity = "1";
  4047. imgBack.style.transform = "rotateZ(360deg)";
  4048. imgBack.style.webkitTransform = "rotateZ(360deg)";
  4049. }, 0);
  4050. };
  4051. Object.defineProperty(Engine.prototype, "loadingUIText", {
  4052. set: function (text) {
  4053. if (!this._loadingDiv) {
  4054. return;
  4055. }
  4056. this._loadingTextDiv.innerHTML = text;
  4057. },
  4058. enumerable: true,
  4059. configurable: true
  4060. });
  4061. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  4062. get: function () {
  4063. return this._loadingDivBackgroundColor;
  4064. },
  4065. set: function (color) {
  4066. this._loadingDivBackgroundColor = color;
  4067. if (!this._loadingDiv) {
  4068. return;
  4069. }
  4070. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  4071. },
  4072. enumerable: true,
  4073. configurable: true
  4074. });
  4075. Engine.prototype.hideLoadingUI = function () {
  4076. var _this = this;
  4077. if (!this._loadingDiv) {
  4078. return;
  4079. }
  4080. var onTransitionEnd = function () {
  4081. if (!_this._loadingDiv) {
  4082. return;
  4083. }
  4084. document.body.removeChild(_this._loadingDiv);
  4085. window.removeEventListener("resize", _this._resizeLoadingUI);
  4086. _this._loadingDiv = null;
  4087. };
  4088. this._loadingDiv.style.opacity = "0";
  4089. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  4090. };
  4091. Engine.isSupported = function () {
  4092. try {
  4093. if (navigator.isCocoonJS) {
  4094. return true;
  4095. }
  4096. var tempcanvas = document.createElement("canvas");
  4097. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  4098. return gl != null && !!window.WebGLRenderingContext;
  4099. } catch (e) {
  4100. return false;
  4101. }
  4102. };
  4103. Engine._ALPHA_DISABLE = 0;
  4104. Engine._ALPHA_ADD = 1;
  4105. Engine._ALPHA_COMBINE = 2;
  4106. Engine._DELAYLOADSTATE_NONE = 0;
  4107. Engine._DELAYLOADSTATE_LOADED = 1;
  4108. Engine._DELAYLOADSTATE_LOADING = 2;
  4109. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  4110. Engine.Epsilon = 0.001;
  4111. Engine.CollisionsEpsilon = 0.001;
  4112. Engine.ShadersRepository = "Babylon/Shaders/";
  4113. return Engine;
  4114. })();
  4115. BABYLON.Engine = Engine;
  4116. })(BABYLON || (BABYLON = {}));
  4117. var BABYLON;
  4118. (function (BABYLON) {
  4119. var Node = (function () {
  4120. function Node(name, scene) {
  4121. this.state = "";
  4122. this.animations = new Array();
  4123. this._childrenFlag = -1;
  4124. this._isEnabled = true;
  4125. this._isReady = true;
  4126. this._currentRenderId = -1;
  4127. this.name = name;
  4128. this.id = name;
  4129. this._scene = scene;
  4130. this._initCache();
  4131. }
  4132. Node.prototype.getScene = function () {
  4133. return this._scene;
  4134. };
  4135. Node.prototype.getEngine = function () {
  4136. return this._scene.getEngine();
  4137. };
  4138. Node.prototype.getWorldMatrix = function () {
  4139. return BABYLON.Matrix.Identity();
  4140. };
  4141. Node.prototype._initCache = function () {
  4142. this._cache = {};
  4143. this._cache.parent = undefined;
  4144. };
  4145. Node.prototype.updateCache = function (force) {
  4146. if (!force && this.isSynchronized())
  4147. return;
  4148. this._cache.parent = this.parent;
  4149. this._updateCache();
  4150. };
  4151. Node.prototype._updateCache = function (ignoreParentClass) {
  4152. };
  4153. Node.prototype._isSynchronized = function () {
  4154. return true;
  4155. };
  4156. Node.prototype.isSynchronizedWithParent = function () {
  4157. return this.parent ? this.parent._currentRenderId <= this._currentRenderId : true;
  4158. };
  4159. Node.prototype.isSynchronized = function (updateCache) {
  4160. var check = this.hasNewParent();
  4161. check = check || !this.isSynchronizedWithParent();
  4162. check = check || !this._isSynchronized();
  4163. if (updateCache)
  4164. this.updateCache(true);
  4165. return !check;
  4166. };
  4167. Node.prototype.hasNewParent = function (update) {
  4168. if (this._cache.parent === this.parent)
  4169. return false;
  4170. if (update)
  4171. this._cache.parent = this.parent;
  4172. return true;
  4173. };
  4174. Node.prototype.isReady = function () {
  4175. return this._isReady;
  4176. };
  4177. Node.prototype.isEnabled = function () {
  4178. if (!this._isEnabled) {
  4179. return false;
  4180. }
  4181. if (this.parent) {
  4182. return this.parent.isEnabled();
  4183. }
  4184. return true;
  4185. };
  4186. Node.prototype.setEnabled = function (value) {
  4187. this._isEnabled = value;
  4188. };
  4189. Node.prototype.isDescendantOf = function (ancestor) {
  4190. if (this.parent) {
  4191. if (this.parent === ancestor) {
  4192. return true;
  4193. }
  4194. return this.parent.isDescendantOf(ancestor);
  4195. }
  4196. return false;
  4197. };
  4198. Node.prototype._getDescendants = function (list, results) {
  4199. for (var index = 0; index < list.length; index++) {
  4200. var item = list[index];
  4201. if (item.isDescendantOf(this)) {
  4202. results.push(item);
  4203. }
  4204. }
  4205. };
  4206. Node.prototype.getDescendants = function () {
  4207. var results = [];
  4208. this._getDescendants(this._scene.meshes, results);
  4209. this._getDescendants(this._scene.lights, results);
  4210. this._getDescendants(this._scene.cameras, results);
  4211. return results;
  4212. };
  4213. Node.prototype._setReady = function (state) {
  4214. if (state == this._isReady) {
  4215. return;
  4216. }
  4217. if (!state) {
  4218. this._isReady = false;
  4219. return;
  4220. }
  4221. this._isReady = true;
  4222. if (this.onReady) {
  4223. this.onReady(this);
  4224. }
  4225. };
  4226. return Node;
  4227. })();
  4228. BABYLON.Node = Node;
  4229. })(BABYLON || (BABYLON = {}));
  4230. var BABYLON;
  4231. (function (BABYLON) {
  4232. var BoundingSphere = (function () {
  4233. function BoundingSphere(minimum, maximum) {
  4234. this.minimum = minimum;
  4235. this.maximum = maximum;
  4236. this._tempRadiusVector = BABYLON.Vector3.Zero();
  4237. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  4238. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  4239. this.radius = distance * 0.5;
  4240. this.centerWorld = BABYLON.Vector3.Zero();
  4241. this._update(BABYLON.Matrix.Identity());
  4242. }
  4243. BoundingSphere.prototype._update = function (world) {
  4244. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  4245. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  4246. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  4247. };
  4248. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  4249. for (var i = 0; i < 6; i++) {
  4250. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  4251. return false;
  4252. }
  4253. return true;
  4254. };
  4255. BoundingSphere.prototype.intersectsPoint = function (point) {
  4256. var x = this.centerWorld.x - point.x;
  4257. var y = this.centerWorld.y - point.y;
  4258. var z = this.centerWorld.z - point.z;
  4259. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  4260. if (Math.abs(this.radiusWorld - distance) < BABYLON.Engine.Epsilon)
  4261. return false;
  4262. return true;
  4263. };
  4264. BoundingSphere.Intersects = function (sphere0, sphere1) {
  4265. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  4266. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  4267. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  4268. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  4269. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  4270. return false;
  4271. return true;
  4272. };
  4273. return BoundingSphere;
  4274. })();
  4275. BABYLON.BoundingSphere = BoundingSphere;
  4276. })(BABYLON || (BABYLON = {}));
  4277. var BABYLON;
  4278. (function (BABYLON) {
  4279. var BoundingBox = (function () {
  4280. function BoundingBox(minimum, maximum) {
  4281. this.minimum = minimum;
  4282. this.maximum = maximum;
  4283. this.vectors = new Array();
  4284. this.vectorsWorld = new Array();
  4285. this.vectors.push(this.minimum.clone());
  4286. this.vectors.push(this.maximum.clone());
  4287. this.vectors.push(this.minimum.clone());
  4288. this.vectors[2].x = this.maximum.x;
  4289. this.vectors.push(this.minimum.clone());
  4290. this.vectors[3].y = this.maximum.y;
  4291. this.vectors.push(this.minimum.clone());
  4292. this.vectors[4].z = this.maximum.z;
  4293. this.vectors.push(this.maximum.clone());
  4294. this.vectors[5].z = this.minimum.z;
  4295. this.vectors.push(this.maximum.clone());
  4296. this.vectors[6].x = this.minimum.x;
  4297. this.vectors.push(this.maximum.clone());
  4298. this.vectors[7].y = this.minimum.y;
  4299. this.center = this.maximum.add(this.minimum).scale(0.5);
  4300. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  4301. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  4302. for (var index = 0; index < this.vectors.length; index++) {
  4303. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  4304. }
  4305. this.minimumWorld = BABYLON.Vector3.Zero();
  4306. this.maximumWorld = BABYLON.Vector3.Zero();
  4307. this._update(BABYLON.Matrix.Identity());
  4308. }
  4309. BoundingBox.prototype.getWorldMatrix = function () {
  4310. return this._worldMatrix;
  4311. };
  4312. BoundingBox.prototype._update = function (world) {
  4313. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  4314. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  4315. for (var index = 0; index < this.vectors.length; index++) {
  4316. var v = this.vectorsWorld[index];
  4317. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  4318. if (v.x < this.minimumWorld.x)
  4319. this.minimumWorld.x = v.x;
  4320. if (v.y < this.minimumWorld.y)
  4321. this.minimumWorld.y = v.y;
  4322. if (v.z < this.minimumWorld.z)
  4323. this.minimumWorld.z = v.z;
  4324. if (v.x > this.maximumWorld.x)
  4325. this.maximumWorld.x = v.x;
  4326. if (v.y > this.maximumWorld.y)
  4327. this.maximumWorld.y = v.y;
  4328. if (v.z > this.maximumWorld.z)
  4329. this.maximumWorld.z = v.z;
  4330. }
  4331. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  4332. this.center.scaleInPlace(0.5);
  4333. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  4334. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  4335. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  4336. this._worldMatrix = world;
  4337. };
  4338. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  4339. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  4340. };
  4341. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  4342. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  4343. };
  4344. BoundingBox.prototype.intersectsPoint = function (point) {
  4345. var delta = BABYLON.Engine.Epsilon;
  4346. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  4347. return false;
  4348. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  4349. return false;
  4350. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  4351. return false;
  4352. return true;
  4353. };
  4354. BoundingBox.prototype.intersectsSphere = function (sphere) {
  4355. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  4356. };
  4357. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  4358. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  4359. return false;
  4360. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  4361. return false;
  4362. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  4363. return false;
  4364. return true;
  4365. };
  4366. BoundingBox.Intersects = function (box0, box1) {
  4367. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  4368. return false;
  4369. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  4370. return false;
  4371. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  4372. return false;
  4373. return true;
  4374. };
  4375. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  4376. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  4377. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  4378. return (num <= (sphereRadius * sphereRadius));
  4379. };
  4380. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  4381. for (var p = 0; p < 6; p++) {
  4382. for (var i = 0; i < 8; i++) {
  4383. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  4384. return false;
  4385. }
  4386. }
  4387. }
  4388. return true;
  4389. };
  4390. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  4391. for (var p = 0; p < 6; p++) {
  4392. var inCount = 8;
  4393. for (var i = 0; i < 8; i++) {
  4394. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  4395. --inCount;
  4396. } else {
  4397. break;
  4398. }
  4399. }
  4400. if (inCount == 0)
  4401. return false;
  4402. }
  4403. return true;
  4404. };
  4405. return BoundingBox;
  4406. })();
  4407. BABYLON.BoundingBox = BoundingBox;
  4408. })(BABYLON || (BABYLON = {}));
  4409. var BABYLON;
  4410. (function (BABYLON) {
  4411. var computeBoxExtents = function (axis, box) {
  4412. var p = BABYLON.Vector3.Dot(box.center, axis);
  4413. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  4414. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  4415. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  4416. var r = r0 + r1 + r2;
  4417. return {
  4418. min: p - r,
  4419. max: p + r
  4420. };
  4421. };
  4422. var extentsOverlap = function (min0, max0, min1, max1) {
  4423. return !(min0 > max1 || min1 > max0);
  4424. };
  4425. var axisOverlap = function (axis, box0, box1) {
  4426. var result0 = computeBoxExtents(axis, box0);
  4427. var result1 = computeBoxExtents(axis, box1);
  4428. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  4429. };
  4430. var BoundingInfo = (function () {
  4431. function BoundingInfo(minimum, maximum) {
  4432. this.minimum = minimum;
  4433. this.maximum = maximum;
  4434. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  4435. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  4436. }
  4437. BoundingInfo.prototype._update = function (world) {
  4438. this.boundingBox._update(world);
  4439. this.boundingSphere._update(world);
  4440. };
  4441. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  4442. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  4443. return false;
  4444. return this.boundingBox.isInFrustum(frustumPlanes);
  4445. };
  4446. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  4447. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  4448. };
  4449. BoundingInfo.prototype._checkCollision = function (collider) {
  4450. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  4451. };
  4452. BoundingInfo.prototype.intersectsPoint = function (point) {
  4453. if (!this.boundingSphere.centerWorld) {
  4454. return false;
  4455. }
  4456. if (!this.boundingSphere.intersectsPoint(point)) {
  4457. return false;
  4458. }
  4459. if (!this.boundingBox.intersectsPoint(point)) {
  4460. return false;
  4461. }
  4462. return true;
  4463. };
  4464. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  4465. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  4466. return false;
  4467. }
  4468. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  4469. return false;
  4470. }
  4471. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  4472. return false;
  4473. }
  4474. if (!precise) {
  4475. return true;
  4476. }
  4477. var box0 = this.boundingBox;
  4478. var box1 = boundingInfo.boundingBox;
  4479. if (!axisOverlap(box0.directions[0], box0, box1))
  4480. return false;
  4481. if (!axisOverlap(box0.directions[1], box0, box1))
  4482. return false;
  4483. if (!axisOverlap(box0.directions[2], box0, box1))
  4484. return false;
  4485. if (!axisOverlap(box1.directions[0], box0, box1))
  4486. return false;
  4487. if (!axisOverlap(box1.directions[1], box0, box1))
  4488. return false;
  4489. if (!axisOverlap(box1.directions[2], box0, box1))
  4490. return false;
  4491. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  4492. return false;
  4493. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  4494. return false;
  4495. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  4496. return false;
  4497. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  4498. return false;
  4499. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  4500. return false;
  4501. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  4502. return false;
  4503. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  4504. return false;
  4505. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  4506. return false;
  4507. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  4508. return false;
  4509. return true;
  4510. };
  4511. return BoundingInfo;
  4512. })();
  4513. BABYLON.BoundingInfo = BoundingInfo;
  4514. })(BABYLON || (BABYLON = {}));
  4515. var __extends = this.__extends || function (d, b) {
  4516. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  4517. function __() { this.constructor = d; }
  4518. __.prototype = b.prototype;
  4519. d.prototype = new __();
  4520. };
  4521. var BABYLON;
  4522. (function (BABYLON) {
  4523. var Light = (function (_super) {
  4524. __extends(Light, _super);
  4525. function Light(name, scene) {
  4526. _super.call(this, name, scene);
  4527. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  4528. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  4529. this.intensity = 1.0;
  4530. this.range = Number.MAX_VALUE;
  4531. this.includedOnlyMeshes = new Array();
  4532. this.excludedMeshes = new Array();
  4533. this._excludedMeshesIds = new Array();
  4534. this._includedOnlyMeshesIds = new Array();
  4535. scene.lights.push(this);
  4536. }
  4537. Light.prototype.getShadowGenerator = function () {
  4538. return this._shadowGenerator;
  4539. };
  4540. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  4541. };
  4542. Light.prototype._getWorldMatrix = function () {
  4543. return BABYLON.Matrix.Identity();
  4544. };
  4545. Light.prototype.canAffectMesh = function (mesh) {
  4546. if (!mesh) {
  4547. return true;
  4548. }
  4549. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  4550. return false;
  4551. }
  4552. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  4553. return false;
  4554. }
  4555. return true;
  4556. };
  4557. Light.prototype.getWorldMatrix = function () {
  4558. this._currentRenderId = this.getScene().getRenderId();
  4559. var worldMatrix = this._getWorldMatrix();
  4560. if (this.parent && this.parent.getWorldMatrix) {
  4561. if (!this._parentedWorldMatrix) {
  4562. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  4563. }
  4564. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  4565. return this._parentedWorldMatrix;
  4566. }
  4567. return worldMatrix;
  4568. };
  4569. Light.prototype.dispose = function () {
  4570. if (this._shadowGenerator) {
  4571. this._shadowGenerator.dispose();
  4572. this._shadowGenerator = null;
  4573. }
  4574. var index = this.getScene().lights.indexOf(this);
  4575. this.getScene().lights.splice(index, 1);
  4576. };
  4577. return Light;
  4578. })(BABYLON.Node);
  4579. BABYLON.Light = Light;
  4580. })(BABYLON || (BABYLON = {}));
  4581. var __extends = this.__extends || function (d, b) {
  4582. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  4583. function __() { this.constructor = d; }
  4584. __.prototype = b.prototype;
  4585. d.prototype = new __();
  4586. };
  4587. var BABYLON;
  4588. (function (BABYLON) {
  4589. var PointLight = (function (_super) {
  4590. __extends(PointLight, _super);
  4591. function PointLight(name, position, scene) {
  4592. _super.call(this, name, scene);
  4593. this.position = position;
  4594. }
  4595. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  4596. if (this.parent && this.parent.getWorldMatrix) {
  4597. if (!this._transformedPosition) {
  4598. this._transformedPosition = BABYLON.Vector3.Zero();
  4599. }
  4600. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this._transformedPosition);
  4601. effect.setFloat4(positionUniformName, this._transformedPosition.x, this._transformedPosition.y, this._transformedPosition.z, 0);
  4602. return;
  4603. }
  4604. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  4605. };
  4606. PointLight.prototype.getShadowGenerator = function () {
  4607. return null;
  4608. };
  4609. PointLight.prototype._getWorldMatrix = function () {
  4610. if (!this._worldMatrix) {
  4611. this._worldMatrix = BABYLON.Matrix.Identity();
  4612. }
  4613. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  4614. return this._worldMatrix;
  4615. };
  4616. return PointLight;
  4617. })(BABYLON.Light);
  4618. BABYLON.PointLight = PointLight;
  4619. })(BABYLON || (BABYLON = {}));
  4620. var __extends = this.__extends || function (d, b) {
  4621. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  4622. function __() { this.constructor = d; }
  4623. __.prototype = b.prototype;
  4624. d.prototype = new __();
  4625. };
  4626. var BABYLON;
  4627. (function (BABYLON) {
  4628. var SpotLight = (function (_super) {
  4629. __extends(SpotLight, _super);
  4630. function SpotLight(name, position, direction, angle, exponent, scene) {
  4631. _super.call(this, name, scene);
  4632. this.position = position;
  4633. this.direction = direction;
  4634. this.angle = angle;
  4635. this.exponent = exponent;
  4636. }
  4637. SpotLight.prototype.setDirectionToTarget = function (target) {
  4638. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  4639. return this.direction;
  4640. };
  4641. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  4642. var normalizeDirection;
  4643. if (this.parent && this.parent.getWorldMatrix) {
  4644. if (!this._transformedDirection) {
  4645. this._transformedDirection = BABYLON.Vector3.Zero();
  4646. }
  4647. if (!this._transformedPosition) {
  4648. this._transformedPosition = BABYLON.Vector3.Zero();
  4649. }
  4650. var parentWorldMatrix = this.parent.getWorldMatrix();
  4651. BABYLON.Vector3.TransformCoordinatesToRef(this.position, parentWorldMatrix, this._transformedPosition);
  4652. BABYLON.Vector3.TransformNormalToRef(this.direction, parentWorldMatrix, this._transformedDirection);
  4653. effect.setFloat4(positionUniformName, this._transformedPosition.x, this._transformedPosition.y, this._transformedPosition.z, this.exponent);
  4654. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  4655. } else {
  4656. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  4657. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  4658. }
  4659. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  4660. };
  4661. SpotLight.prototype._getWorldMatrix = function () {
  4662. if (!this._worldMatrix) {
  4663. this._worldMatrix = BABYLON.Matrix.Identity();
  4664. }
  4665. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  4666. return this._worldMatrix;
  4667. };
  4668. return SpotLight;
  4669. })(BABYLON.Light);
  4670. BABYLON.SpotLight = SpotLight;
  4671. })(BABYLON || (BABYLON = {}));
  4672. var __extends = this.__extends || function (d, b) {
  4673. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  4674. function __() { this.constructor = d; }
  4675. __.prototype = b.prototype;
  4676. d.prototype = new __();
  4677. };
  4678. var BABYLON;
  4679. (function (BABYLON) {
  4680. var DirectionalLight = (function (_super) {
  4681. __extends(DirectionalLight, _super);
  4682. function DirectionalLight(name, direction, scene) {
  4683. _super.call(this, name, scene);
  4684. this.direction = direction;
  4685. this.position = direction.scale(-1);
  4686. }
  4687. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  4688. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  4689. return this.direction;
  4690. };
  4691. DirectionalLight.prototype._computeTransformedPosition = function () {
  4692. if (this.parent && this.parent.getWorldMatrix) {
  4693. if (!this._transformedPosition) {
  4694. this._transformedPosition = BABYLON.Vector3.Zero();
  4695. }
  4696. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this._transformedPosition);
  4697. return true;
  4698. }
  4699. return false;
  4700. };
  4701. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  4702. if (this.parent && this.parent.getWorldMatrix) {
  4703. if (!this._transformedDirection) {
  4704. this._transformedDirection = BABYLON.Vector3.Zero();
  4705. }
  4706. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  4707. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  4708. return;
  4709. }
  4710. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  4711. };
  4712. DirectionalLight.prototype._getWorldMatrix = function () {
  4713. if (!this._worldMatrix) {
  4714. this._worldMatrix = BABYLON.Matrix.Identity();
  4715. }
  4716. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  4717. return this._worldMatrix;
  4718. };
  4719. return DirectionalLight;
  4720. })(BABYLON.Light);
  4721. BABYLON.DirectionalLight = DirectionalLight;
  4722. })(BABYLON || (BABYLON = {}));
  4723. var BABYLON;
  4724. (function (BABYLON) {
  4725. var ShadowGenerator = (function () {
  4726. function ShadowGenerator(mapSize, light) {
  4727. var _this = this;
  4728. this.filter = ShadowGenerator.FILTER_VARIANCESHADOWMAP;
  4729. this._darkness = 0;
  4730. this._transparencyShadow = false;
  4731. this._viewMatrix = BABYLON.Matrix.Zero();
  4732. this._projectionMatrix = BABYLON.Matrix.Zero();
  4733. this._transformMatrix = BABYLON.Matrix.Zero();
  4734. this._worldViewProjection = BABYLON.Matrix.Zero();
  4735. this._light = light;
  4736. this._scene = light.getScene();
  4737. light._shadowGenerator = this;
  4738. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false);
  4739. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  4740. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  4741. this._shadowMap.renderParticles = false;
  4742. var renderSubMesh = function (subMesh) {
  4743. var mesh = subMesh.getRenderingMesh();
  4744. var scene = _this._scene;
  4745. var engine = scene.getEngine();
  4746. engine.setState(subMesh.getMaterial().backFaceCulling);
  4747. var batch = mesh._getInstancesRenderList(subMesh._id);
  4748. if (batch.mustReturn) {
  4749. return;
  4750. }
  4751. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  4752. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  4753. engine.enableEffect(_this._effect);
  4754. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  4755. var material = subMesh.getMaterial();
  4756. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  4757. if (material && material.needAlphaTesting()) {
  4758. var alphaTexture = material.getAlphaTestTexture();
  4759. _this._effect.setTexture("diffuseSampler", alphaTexture);
  4760. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  4761. }
  4762. var useBones = mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  4763. if (useBones) {
  4764. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  4765. }
  4766. if (hardwareInstancedRendering) {
  4767. mesh._renderWithInstances(subMesh, BABYLON.Material.TriangleFillMode, batch, _this._effect, engine);
  4768. } else {
  4769. if (batch.renderSelf[subMesh._id]) {
  4770. _this._effect.setMatrix("world", mesh.getWorldMatrix());
  4771. mesh._draw(subMesh, BABYLON.Material.TriangleFillMode);
  4772. }
  4773. if (batch.visibleInstances[subMesh._id]) {
  4774. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  4775. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  4776. _this._effect.setMatrix("world", instance.getWorldMatrix());
  4777. mesh._draw(subMesh, BABYLON.Material.TriangleFillMode);
  4778. }
  4779. }
  4780. }
  4781. } else {
  4782. _this._shadowMap.resetRefreshCounter();
  4783. }
  4784. };
  4785. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  4786. var index;
  4787. for (index = 0; index < opaqueSubMeshes.length; index++) {
  4788. renderSubMesh(opaqueSubMeshes.data[index]);
  4789. }
  4790. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  4791. renderSubMesh(alphaTestSubMeshes.data[index]);
  4792. }
  4793. if (_this._transparencyShadow) {
  4794. for (index = 0; index < transparentSubMeshes.length; index++) {
  4795. renderSubMesh(transparentSubMeshes.data[index]);
  4796. }
  4797. }
  4798. };
  4799. }
  4800. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  4801. get: function () {
  4802. return ShadowGenerator._FILTER_NONE;
  4803. },
  4804. enumerable: true,
  4805. configurable: true
  4806. });
  4807. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  4808. get: function () {
  4809. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  4810. },
  4811. enumerable: true,
  4812. configurable: true
  4813. });
  4814. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  4815. get: function () {
  4816. return ShadowGenerator._FILTER_POISSONSAMPLING;
  4817. },
  4818. enumerable: true,
  4819. configurable: true
  4820. });
  4821. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  4822. get: function () {
  4823. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP;
  4824. },
  4825. set: function (value) {
  4826. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  4827. },
  4828. enumerable: true,
  4829. configurable: true
  4830. });
  4831. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  4832. get: function () {
  4833. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  4834. },
  4835. set: function (value) {
  4836. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  4837. },
  4838. enumerable: true,
  4839. configurable: true
  4840. });
  4841. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  4842. var defines = [];
  4843. if (this.useVarianceShadowMap) {
  4844. defines.push("#define VSM");
  4845. }
  4846. var attribs = [BABYLON.VertexBuffer.PositionKind];
  4847. var mesh = subMesh.getMesh();
  4848. var material = subMesh.getMaterial();
  4849. if (material && material.needAlphaTesting()) {
  4850. defines.push("#define ALPHATEST");
  4851. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  4852. attribs.push(BABYLON.VertexBuffer.UVKind);
  4853. defines.push("#define UV1");
  4854. }
  4855. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  4856. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  4857. defines.push("#define UV2");
  4858. }
  4859. }
  4860. if (mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  4861. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  4862. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  4863. defines.push("#define BONES");
  4864. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  4865. }
  4866. if (useInstances) {
  4867. defines.push("#define INSTANCES");
  4868. attribs.push("world0");
  4869. attribs.push("world1");
  4870. attribs.push("world2");
  4871. attribs.push("world3");
  4872. }
  4873. var join = defines.join("\n");
  4874. if (this._cachedDefines != join) {
  4875. this._cachedDefines = join;
  4876. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  4877. }
  4878. return this._effect.isReady();
  4879. };
  4880. ShadowGenerator.prototype.getShadowMap = function () {
  4881. return this._shadowMap;
  4882. };
  4883. ShadowGenerator.prototype.getLight = function () {
  4884. return this._light;
  4885. };
  4886. ShadowGenerator.prototype.getTransformMatrix = function () {
  4887. var lightPosition = this._light.position;
  4888. var lightDirection = this._light.direction;
  4889. if (this._light._computeTransformedPosition()) {
  4890. lightPosition = this._light._transformedPosition;
  4891. }
  4892. if (!this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !lightDirection.equals(this._cachedDirection)) {
  4893. this._cachedPosition = lightPosition.clone();
  4894. this._cachedDirection = lightDirection.clone();
  4895. var activeCamera = this._scene.activeCamera;
  4896. BABYLON.Matrix.LookAtLHToRef(lightPosition, this._light.position.add(lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  4897. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2.0, 1.0, activeCamera.minZ, activeCamera.maxZ, this._projectionMatrix);
  4898. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  4899. }
  4900. return this._transformMatrix;
  4901. };
  4902. ShadowGenerator.prototype.getDarkness = function () {
  4903. return this._darkness;
  4904. };
  4905. ShadowGenerator.prototype.setDarkness = function (darkness) {
  4906. if (darkness >= 1.0)
  4907. this._darkness = 1.0;
  4908. else if (darkness <= 0.0)
  4909. this._darkness = 0.0;
  4910. else
  4911. this._darkness = darkness;
  4912. };
  4913. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  4914. this._transparencyShadow = hasShadow;
  4915. };
  4916. ShadowGenerator.prototype.dispose = function () {
  4917. this._shadowMap.dispose();
  4918. };
  4919. ShadowGenerator._FILTER_NONE = 0;
  4920. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  4921. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  4922. return ShadowGenerator;
  4923. })();
  4924. BABYLON.ShadowGenerator = ShadowGenerator;
  4925. })(BABYLON || (BABYLON = {}));
  4926. var __extends = this.__extends || function (d, b) {
  4927. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  4928. function __() { this.constructor = d; }
  4929. __.prototype = b.prototype;
  4930. d.prototype = new __();
  4931. };
  4932. var BABYLON;
  4933. (function (BABYLON) {
  4934. var HemisphericLight = (function (_super) {
  4935. __extends(HemisphericLight, _super);
  4936. function HemisphericLight(name, direction, scene) {
  4937. _super.call(this, name, scene);
  4938. this.direction = direction;
  4939. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  4940. }
  4941. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  4942. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  4943. return this.direction;
  4944. };
  4945. HemisphericLight.prototype.getShadowGenerator = function () {
  4946. return null;
  4947. };
  4948. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  4949. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  4950. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  4951. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  4952. };
  4953. HemisphericLight.prototype._getWorldMatrix = function () {
  4954. if (!this._worldMatrix) {
  4955. this._worldMatrix = BABYLON.Matrix.Identity();
  4956. }
  4957. return this._worldMatrix;
  4958. };
  4959. return HemisphericLight;
  4960. })(BABYLON.Light);
  4961. BABYLON.HemisphericLight = HemisphericLight;
  4962. })(BABYLON || (BABYLON = {}));
  4963. var BABYLON;
  4964. (function (BABYLON) {
  4965. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  4966. if (boxMin.x > sphereCenter.x + sphereRadius)
  4967. return false;
  4968. if (sphereCenter.x - sphereRadius > boxMax.x)
  4969. return false;
  4970. if (boxMin.y > sphereCenter.y + sphereRadius)
  4971. return false;
  4972. if (sphereCenter.y - sphereRadius > boxMax.y)
  4973. return false;
  4974. if (boxMin.z > sphereCenter.z + sphereRadius)
  4975. return false;
  4976. if (sphereCenter.z - sphereRadius > boxMax.z)
  4977. return false;
  4978. return true;
  4979. };
  4980. var getLowestRoot = function (a, b, c, maxR) {
  4981. var determinant = b * b - 4.0 * a * c;
  4982. var result = { root: 0, found: false };
  4983. if (determinant < 0)
  4984. return result;
  4985. var sqrtD = Math.sqrt(determinant);
  4986. var r1 = (-b - sqrtD) / (2.0 * a);
  4987. var r2 = (-b + sqrtD) / (2.0 * a);
  4988. if (r1 > r2) {
  4989. var temp = r2;
  4990. r2 = r1;
  4991. r1 = temp;
  4992. }
  4993. if (r1 > 0 && r1 < maxR) {
  4994. result.root = r1;
  4995. result.found = true;
  4996. return result;
  4997. }
  4998. if (r2 > 0 && r2 < maxR) {
  4999. result.root = r2;
  5000. result.found = true;
  5001. return result;
  5002. }
  5003. return result;
  5004. };
  5005. var Collider = (function () {
  5006. function Collider() {
  5007. this.radius = new BABYLON.Vector3(1, 1, 1);
  5008. this.retry = 0;
  5009. this.basePointWorld = BABYLON.Vector3.Zero();
  5010. this.velocityWorld = BABYLON.Vector3.Zero();
  5011. this.normalizedVelocity = BABYLON.Vector3.Zero();
  5012. this._collisionPoint = BABYLON.Vector3.Zero();
  5013. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  5014. this._tempVector = BABYLON.Vector3.Zero();
  5015. this._tempVector2 = BABYLON.Vector3.Zero();
  5016. this._tempVector3 = BABYLON.Vector3.Zero();
  5017. this._tempVector4 = BABYLON.Vector3.Zero();
  5018. this._edge = BABYLON.Vector3.Zero();
  5019. this._baseToVertex = BABYLON.Vector3.Zero();
  5020. this._destinationPoint = BABYLON.Vector3.Zero();
  5021. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  5022. this._displacementVector = BABYLON.Vector3.Zero();
  5023. }
  5024. Collider.prototype._initialize = function (source, dir, e) {
  5025. this.velocity = dir;
  5026. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  5027. this.basePoint = source;
  5028. source.multiplyToRef(this.radius, this.basePointWorld);
  5029. dir.multiplyToRef(this.radius, this.velocityWorld);
  5030. this.velocityWorldLength = this.velocityWorld.length();
  5031. this.epsilon = e;
  5032. this.collisionFound = false;
  5033. };
  5034. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  5035. pa.subtractToRef(point, this._tempVector);
  5036. pb.subtractToRef(point, this._tempVector2);
  5037. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  5038. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  5039. if (d < 0)
  5040. return false;
  5041. pc.subtractToRef(point, this._tempVector3);
  5042. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  5043. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  5044. if (d < 0)
  5045. return false;
  5046. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  5047. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  5048. return d >= 0;
  5049. };
  5050. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  5051. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  5052. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  5053. if (distance > this.velocityWorldLength + max + sphereRadius) {
  5054. return false;
  5055. }
  5056. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  5057. return false;
  5058. return true;
  5059. };
  5060. Collider.prototype._testTriangle = function (faceIndex, subMesh, p1, p2, p3) {
  5061. var t0;
  5062. var embeddedInPlane = false;
  5063. if (!subMesh._trianglePlanes) {
  5064. subMesh._trianglePlanes = [];
  5065. }
  5066. if (!subMesh._trianglePlanes[faceIndex]) {
  5067. subMesh._trianglePlanes[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  5068. subMesh._trianglePlanes[faceIndex].copyFromPoints(p1, p2, p3);
  5069. }
  5070. var trianglePlane = subMesh._trianglePlanes[faceIndex];
  5071. if ((!subMesh.getMaterial()) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  5072. return;
  5073. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  5074. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  5075. if (normalDotVelocity == 0) {
  5076. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  5077. return;
  5078. embeddedInPlane = true;
  5079. t0 = 0;
  5080. } else {
  5081. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  5082. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  5083. if (t0 > t1) {
  5084. var temp = t1;
  5085. t1 = t0;
  5086. t0 = temp;
  5087. }
  5088. if (t0 > 1.0 || t1 < 0.0)
  5089. return;
  5090. if (t0 < 0)
  5091. t0 = 0;
  5092. if (t0 > 1.0)
  5093. t0 = 1.0;
  5094. }
  5095. this._collisionPoint.copyFromFloats(0, 0, 0);
  5096. var found = false;
  5097. var t = 1.0;
  5098. if (!embeddedInPlane) {
  5099. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  5100. this.velocity.scaleToRef(t0, this._tempVector);
  5101. this._planeIntersectionPoint.addInPlace(this._tempVector);
  5102. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  5103. found = true;
  5104. t = t0;
  5105. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  5106. }
  5107. }
  5108. if (!found) {
  5109. var velocitySquaredLength = this.velocity.lengthSquared();
  5110. var a = velocitySquaredLength;
  5111. this.basePoint.subtractToRef(p1, this._tempVector);
  5112. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  5113. var c = this._tempVector.lengthSquared() - 1.0;
  5114. var lowestRoot = getLowestRoot(a, b, c, t);
  5115. if (lowestRoot.found) {
  5116. t = lowestRoot.root;
  5117. found = true;
  5118. this._collisionPoint.copyFrom(p1);
  5119. }
  5120. this.basePoint.subtractToRef(p2, this._tempVector);
  5121. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  5122. c = this._tempVector.lengthSquared() - 1.0;
  5123. lowestRoot = getLowestRoot(a, b, c, t);
  5124. if (lowestRoot.found) {
  5125. t = lowestRoot.root;
  5126. found = true;
  5127. this._collisionPoint.copyFrom(p2);
  5128. }
  5129. this.basePoint.subtractToRef(p3, this._tempVector);
  5130. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  5131. c = this._tempVector.lengthSquared() - 1.0;
  5132. lowestRoot = getLowestRoot(a, b, c, t);
  5133. if (lowestRoot.found) {
  5134. t = lowestRoot.root;
  5135. found = true;
  5136. this._collisionPoint.copyFrom(p3);
  5137. }
  5138. p2.subtractToRef(p1, this._edge);
  5139. p1.subtractToRef(this.basePoint, this._baseToVertex);
  5140. var edgeSquaredLength = this._edge.lengthSquared();
  5141. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  5142. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  5143. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  5144. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  5145. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  5146. lowestRoot = getLowestRoot(a, b, c, t);
  5147. if (lowestRoot.found) {
  5148. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  5149. if (f >= 0.0 && f <= 1.0) {
  5150. t = lowestRoot.root;
  5151. found = true;
  5152. this._edge.scaleInPlace(f);
  5153. p1.addToRef(this._edge, this._collisionPoint);
  5154. }
  5155. }
  5156. p3.subtractToRef(p2, this._edge);
  5157. p2.subtractToRef(this.basePoint, this._baseToVertex);
  5158. edgeSquaredLength = this._edge.lengthSquared();
  5159. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  5160. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  5161. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  5162. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  5163. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  5164. lowestRoot = getLowestRoot(a, b, c, t);
  5165. if (lowestRoot.found) {
  5166. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  5167. if (f >= 0.0 && f <= 1.0) {
  5168. t = lowestRoot.root;
  5169. found = true;
  5170. this._edge.scaleInPlace(f);
  5171. p2.addToRef(this._edge, this._collisionPoint);
  5172. }
  5173. }
  5174. p1.subtractToRef(p3, this._edge);
  5175. p3.subtractToRef(this.basePoint, this._baseToVertex);
  5176. edgeSquaredLength = this._edge.lengthSquared();
  5177. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  5178. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  5179. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  5180. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  5181. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  5182. lowestRoot = getLowestRoot(a, b, c, t);
  5183. if (lowestRoot.found) {
  5184. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  5185. if (f >= 0.0 && f <= 1.0) {
  5186. t = lowestRoot.root;
  5187. found = true;
  5188. this._edge.scaleInPlace(f);
  5189. p3.addToRef(this._edge, this._collisionPoint);
  5190. }
  5191. }
  5192. }
  5193. if (found) {
  5194. var distToCollision = t * this.velocity.length();
  5195. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  5196. if (!this.intersectionPoint) {
  5197. this.intersectionPoint = this._collisionPoint.clone();
  5198. } else {
  5199. this.intersectionPoint.copyFrom(this._collisionPoint);
  5200. }
  5201. this.nearestDistance = distToCollision;
  5202. this.collisionFound = true;
  5203. this.collidedMesh = subMesh.getMesh();
  5204. }
  5205. }
  5206. };
  5207. Collider.prototype._collide = function (subMesh, pts, indices, indexStart, indexEnd, decal) {
  5208. for (var i = indexStart; i < indexEnd; i += 3) {
  5209. var p1 = pts[indices[i] - decal];
  5210. var p2 = pts[indices[i + 1] - decal];
  5211. var p3 = pts[indices[i + 2] - decal];
  5212. this._testTriangle(i, subMesh, p3, p2, p1);
  5213. }
  5214. };
  5215. Collider.prototype._getResponse = function (pos, vel) {
  5216. pos.addToRef(vel, this._destinationPoint);
  5217. vel.scaleInPlace((this.nearestDistance / vel.length()));
  5218. this.basePoint.addToRef(vel, pos);
  5219. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  5220. this._slidePlaneNormal.normalize();
  5221. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  5222. pos.addInPlace(this._displacementVector);
  5223. this.intersectionPoint.addInPlace(this._displacementVector);
  5224. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  5225. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  5226. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  5227. };
  5228. return Collider;
  5229. })();
  5230. BABYLON.Collider = Collider;
  5231. })(BABYLON || (BABYLON = {}));
  5232. var __extends = this.__extends || function (d, b) {
  5233. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  5234. function __() { this.constructor = d; }
  5235. __.prototype = b.prototype;
  5236. d.prototype = new __();
  5237. };
  5238. var BABYLON;
  5239. (function (BABYLON) {
  5240. var Camera = (function (_super) {
  5241. __extends(Camera, _super);
  5242. function Camera(name, position, scene) {
  5243. _super.call(this, name, scene);
  5244. this.position = position;
  5245. this.upVector = BABYLON.Vector3.Up();
  5246. this.orthoLeft = null;
  5247. this.orthoRight = null;
  5248. this.orthoBottom = null;
  5249. this.orthoTop = null;
  5250. this.fov = 0.8;
  5251. this.minZ = 1.0;
  5252. this.maxZ = 10000.0;
  5253. this.inertia = 0.9;
  5254. this.mode = Camera.PERSPECTIVE_CAMERA;
  5255. this.isIntermediate = false;
  5256. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  5257. this.subCameras = [];
  5258. this.layerMask = 0xFFFFFFFF;
  5259. this._computedViewMatrix = BABYLON.Matrix.Identity();
  5260. this._projectionMatrix = new BABYLON.Matrix();
  5261. this._postProcesses = new Array();
  5262. this._postProcessesTakenIndices = [];
  5263. scene.cameras.push(this);
  5264. if (!scene.activeCamera) {
  5265. scene.activeCamera = this;
  5266. }
  5267. }
  5268. Camera.prototype._initCache = function () {
  5269. _super.prototype._initCache.call(this);
  5270. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5271. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5272. this._cache.mode = undefined;
  5273. this._cache.minZ = undefined;
  5274. this._cache.maxZ = undefined;
  5275. this._cache.fov = undefined;
  5276. this._cache.aspectRatio = undefined;
  5277. this._cache.orthoLeft = undefined;
  5278. this._cache.orthoRight = undefined;
  5279. this._cache.orthoBottom = undefined;
  5280. this._cache.orthoTop = undefined;
  5281. this._cache.renderWidth = undefined;
  5282. this._cache.renderHeight = undefined;
  5283. };
  5284. Camera.prototype._updateCache = function (ignoreParentClass) {
  5285. if (!ignoreParentClass) {
  5286. _super.prototype._updateCache.call(this);
  5287. }
  5288. var engine = this.getEngine();
  5289. this._cache.position.copyFrom(this.position);
  5290. this._cache.upVector.copyFrom(this.upVector);
  5291. this._cache.mode = this.mode;
  5292. this._cache.minZ = this.minZ;
  5293. this._cache.maxZ = this.maxZ;
  5294. this._cache.fov = this.fov;
  5295. this._cache.aspectRatio = engine.getAspectRatio(this);
  5296. this._cache.orthoLeft = this.orthoLeft;
  5297. this._cache.orthoRight = this.orthoRight;
  5298. this._cache.orthoBottom = this.orthoBottom;
  5299. this._cache.orthoTop = this.orthoTop;
  5300. this._cache.renderWidth = engine.getRenderWidth();
  5301. this._cache.renderHeight = engine.getRenderHeight();
  5302. };
  5303. Camera.prototype._updateFromScene = function () {
  5304. this.updateCache();
  5305. this._update();
  5306. };
  5307. Camera.prototype._isSynchronized = function () {
  5308. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  5309. };
  5310. Camera.prototype._isSynchronizedViewMatrix = function () {
  5311. if (!_super.prototype._isSynchronized.call(this))
  5312. return false;
  5313. return this._cache.position.equals(this.position) && this._cache.upVector.equals(this.upVector) && this.isSynchronizedWithParent();
  5314. };
  5315. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  5316. var check = this._cache.mode === this.mode && this._cache.minZ === this.minZ && this._cache.maxZ === this.maxZ;
  5317. if (!check) {
  5318. return false;
  5319. }
  5320. var engine = this.getEngine();
  5321. if (this.mode === BABYLON.Camera.PERSPECTIVE_CAMERA) {
  5322. check = this._cache.fov === this.fov && this._cache.aspectRatio === engine.getAspectRatio(this);
  5323. } else {
  5324. 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();
  5325. }
  5326. return check;
  5327. };
  5328. Camera.prototype.attachControl = function (element) {
  5329. };
  5330. Camera.prototype.detachControl = function (element) {
  5331. };
  5332. Camera.prototype._update = function () {
  5333. };
  5334. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  5335. if (typeof insertAt === "undefined") { insertAt = null; }
  5336. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  5337. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  5338. return 0;
  5339. }
  5340. if (insertAt == null || insertAt < 0) {
  5341. this._postProcesses.push(postProcess);
  5342. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  5343. return this._postProcesses.length - 1;
  5344. }
  5345. var add = 0;
  5346. if (this._postProcesses[insertAt]) {
  5347. var start = this._postProcesses.length - 1;
  5348. for (var i = start; i >= insertAt + 1; --i) {
  5349. this._postProcesses[i + 1] = this._postProcesses[i];
  5350. }
  5351. add = 1;
  5352. }
  5353. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  5354. if (this._postProcessesTakenIndices[i] < insertAt) {
  5355. continue;
  5356. }
  5357. start = this._postProcessesTakenIndices.length - 1;
  5358. for (var j = start; j >= i; --j) {
  5359. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  5360. }
  5361. this._postProcessesTakenIndices[i] = insertAt;
  5362. break;
  5363. }
  5364. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) == -1) {
  5365. this._postProcessesTakenIndices.push(insertAt);
  5366. }
  5367. var result = insertAt + add;
  5368. this._postProcesses[result] = postProcess;
  5369. return result;
  5370. };
  5371. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  5372. if (typeof atIndices === "undefined") { atIndices = null; }
  5373. var result = [];
  5374. if (!atIndices) {
  5375. var length = this._postProcesses.length;
  5376. for (var i = 0; i < length; i++) {
  5377. if (this._postProcesses[i] !== postProcess) {
  5378. continue;
  5379. }
  5380. delete this._postProcesses[i];
  5381. var index = this._postProcessesTakenIndices.indexOf(i);
  5382. this._postProcessesTakenIndices.splice(index, 1);
  5383. }
  5384. } else {
  5385. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  5386. for (i = 0; i < atIndices.length; i++) {
  5387. var foundPostProcess = this._postProcesses[atIndices[i]];
  5388. if (foundPostProcess !== postProcess) {
  5389. result.push(i);
  5390. continue;
  5391. }
  5392. delete this._postProcesses[atIndices[i]];
  5393. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  5394. this._postProcessesTakenIndices.splice(index, 1);
  5395. }
  5396. }
  5397. return result;
  5398. };
  5399. Camera.prototype.getWorldMatrix = function () {
  5400. if (!this._worldMatrix) {
  5401. this._worldMatrix = BABYLON.Matrix.Identity();
  5402. }
  5403. var viewMatrix = this.getViewMatrix();
  5404. viewMatrix.invertToRef(this._worldMatrix);
  5405. return this._worldMatrix;
  5406. };
  5407. Camera.prototype._getViewMatrix = function () {
  5408. return BABYLON.Matrix.Identity();
  5409. };
  5410. Camera.prototype.getViewMatrix = function () {
  5411. this._computedViewMatrix = this._computeViewMatrix();
  5412. if (!this.parent || !this.parent.getWorldMatrix || this.isSynchronized()) {
  5413. return this._computedViewMatrix;
  5414. }
  5415. if (!this._worldMatrix) {
  5416. this._worldMatrix = BABYLON.Matrix.Identity();
  5417. }
  5418. this._computedViewMatrix.invertToRef(this._worldMatrix);
  5419. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  5420. this._computedViewMatrix.invert();
  5421. this._currentRenderId = this.getScene().getRenderId();
  5422. return this._computedViewMatrix;
  5423. };
  5424. Camera.prototype._computeViewMatrix = function (force) {
  5425. if (!force && this._isSynchronizedViewMatrix()) {
  5426. return this._computedViewMatrix;
  5427. }
  5428. this._computedViewMatrix = this._getViewMatrix();
  5429. if (!this.parent || !this.parent.getWorldMatrix) {
  5430. this._currentRenderId = this.getScene().getRenderId();
  5431. }
  5432. return this._computedViewMatrix;
  5433. };
  5434. Camera.prototype.getProjectionMatrix = function (force) {
  5435. if (!force && this._isSynchronizedProjectionMatrix()) {
  5436. return this._projectionMatrix;
  5437. }
  5438. var engine = this.getEngine();
  5439. if (this.mode === BABYLON.Camera.PERSPECTIVE_CAMERA) {
  5440. if (this.minZ <= 0) {
  5441. this.minZ = 0.1;
  5442. }
  5443. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix);
  5444. return this._projectionMatrix;
  5445. }
  5446. var halfWidth = engine.getRenderWidth() / 2.0;
  5447. var halfHeight = engine.getRenderHeight() / 2.0;
  5448. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  5449. return this._projectionMatrix;
  5450. };
  5451. Camera.prototype.dispose = function () {
  5452. var index = this.getScene().cameras.indexOf(this);
  5453. this.getScene().cameras.splice(index, 1);
  5454. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  5455. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  5456. }
  5457. };
  5458. Camera.PERSPECTIVE_CAMERA = 0;
  5459. Camera.ORTHOGRAPHIC_CAMERA = 1;
  5460. return Camera;
  5461. })(BABYLON.Node);
  5462. BABYLON.Camera = Camera;
  5463. })(BABYLON || (BABYLON = {}));
  5464. var __extends = this.__extends || function (d, b) {
  5465. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  5466. function __() { this.constructor = d; }
  5467. __.prototype = b.prototype;
  5468. d.prototype = new __();
  5469. };
  5470. var BABYLON;
  5471. (function (BABYLON) {
  5472. var TargetCamera = (function (_super) {
  5473. __extends(TargetCamera, _super);
  5474. function TargetCamera(name, position, scene) {
  5475. _super.call(this, name, position, scene);
  5476. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  5477. this.cameraRotation = new BABYLON.Vector2(0, 0);
  5478. this.rotation = new BABYLON.Vector3(0, 0, 0);
  5479. this.speed = 2.0;
  5480. this.noRotationConstraint = false;
  5481. this.lockedTarget = null;
  5482. this._currentTarget = BABYLON.Vector3.Zero();
  5483. this._viewMatrix = BABYLON.Matrix.Zero();
  5484. this._camMatrix = BABYLON.Matrix.Zero();
  5485. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  5486. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  5487. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  5488. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  5489. this._lookAtTemp = BABYLON.Matrix.Zero();
  5490. this._tempMatrix = BABYLON.Matrix.Zero();
  5491. }
  5492. TargetCamera.prototype._getLockedTargetPosition = function () {
  5493. if (!this.lockedTarget) {
  5494. return null;
  5495. }
  5496. return this.lockedTarget.position || this.lockedTarget;
  5497. };
  5498. TargetCamera.prototype._initCache = function () {
  5499. _super.prototype._initCache.call(this);
  5500. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5501. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5502. };
  5503. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  5504. if (!ignoreParentClass) {
  5505. _super.prototype._updateCache.call(this);
  5506. }
  5507. var lockedTargetPosition = this._getLockedTargetPosition();
  5508. if (!lockedTargetPosition) {
  5509. this._cache.lockedTarget = null;
  5510. } else {
  5511. if (!this._cache.lockedTarget) {
  5512. this._cache.lockedTarget = lockedTargetPosition.clone();
  5513. } else {
  5514. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  5515. }
  5516. }
  5517. this._cache.rotation.copyFrom(this.rotation);
  5518. };
  5519. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  5520. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  5521. return false;
  5522. }
  5523. var lockedTargetPosition = this._getLockedTargetPosition();
  5524. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition) && this._cache.rotation.equals(this.rotation);
  5525. };
  5526. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  5527. return this.speed * ((BABYLON.Tools.GetDeltaTime() / (BABYLON.Tools.GetFps() * 10.0)));
  5528. };
  5529. TargetCamera.prototype.setTarget = function (target) {
  5530. this.upVector.normalize();
  5531. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  5532. this._camMatrix.invert();
  5533. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  5534. var vDir = target.subtract(this.position);
  5535. if (vDir.x >= 0.0) {
  5536. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  5537. } else {
  5538. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  5539. }
  5540. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  5541. if (isNaN(this.rotation.x)) {
  5542. this.rotation.x = 0;
  5543. }
  5544. if (isNaN(this.rotation.y)) {
  5545. this.rotation.y = 0;
  5546. }
  5547. if (isNaN(this.rotation.z)) {
  5548. this.rotation.z = 0;
  5549. }
  5550. };
  5551. TargetCamera.prototype.getTarget = function () {
  5552. return this._currentTarget;
  5553. };
  5554. TargetCamera.prototype._decideIfNeedsToMove = function () {
  5555. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  5556. };
  5557. TargetCamera.prototype._updatePosition = function () {
  5558. this.position.addInPlace(this.cameraDirection);
  5559. };
  5560. TargetCamera.prototype._update = function () {
  5561. var needToMove = this._decideIfNeedsToMove();
  5562. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  5563. if (needToMove) {
  5564. this._updatePosition();
  5565. }
  5566. if (needToRotate) {
  5567. this.rotation.x += this.cameraRotation.x;
  5568. this.rotation.y += this.cameraRotation.y;
  5569. if (!this.noRotationConstraint) {
  5570. var limit = (Math.PI / 2) * 0.95;
  5571. if (this.rotation.x > limit)
  5572. this.rotation.x = limit;
  5573. if (this.rotation.x < -limit)
  5574. this.rotation.x = -limit;
  5575. }
  5576. }
  5577. if (needToMove) {
  5578. if (Math.abs(this.cameraDirection.x) < BABYLON.Engine.Epsilon) {
  5579. this.cameraDirection.x = 0;
  5580. }
  5581. if (Math.abs(this.cameraDirection.y) < BABYLON.Engine.Epsilon) {
  5582. this.cameraDirection.y = 0;
  5583. }
  5584. if (Math.abs(this.cameraDirection.z) < BABYLON.Engine.Epsilon) {
  5585. this.cameraDirection.z = 0;
  5586. }
  5587. this.cameraDirection.scaleInPlace(this.inertia);
  5588. }
  5589. if (needToRotate) {
  5590. if (Math.abs(this.cameraRotation.x) < BABYLON.Engine.Epsilon) {
  5591. this.cameraRotation.x = 0;
  5592. }
  5593. if (Math.abs(this.cameraRotation.y) < BABYLON.Engine.Epsilon) {
  5594. this.cameraRotation.y = 0;
  5595. }
  5596. this.cameraRotation.scaleInPlace(this.inertia);
  5597. }
  5598. };
  5599. TargetCamera.prototype._getViewMatrix = function () {
  5600. if (!this.lockedTarget) {
  5601. if (this.upVector.x != 0 || this.upVector.y != 1.0 || this.upVector.z != 0) {
  5602. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  5603. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  5604. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  5605. this._lookAtTemp.invert();
  5606. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  5607. } else {
  5608. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  5609. }
  5610. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  5611. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  5612. } else {
  5613. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  5614. }
  5615. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  5616. return this._viewMatrix;
  5617. };
  5618. return TargetCamera;
  5619. })(BABYLON.Camera);
  5620. BABYLON.TargetCamera = TargetCamera;
  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 FollowCamera = (function (_super) {
  5631. __extends(FollowCamera, _super);
  5632. function FollowCamera(name, position, scene) {
  5633. _super.call(this, name, position, scene);
  5634. this.radius = 12;
  5635. this.rotationOffset = 0;
  5636. this.heightOffset = 4;
  5637. this.cameraAcceleration = 0.05;
  5638. this.maxCameraSpeed = 20;
  5639. }
  5640. FollowCamera.prototype.getRadians = function (degrees) {
  5641. return degrees * Math.PI / 180;
  5642. };
  5643. FollowCamera.prototype.follow = function (cameraTarget) {
  5644. if (!cameraTarget)
  5645. return;
  5646. var radians = this.getRadians(this.rotationOffset) + cameraTarget.rotation.y;
  5647. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  5648. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  5649. var dx = targetX - this.position.x;
  5650. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  5651. var dz = (targetZ) - this.position.z;
  5652. var vx = dx * this.cameraAcceleration * 2;
  5653. var vy = dy * this.cameraAcceleration;
  5654. var vz = dz * this.cameraAcceleration * 2;
  5655. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  5656. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  5657. }
  5658. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  5659. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  5660. }
  5661. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  5662. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  5663. }
  5664. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  5665. this.setTarget(cameraTarget.position);
  5666. };
  5667. FollowCamera.prototype._update = function () {
  5668. _super.prototype._update.call(this);
  5669. this.follow(this.target);
  5670. };
  5671. return FollowCamera;
  5672. })(BABYLON.TargetCamera);
  5673. BABYLON.FollowCamera = FollowCamera;
  5674. })(BABYLON || (BABYLON = {}));
  5675. var __extends = this.__extends || function (d, b) {
  5676. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  5677. function __() { this.constructor = d; }
  5678. __.prototype = b.prototype;
  5679. d.prototype = new __();
  5680. };
  5681. var BABYLON;
  5682. (function (BABYLON) {
  5683. var FreeCamera = (function (_super) {
  5684. __extends(FreeCamera, _super);
  5685. function FreeCamera(name, position, scene) {
  5686. _super.call(this, name, position, scene);
  5687. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  5688. this.keysUp = [38];
  5689. this.keysDown = [40];
  5690. this.keysLeft = [37];
  5691. this.keysRight = [39];
  5692. this.checkCollisions = false;
  5693. this.applyGravity = false;
  5694. this.angularSensibility = 2000.0;
  5695. this._keys = [];
  5696. this._collider = new BABYLON.Collider();
  5697. this._needMoveForGravity = true;
  5698. this._oldPosition = BABYLON.Vector3.Zero();
  5699. this._diffPosition = BABYLON.Vector3.Zero();
  5700. this._newPosition = BABYLON.Vector3.Zero();
  5701. }
  5702. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  5703. var _this = this;
  5704. var previousPosition;
  5705. var engine = this.getEngine();
  5706. if (this._attachedElement) {
  5707. return;
  5708. }
  5709. this._attachedElement = element;
  5710. if (this._onMouseDown === undefined) {
  5711. this._onMouseDown = function (evt) {
  5712. previousPosition = {
  5713. x: evt.clientX,
  5714. y: evt.clientY
  5715. };
  5716. if (!noPreventDefault) {
  5717. evt.preventDefault();
  5718. }
  5719. };
  5720. this._onMouseUp = function (evt) {
  5721. previousPosition = null;
  5722. if (!noPreventDefault) {
  5723. evt.preventDefault();
  5724. }
  5725. };
  5726. this._onMouseOut = function (evt) {
  5727. previousPosition = null;
  5728. _this._keys = [];
  5729. if (!noPreventDefault) {
  5730. evt.preventDefault();
  5731. }
  5732. };
  5733. this._onMouseMove = function (evt) {
  5734. if (!previousPosition && !engine.isPointerLock) {
  5735. return;
  5736. }
  5737. var offsetX;
  5738. var offsetY;
  5739. if (!engine.isPointerLock) {
  5740. offsetX = evt.clientX - previousPosition.x;
  5741. offsetY = evt.clientY - previousPosition.y;
  5742. } else {
  5743. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  5744. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  5745. }
  5746. _this.cameraRotation.y += offsetX / _this.angularSensibility;
  5747. _this.cameraRotation.x += offsetY / _this.angularSensibility;
  5748. previousPosition = {
  5749. x: evt.clientX,
  5750. y: evt.clientY
  5751. };
  5752. if (!noPreventDefault) {
  5753. evt.preventDefault();
  5754. }
  5755. };
  5756. this._onKeyDown = function (evt) {
  5757. 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) {
  5758. var index = _this._keys.indexOf(evt.keyCode);
  5759. if (index === -1) {
  5760. _this._keys.push(evt.keyCode);
  5761. }
  5762. if (!noPreventDefault) {
  5763. evt.preventDefault();
  5764. }
  5765. }
  5766. };
  5767. this._onKeyUp = function (evt) {
  5768. 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) {
  5769. var index = _this._keys.indexOf(evt.keyCode);
  5770. if (index >= 0) {
  5771. _this._keys.splice(index, 1);
  5772. }
  5773. if (!noPreventDefault) {
  5774. evt.preventDefault();
  5775. }
  5776. }
  5777. };
  5778. this._onLostFocus = function () {
  5779. _this._keys = [];
  5780. };
  5781. this._reset = function () {
  5782. _this._keys = [];
  5783. previousPosition = null;
  5784. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  5785. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  5786. };
  5787. }
  5788. element.addEventListener("mousedown", this._onMouseDown, false);
  5789. element.addEventListener("mouseup", this._onMouseUp, false);
  5790. element.addEventListener("mouseout", this._onMouseOut, false);
  5791. element.addEventListener("mousemove", this._onMouseMove, false);
  5792. BABYLON.Tools.RegisterTopRootEvents([
  5793. { name: "keydown", handler: this._onKeyDown },
  5794. { name: "keyup", handler: this._onKeyUp },
  5795. { name: "blur", handler: this._onLostFocus }
  5796. ]);
  5797. };
  5798. FreeCamera.prototype.detachControl = function (element) {
  5799. if (this._attachedElement != element) {
  5800. return;
  5801. }
  5802. element.removeEventListener("mousedown", this._onMouseDown);
  5803. element.removeEventListener("mouseup", this._onMouseUp);
  5804. element.removeEventListener("mouseout", this._onMouseOut);
  5805. element.removeEventListener("mousemove", this._onMouseMove);
  5806. BABYLON.Tools.UnregisterTopRootEvents([
  5807. { name: "keydown", handler: this._onKeyDown },
  5808. { name: "keyup", handler: this._onKeyUp },
  5809. { name: "blur", handler: this._onLostFocus }
  5810. ]);
  5811. this._attachedElement = null;
  5812. if (this._reset) {
  5813. this._reset();
  5814. }
  5815. };
  5816. FreeCamera.prototype._collideWithWorld = function (velocity) {
  5817. var globalPosition;
  5818. if (this.parent) {
  5819. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  5820. } else {
  5821. globalPosition = this.position;
  5822. }
  5823. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  5824. this._collider.radius = this.ellipsoid;
  5825. this.getScene()._getNewPosition(this._oldPosition, velocity, this._collider, 3, this._newPosition);
  5826. this._newPosition.subtractToRef(this._oldPosition, this._diffPosition);
  5827. if (this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  5828. this.position.addInPlace(this._diffPosition);
  5829. if (this.onCollide) {
  5830. this.onCollide(this._collider.collidedMesh);
  5831. }
  5832. }
  5833. };
  5834. FreeCamera.prototype._checkInputs = function () {
  5835. if (!this._localDirection) {
  5836. this._localDirection = BABYLON.Vector3.Zero();
  5837. this._transformedDirection = BABYLON.Vector3.Zero();
  5838. }
  5839. for (var index = 0; index < this._keys.length; index++) {
  5840. var keyCode = this._keys[index];
  5841. var speed = this._computeLocalCameraSpeed();
  5842. if (this.keysLeft.indexOf(keyCode) !== -1) {
  5843. this._localDirection.copyFromFloats(-speed, 0, 0);
  5844. } else if (this.keysUp.indexOf(keyCode) !== -1) {
  5845. this._localDirection.copyFromFloats(0, 0, speed);
  5846. } else if (this.keysRight.indexOf(keyCode) !== -1) {
  5847. this._localDirection.copyFromFloats(speed, 0, 0);
  5848. } else if (this.keysDown.indexOf(keyCode) !== -1) {
  5849. this._localDirection.copyFromFloats(0, 0, -speed);
  5850. }
  5851. this.getViewMatrix().invertToRef(this._cameraTransformMatrix);
  5852. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  5853. this.cameraDirection.addInPlace(this._transformedDirection);
  5854. }
  5855. };
  5856. FreeCamera.prototype._decideIfNeedsToMove = function () {
  5857. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  5858. };
  5859. FreeCamera.prototype._updatePosition = function () {
  5860. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  5861. this._collideWithWorld(this.cameraDirection);
  5862. if (this.applyGravity) {
  5863. var oldPosition = this.position;
  5864. this._collideWithWorld(this.getScene().gravity);
  5865. this._needMoveForGravity = (BABYLON.Vector3.DistanceSquared(oldPosition, this.position) != 0);
  5866. }
  5867. } else {
  5868. this.position.addInPlace(this.cameraDirection);
  5869. }
  5870. };
  5871. FreeCamera.prototype._update = function () {
  5872. this._checkInputs();
  5873. _super.prototype._update.call(this);
  5874. };
  5875. return FreeCamera;
  5876. })(BABYLON.TargetCamera);
  5877. BABYLON.FreeCamera = FreeCamera;
  5878. })(BABYLON || (BABYLON = {}));
  5879. var __extends = this.__extends || function (d, b) {
  5880. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  5881. function __() { this.constructor = d; }
  5882. __.prototype = b.prototype;
  5883. d.prototype = new __();
  5884. };
  5885. var BABYLON;
  5886. (function (BABYLON) {
  5887. var TouchCamera = (function (_super) {
  5888. __extends(TouchCamera, _super);
  5889. function TouchCamera(name, position, scene) {
  5890. _super.call(this, name, position, scene);
  5891. this._offsetX = null;
  5892. this._offsetY = null;
  5893. this._pointerCount = 0;
  5894. this._pointerPressed = [];
  5895. this.angularSensibility = 200000.0;
  5896. this.moveSensibility = 500.0;
  5897. }
  5898. TouchCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  5899. var _this = this;
  5900. var previousPosition;
  5901. if (this._attachedCanvas) {
  5902. return;
  5903. }
  5904. this._attachedCanvas = canvas;
  5905. if (this._onPointerDown === undefined) {
  5906. this._onPointerDown = function (evt) {
  5907. if (!noPreventDefault) {
  5908. evt.preventDefault();
  5909. }
  5910. _this._pointerPressed.push(evt.pointerId);
  5911. if (_this._pointerPressed.length !== 1) {
  5912. return;
  5913. }
  5914. previousPosition = {
  5915. x: evt.clientX,
  5916. y: evt.clientY
  5917. };
  5918. };
  5919. this._onPointerUp = function (evt) {
  5920. if (!noPreventDefault) {
  5921. evt.preventDefault();
  5922. }
  5923. var index = _this._pointerPressed.indexOf(evt.pointerId);
  5924. if (index === -1) {
  5925. return;
  5926. }
  5927. _this._pointerPressed.splice(index, 1);
  5928. if (index != 0) {
  5929. return;
  5930. }
  5931. previousPosition = null;
  5932. _this._offsetX = null;
  5933. _this._offsetY = null;
  5934. };
  5935. this._onPointerMove = function (evt) {
  5936. if (!noPreventDefault) {
  5937. evt.preventDefault();
  5938. }
  5939. if (!previousPosition) {
  5940. return;
  5941. }
  5942. var index = _this._pointerPressed.indexOf(evt.pointerId);
  5943. if (index != 0) {
  5944. return;
  5945. }
  5946. _this._offsetX = evt.clientX - previousPosition.x;
  5947. _this._offsetY = -(evt.clientY - previousPosition.y);
  5948. };
  5949. this._onLostFocus = function () {
  5950. _this._offsetX = null;
  5951. _this._offsetY = null;
  5952. };
  5953. }
  5954. canvas.addEventListener("pointerdown", this._onPointerDown);
  5955. canvas.addEventListener("pointerup", this._onPointerUp);
  5956. canvas.addEventListener("pointerout", this._onPointerUp);
  5957. canvas.addEventListener("pointermove", this._onPointerMove);
  5958. BABYLON.Tools.RegisterTopRootEvents([
  5959. { name: "blur", handler: this._onLostFocus }
  5960. ]);
  5961. };
  5962. TouchCamera.prototype.detachControl = function (canvas) {
  5963. if (this._attachedCanvas != canvas) {
  5964. return;
  5965. }
  5966. canvas.removeEventListener("pointerdown", this._onPointerDown);
  5967. canvas.removeEventListener("pointerup", this._onPointerUp);
  5968. canvas.removeEventListener("pointerout", this._onPointerUp);
  5969. canvas.removeEventListener("pointermove", this._onPointerMove);
  5970. BABYLON.Tools.UnregisterTopRootEvents([
  5971. { name: "blur", handler: this._onLostFocus }
  5972. ]);
  5973. this._attachedCanvas = null;
  5974. };
  5975. TouchCamera.prototype._checkInputs = function () {
  5976. if (!this._offsetX) {
  5977. return;
  5978. }
  5979. this.cameraRotation.y += this._offsetX / this.angularSensibility;
  5980. if (this._pointerPressed.length > 1) {
  5981. this.cameraRotation.x += -this._offsetY / this.angularSensibility;
  5982. } else {
  5983. var speed = this._computeLocalCameraSpeed();
  5984. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  5985. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  5986. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  5987. }
  5988. };
  5989. return TouchCamera;
  5990. })(BABYLON.FreeCamera);
  5991. BABYLON.TouchCamera = TouchCamera;
  5992. })(BABYLON || (BABYLON = {}));
  5993. var __extends = this.__extends || function (d, b) {
  5994. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  5995. function __() { this.constructor = d; }
  5996. __.prototype = b.prototype;
  5997. d.prototype = new __();
  5998. };
  5999. var BABYLON;
  6000. (function (BABYLON) {
  6001. var DeviceOrientationCamera = (function (_super) {
  6002. __extends(DeviceOrientationCamera, _super);
  6003. function DeviceOrientationCamera(name, position, scene) {
  6004. var _this = this;
  6005. _super.call(this, name, position, scene);
  6006. this._offsetX = null;
  6007. this._offsetY = null;
  6008. this._orientationGamma = 0;
  6009. this._orientationBeta = 0;
  6010. this._initialOrientationGamma = 0;
  6011. this._initialOrientationBeta = 0;
  6012. this.angularSensibility = 10000.0;
  6013. this.moveSensibility = 50.0;
  6014. window.addEventListener("resize", function () {
  6015. _this._initialOrientationGamma = null;
  6016. }, false);
  6017. }
  6018. DeviceOrientationCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  6019. var _this = this;
  6020. if (this._attachedCanvas) {
  6021. return;
  6022. }
  6023. this._attachedCanvas = canvas;
  6024. if (!this._orientationChanged) {
  6025. this._orientationChanged = function (evt) {
  6026. if (!_this._initialOrientationGamma) {
  6027. _this._initialOrientationGamma = evt.gamma;
  6028. _this._initialOrientationBeta = evt.beta;
  6029. }
  6030. _this._orientationGamma = evt.gamma;
  6031. _this._orientationBeta = evt.beta;
  6032. _this._offsetY = (_this._initialOrientationBeta - _this._orientationBeta);
  6033. _this._offsetX = (_this._initialOrientationGamma - _this._orientationGamma);
  6034. };
  6035. }
  6036. window.addEventListener("deviceorientation", this._orientationChanged);
  6037. };
  6038. DeviceOrientationCamera.prototype.detachControl = function (canvas) {
  6039. if (this._attachedCanvas != canvas) {
  6040. return;
  6041. }
  6042. window.removeEventListener("deviceorientation", this._orientationChanged);
  6043. this._attachedCanvas = null;
  6044. this._orientationGamma = 0;
  6045. this._orientationBeta = 0;
  6046. this._initialOrientationGamma = 0;
  6047. this._initialOrientationBeta = 0;
  6048. };
  6049. DeviceOrientationCamera.prototype._checkInputs = function () {
  6050. if (!this._offsetX) {
  6051. return;
  6052. }
  6053. this.cameraRotation.y -= this._offsetX / this.angularSensibility;
  6054. var speed = this._computeLocalCameraSpeed();
  6055. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  6056. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  6057. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  6058. };
  6059. return DeviceOrientationCamera;
  6060. })(BABYLON.FreeCamera);
  6061. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  6062. })(BABYLON || (BABYLON = {}));
  6063. var __extends = this.__extends || function (d, b) {
  6064. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  6065. function __() { this.constructor = d; }
  6066. __.prototype = b.prototype;
  6067. d.prototype = new __();
  6068. };
  6069. var BABYLON;
  6070. (function (BABYLON) {
  6071. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  6072. var ArcRotateCamera = (function (_super) {
  6073. __extends(ArcRotateCamera, _super);
  6074. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  6075. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  6076. this.alpha = alpha;
  6077. this.beta = beta;
  6078. this.radius = radius;
  6079. this.target = target;
  6080. this.inertialAlphaOffset = 0;
  6081. this.inertialBetaOffset = 0;
  6082. this.inertialRadiusOffset = 0;
  6083. this.lowerAlphaLimit = null;
  6084. this.upperAlphaLimit = null;
  6085. this.lowerBetaLimit = 0.01;
  6086. this.upperBetaLimit = Math.PI;
  6087. this.lowerRadiusLimit = null;
  6088. this.upperRadiusLimit = null;
  6089. this.angularSensibility = 1000.0;
  6090. this.wheelPrecision = 3.0;
  6091. this.keysUp = [38];
  6092. this.keysDown = [40];
  6093. this.keysLeft = [37];
  6094. this.keysRight = [39];
  6095. this.zoomOnFactor = 1;
  6096. this.targetScreenOffset = BABYLON.Vector2.Zero();
  6097. this._keys = [];
  6098. this._viewMatrix = new BABYLON.Matrix();
  6099. this.checkCollisions = false;
  6100. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  6101. this._collider = new BABYLON.Collider();
  6102. this._previousPosition = BABYLON.Vector3.Zero();
  6103. this._collisionVelocity = BABYLON.Vector3.Zero();
  6104. this._newPosition = BABYLON.Vector3.Zero();
  6105. this.pinchPrecision = 20;
  6106. this.getViewMatrix();
  6107. }
  6108. ArcRotateCamera.prototype._getTargetPosition = function () {
  6109. return this.target.position || this.target;
  6110. };
  6111. ArcRotateCamera.prototype._initCache = function () {
  6112. _super.prototype._initCache.call(this);
  6113. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6114. this._cache.alpha = undefined;
  6115. this._cache.beta = undefined;
  6116. this._cache.radius = undefined;
  6117. this._cache.targetScreenOffset = undefined;
  6118. };
  6119. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  6120. if (!ignoreParentClass) {
  6121. _super.prototype._updateCache.call(this);
  6122. }
  6123. this._cache.target.copyFrom(this._getTargetPosition());
  6124. this._cache.alpha = this.alpha;
  6125. this._cache.beta = this.beta;
  6126. this._cache.radius = this.radius;
  6127. this._cache.targetScreenOffset = this.targetScreenOffset.clone();
  6128. };
  6129. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  6130. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  6131. return false;
  6132. return this._cache.target.equals(this._getTargetPosition()) && this._cache.alpha === this.alpha && this._cache.beta === this.beta && this._cache.radius === this.radius && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  6133. };
  6134. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault) {
  6135. var _this = this;
  6136. var previousPosition;
  6137. var pointerId;
  6138. var pinchStarted = false;
  6139. var pinchPointX1, pinchPointX2;
  6140. if (this._attachedElement) {
  6141. return;
  6142. }
  6143. this._attachedElement = element;
  6144. var engine = this.getEngine();
  6145. if (this._onPointerDown === undefined) {
  6146. this._onPointerDown = function (evt) {
  6147. if (pointerId) {
  6148. return;
  6149. }
  6150. pointerId = evt.pointerId;
  6151. previousPosition = {
  6152. x: evt.clientX,
  6153. y: evt.clientY
  6154. };
  6155. if (!noPreventDefault) {
  6156. evt.preventDefault();
  6157. }
  6158. };
  6159. this._onPointerUp = function (evt) {
  6160. previousPosition = null;
  6161. pointerId = null;
  6162. if (!noPreventDefault) {
  6163. evt.preventDefault();
  6164. }
  6165. };
  6166. this._onPointerMove = function (evt) {
  6167. if (!previousPosition) {
  6168. return;
  6169. }
  6170. if (pointerId !== evt.pointerId) {
  6171. return;
  6172. }
  6173. if (pinchStarted) {
  6174. return;
  6175. }
  6176. var offsetX = evt.clientX - previousPosition.x;
  6177. var offsetY = evt.clientY - previousPosition.y;
  6178. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  6179. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  6180. previousPosition = {
  6181. x: evt.clientX,
  6182. y: evt.clientY
  6183. };
  6184. if (!noPreventDefault) {
  6185. evt.preventDefault();
  6186. }
  6187. };
  6188. this._onMouseMove = function (evt) {
  6189. if (!engine.isPointerLock) {
  6190. return;
  6191. }
  6192. if (pinchStarted) {
  6193. return;
  6194. }
  6195. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  6196. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  6197. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  6198. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  6199. if (!noPreventDefault) {
  6200. evt.preventDefault();
  6201. }
  6202. };
  6203. this._wheel = function (event) {
  6204. var delta = 0;
  6205. if (event.wheelDelta) {
  6206. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  6207. } else if (event.detail) {
  6208. delta = -event.detail / _this.wheelPrecision;
  6209. }
  6210. if (delta)
  6211. _this.inertialRadiusOffset += delta;
  6212. if (event.preventDefault) {
  6213. if (!noPreventDefault) {
  6214. event.preventDefault();
  6215. }
  6216. }
  6217. };
  6218. this._onKeyDown = function (evt) {
  6219. 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) {
  6220. var index = _this._keys.indexOf(evt.keyCode);
  6221. if (index === -1) {
  6222. _this._keys.push(evt.keyCode);
  6223. }
  6224. if (evt.preventDefault) {
  6225. if (!noPreventDefault) {
  6226. evt.preventDefault();
  6227. }
  6228. }
  6229. }
  6230. };
  6231. this._onKeyUp = function (evt) {
  6232. 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) {
  6233. var index = _this._keys.indexOf(evt.keyCode);
  6234. if (index >= 0) {
  6235. _this._keys.splice(index, 1);
  6236. }
  6237. if (evt.preventDefault) {
  6238. if (!noPreventDefault) {
  6239. evt.preventDefault();
  6240. }
  6241. }
  6242. }
  6243. };
  6244. this._onLostFocus = function () {
  6245. _this._keys = [];
  6246. pointerId = null;
  6247. };
  6248. this._onGestureStart = function (e) {
  6249. if (window.MSGesture === undefined) {
  6250. return;
  6251. }
  6252. if (!_this._MSGestureHandler) {
  6253. _this._MSGestureHandler = new MSGesture();
  6254. _this._MSGestureHandler.target = element;
  6255. }
  6256. _this._MSGestureHandler.addPointer(e.pointerId);
  6257. };
  6258. this._onGesture = function (e) {
  6259. _this.radius *= e.scale;
  6260. if (e.preventDefault) {
  6261. if (!noPreventDefault) {
  6262. e.stopPropagation();
  6263. e.preventDefault();
  6264. }
  6265. }
  6266. };
  6267. this._reset = function () {
  6268. _this._keys = [];
  6269. _this.inertialAlphaOffset = 0;
  6270. _this.inertialBetaOffset = 0;
  6271. _this.inertialRadiusOffset = 0;
  6272. previousPosition = null;
  6273. pointerId = null;
  6274. };
  6275. this._touchStart = function (event) {
  6276. if (event.touches.length == 2) {
  6277. pinchStarted = true;
  6278. _this._pinchStart(event);
  6279. }
  6280. };
  6281. this._touchMove = function (event) {
  6282. if (pinchStarted) {
  6283. _this._pinchMove(event);
  6284. }
  6285. };
  6286. this._touchEnd = function (event) {
  6287. if (pinchStarted) {
  6288. _this._pinchEnd(event);
  6289. }
  6290. };
  6291. this._pinchStart = function (event) {
  6292. pinchPointX1 = event.touches[0].clientX;
  6293. pinchPointX2 = event.touches[1].clientX;
  6294. pinchStarted = true;
  6295. };
  6296. this._pinchMove = function (event) {
  6297. var delta = 0;
  6298. var direction = 1;
  6299. var distanceXOrigine, distanceXNow;
  6300. if (event.touches.length != 2)
  6301. return;
  6302. distanceXOrigine = Math.abs(pinchPointX1 - pinchPointX2);
  6303. distanceXNow = Math.abs(event.touches[0].clientX - event.touches[1].clientX);
  6304. if (distanceXNow < distanceXOrigine) {
  6305. direction = -1;
  6306. }
  6307. delta = (_this.pinchPrecision / (_this.wheelPrecision * 40)) * direction;
  6308. _this.inertialRadiusOffset += delta;
  6309. pinchPointX1 = event.touches[0].clientX;
  6310. pinchPointX2 = event.touches[1].clientX;
  6311. };
  6312. this._pinchEnd = function (event) {
  6313. pinchStarted = false;
  6314. };
  6315. }
  6316. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  6317. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  6318. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  6319. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  6320. element.addEventListener("mousemove", this._onMouseMove, false);
  6321. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  6322. element.addEventListener("MSGestureChange", this._onGesture, false);
  6323. element.addEventListener('mousewheel', this._wheel, false);
  6324. element.addEventListener('DOMMouseScroll', this._wheel, false);
  6325. element.addEventListener('touchstart', this._touchStart, false);
  6326. element.addEventListener('touchmove', this._touchMove, false);
  6327. element.addEventListener('touchend', this._touchEnd, false);
  6328. BABYLON.Tools.RegisterTopRootEvents([
  6329. { name: "keydown", handler: this._onKeyDown },
  6330. { name: "keyup", handler: this._onKeyUp },
  6331. { name: "blur", handler: this._onLostFocus }
  6332. ]);
  6333. };
  6334. ArcRotateCamera.prototype.detachControl = function (element) {
  6335. if (this._attachedElement != element) {
  6336. return;
  6337. }
  6338. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  6339. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  6340. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  6341. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  6342. element.removeEventListener("mousemove", this._onMouseMove);
  6343. element.removeEventListener("MSPointerDown", this._onGestureStart);
  6344. element.removeEventListener("MSGestureChange", this._onGesture);
  6345. element.removeEventListener('mousewheel', this._wheel);
  6346. element.removeEventListener('DOMMouseScroll', this._wheel);
  6347. element.removeEventListener('touchstart', this._touchStart);
  6348. element.removeEventListener('touchmove', this._touchMove);
  6349. element.removeEventListener('touchend', this._touchEnd);
  6350. BABYLON.Tools.UnregisterTopRootEvents([
  6351. { name: "keydown", handler: this._onKeyDown },
  6352. { name: "keyup", handler: this._onKeyUp },
  6353. { name: "blur", handler: this._onLostFocus }
  6354. ]);
  6355. this._MSGestureHandler = null;
  6356. this._attachedElement = null;
  6357. if (this._reset) {
  6358. this._reset();
  6359. }
  6360. };
  6361. ArcRotateCamera.prototype._update = function () {
  6362. for (var index = 0; index < this._keys.length; index++) {
  6363. var keyCode = this._keys[index];
  6364. if (this.keysLeft.indexOf(keyCode) !== -1) {
  6365. this.inertialAlphaOffset -= 0.01;
  6366. } else if (this.keysUp.indexOf(keyCode) !== -1) {
  6367. this.inertialBetaOffset -= 0.01;
  6368. } else if (this.keysRight.indexOf(keyCode) !== -1) {
  6369. this.inertialAlphaOffset += 0.01;
  6370. } else if (this.keysDown.indexOf(keyCode) !== -1) {
  6371. this.inertialBetaOffset += 0.01;
  6372. }
  6373. }
  6374. if (this.inertialAlphaOffset != 0 || this.inertialBetaOffset != 0 || this.inertialRadiusOffset != 0) {
  6375. this.alpha += this.inertialAlphaOffset;
  6376. this.beta += this.inertialBetaOffset;
  6377. this.radius -= this.inertialRadiusOffset;
  6378. this.inertialAlphaOffset *= this.inertia;
  6379. this.inertialBetaOffset *= this.inertia;
  6380. this.inertialRadiusOffset *= this.inertia;
  6381. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Engine.Epsilon)
  6382. this.inertialAlphaOffset = 0;
  6383. if (Math.abs(this.inertialBetaOffset) < BABYLON.Engine.Epsilon)
  6384. this.inertialBetaOffset = 0;
  6385. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Engine.Epsilon)
  6386. this.inertialRadiusOffset = 0;
  6387. }
  6388. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  6389. this.alpha = this.lowerAlphaLimit;
  6390. }
  6391. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  6392. this.alpha = this.upperAlphaLimit;
  6393. }
  6394. if (this.lowerBetaLimit && this.beta < this.lowerBetaLimit) {
  6395. this.beta = this.lowerBetaLimit;
  6396. }
  6397. if (this.upperBetaLimit && this.beta > this.upperBetaLimit) {
  6398. this.beta = this.upperBetaLimit;
  6399. }
  6400. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  6401. this.radius = this.lowerRadiusLimit;
  6402. }
  6403. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  6404. this.radius = this.upperRadiusLimit;
  6405. }
  6406. };
  6407. ArcRotateCamera.prototype.setPosition = function (position) {
  6408. var radiusv3 = position.subtract(this._getTargetPosition());
  6409. this.radius = radiusv3.length();
  6410. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  6411. if (radiusv3.z < 0) {
  6412. this.alpha = 2 * Math.PI - this.alpha;
  6413. }
  6414. this.beta = Math.acos(radiusv3.y / this.radius);
  6415. };
  6416. ArcRotateCamera.prototype._getViewMatrix = function () {
  6417. var cosa = Math.cos(this.alpha);
  6418. var sina = Math.sin(this.alpha);
  6419. var cosb = Math.cos(this.beta);
  6420. var sinb = Math.sin(this.beta);
  6421. var target = this._getTargetPosition();
  6422. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this.position);
  6423. if (this.checkCollisions) {
  6424. this._collider.radius = this.collisionRadius;
  6425. this.position.subtractToRef(this._previousPosition, this._collisionVelocity);
  6426. this.getScene()._getNewPosition(this._previousPosition, this._collisionVelocity, this._collider, 3, this._newPosition);
  6427. if (!this._newPosition.equalsWithEpsilon(this.position)) {
  6428. this.position.copyFrom(this._previousPosition);
  6429. this.alpha = this._previousAlpha;
  6430. this.beta = this._previousBeta;
  6431. this.radius = this._previousRadius;
  6432. if (this.onCollide) {
  6433. this.onCollide(this._collider.collidedMesh);
  6434. }
  6435. }
  6436. }
  6437. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._viewMatrix);
  6438. this._previousAlpha = this.alpha;
  6439. this._previousBeta = this.beta;
  6440. this._previousRadius = this.radius;
  6441. this._previousPosition.copyFrom(this.position);
  6442. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  6443. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  6444. return this._viewMatrix;
  6445. };
  6446. ArcRotateCamera.prototype.zoomOn = function (meshes) {
  6447. meshes = meshes || this.getScene().meshes;
  6448. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  6449. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  6450. this.radius = distance * this.zoomOnFactor;
  6451. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance });
  6452. };
  6453. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance) {
  6454. var meshesOrMinMaxVector;
  6455. var distance;
  6456. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  6457. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  6458. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  6459. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  6460. } else {
  6461. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  6462. distance = meshesOrMinMaxVectorAndDistance.distance;
  6463. }
  6464. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  6465. this.maxZ = distance * 2;
  6466. };
  6467. return ArcRotateCamera;
  6468. })(BABYLON.Camera);
  6469. BABYLON.ArcRotateCamera = ArcRotateCamera;
  6470. })(BABYLON || (BABYLON = {}));
  6471. var BABYLON;
  6472. (function (BABYLON) {
  6473. var Scene = (function () {
  6474. function Scene(engine) {
  6475. this.autoClear = true;
  6476. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  6477. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  6478. this.forceWireframe = false;
  6479. this.cameraToUseForPointers = null;
  6480. this.fogMode = BABYLON.Scene.FOGMODE_NONE;
  6481. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  6482. this.fogDensity = 0.1;
  6483. this.fogStart = 0;
  6484. this.fogEnd = 1000.0;
  6485. this.shadowsEnabled = true;
  6486. this.lightsEnabled = true;
  6487. this.lights = new Array();
  6488. this.cameras = new Array();
  6489. this.activeCameras = new Array();
  6490. this.meshes = new Array();
  6491. this._geometries = new Array();
  6492. this.materials = new Array();
  6493. this.multiMaterials = new Array();
  6494. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  6495. this.texturesEnabled = true;
  6496. this.textures = new Array();
  6497. this.particlesEnabled = true;
  6498. this.particleSystems = new Array();
  6499. this.spriteManagers = new Array();
  6500. this.layers = new Array();
  6501. this.skeletons = new Array();
  6502. this.lensFlaresEnabled = true;
  6503. this.lensFlareSystems = new Array();
  6504. this.collisionsEnabled = true;
  6505. this.gravity = new BABYLON.Vector3(0, -9.0, 0);
  6506. this.postProcessesEnabled = true;
  6507. this.renderTargetsEnabled = true;
  6508. this.customRenderTargets = new Array();
  6509. this.importedMeshesFiles = new Array();
  6510. this._actionManagers = new Array();
  6511. this._meshesForIntersections = new BABYLON.SmartArray(256);
  6512. this.proceduralTexturesEnabled = true;
  6513. this._proceduralTextures = new Array();
  6514. this._totalVertices = 0;
  6515. this._activeVertices = 0;
  6516. this._activeParticles = 0;
  6517. this._lastFrameDuration = 0;
  6518. this._evaluateActiveMeshesDuration = 0;
  6519. this._renderTargetsDuration = 0;
  6520. this._particlesDuration = 0;
  6521. this._renderDuration = 0;
  6522. this._spritesDuration = 0;
  6523. this._animationRatio = 0;
  6524. this._renderId = 0;
  6525. this._executeWhenReadyTimeoutId = -1;
  6526. this._toBeDisposed = new BABYLON.SmartArray(256);
  6527. this._onReadyCallbacks = new Array();
  6528. this._pendingData = [];
  6529. this._onBeforeRenderCallbacks = new Array();
  6530. this._activeMeshes = new BABYLON.SmartArray(256);
  6531. this._processedMaterials = new BABYLON.SmartArray(256);
  6532. this._renderTargets = new BABYLON.SmartArray(256);
  6533. this._activeParticleSystems = new BABYLON.SmartArray(256);
  6534. this._activeSkeletons = new BABYLON.SmartArray(32);
  6535. this._activeAnimatables = new Array();
  6536. this._transformMatrix = BABYLON.Matrix.Zero();
  6537. this._scaledPosition = BABYLON.Vector3.Zero();
  6538. this._scaledVelocity = BABYLON.Vector3.Zero();
  6539. this._engine = engine;
  6540. engine.scenes.push(this);
  6541. this._renderingManager = new BABYLON.RenderingManager(this);
  6542. this.postProcessManager = new BABYLON.PostProcessManager(this);
  6543. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  6544. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  6545. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  6546. this.attachControl();
  6547. }
  6548. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  6549. get: function () {
  6550. return this._meshUnderPointer;
  6551. },
  6552. enumerable: true,
  6553. configurable: true
  6554. });
  6555. Object.defineProperty(Scene.prototype, "pointerX", {
  6556. get: function () {
  6557. return this._pointerX;
  6558. },
  6559. enumerable: true,
  6560. configurable: true
  6561. });
  6562. Object.defineProperty(Scene.prototype, "pointerY", {
  6563. get: function () {
  6564. return this._pointerY;
  6565. },
  6566. enumerable: true,
  6567. configurable: true
  6568. });
  6569. Scene.prototype.getBoundingBoxRenderer = function () {
  6570. return this._boundingBoxRenderer;
  6571. };
  6572. Scene.prototype.getOutlineRenderer = function () {
  6573. return this._outlineRenderer;
  6574. };
  6575. Scene.prototype.getEngine = function () {
  6576. return this._engine;
  6577. };
  6578. Scene.prototype.getTotalVertices = function () {
  6579. return this._totalVertices;
  6580. };
  6581. Scene.prototype.getActiveVertices = function () {
  6582. return this._activeVertices;
  6583. };
  6584. Scene.prototype.getActiveParticles = function () {
  6585. return this._activeParticles;
  6586. };
  6587. Scene.prototype.getLastFrameDuration = function () {
  6588. return this._lastFrameDuration;
  6589. };
  6590. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  6591. return this._evaluateActiveMeshesDuration;
  6592. };
  6593. Scene.prototype.getActiveMeshes = function () {
  6594. return this._activeMeshes;
  6595. };
  6596. Scene.prototype.getRenderTargetsDuration = function () {
  6597. return this._renderTargetsDuration;
  6598. };
  6599. Scene.prototype.getRenderDuration = function () {
  6600. return this._renderDuration;
  6601. };
  6602. Scene.prototype.getParticlesDuration = function () {
  6603. return this._particlesDuration;
  6604. };
  6605. Scene.prototype.getSpritesDuration = function () {
  6606. return this._spritesDuration;
  6607. };
  6608. Scene.prototype.getAnimationRatio = function () {
  6609. return this._animationRatio;
  6610. };
  6611. Scene.prototype.getRenderId = function () {
  6612. return this._renderId;
  6613. };
  6614. Scene.prototype._updatePointerPosition = function (evt) {
  6615. var canvasRect = this._engine.getRenderingCanvasClientRect();
  6616. this._pointerX = evt.clientX - canvasRect.left;
  6617. this._pointerY = evt.clientY - canvasRect.top;
  6618. if (this.cameraToUseForPointers) {
  6619. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  6620. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  6621. }
  6622. };
  6623. Scene.prototype.attachControl = function () {
  6624. var _this = this;
  6625. this._onPointerMove = function (evt) {
  6626. var canvas = _this._engine.getRenderingCanvas();
  6627. _this._updatePointerPosition(evt);
  6628. var pickResult = _this.pick(_this._pointerX, _this._pointerY, function (mesh) {
  6629. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPointerTriggers;
  6630. }, false, _this.cameraToUseForPointers);
  6631. if (pickResult.hit) {
  6632. _this._meshUnderPointer = pickResult.pickedMesh;
  6633. _this.setPointerOverMesh(pickResult.pickedMesh);
  6634. canvas.style.cursor = "pointer";
  6635. } else {
  6636. _this.setPointerOverMesh(null);
  6637. canvas.style.cursor = "";
  6638. _this._meshUnderPointer = null;
  6639. }
  6640. };
  6641. this._onPointerDown = function (evt) {
  6642. var predicate = null;
  6643. if (!_this.onPointerDown) {
  6644. predicate = function (mesh) {
  6645. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPickTriggers;
  6646. };
  6647. }
  6648. _this._updatePointerPosition(evt);
  6649. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  6650. if (pickResult.hit) {
  6651. if (pickResult.pickedMesh.actionManager) {
  6652. switch (evt.button) {
  6653. case 0:
  6654. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh));
  6655. break;
  6656. case 1:
  6657. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh));
  6658. break;
  6659. case 2:
  6660. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh));
  6661. break;
  6662. }
  6663. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh));
  6664. }
  6665. }
  6666. if (_this.onPointerDown) {
  6667. _this.onPointerDown(evt, pickResult);
  6668. }
  6669. };
  6670. this._onKeyDown = function (evt) {
  6671. if (_this.actionManager) {
  6672. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  6673. }
  6674. };
  6675. this._onKeyUp = function (evt) {
  6676. if (_this.actionManager) {
  6677. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  6678. }
  6679. };
  6680. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  6681. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  6682. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  6683. window.addEventListener("keydown", this._onKeyDown, false);
  6684. window.addEventListener("keyup", this._onKeyUp, false);
  6685. };
  6686. Scene.prototype.detachControl = function () {
  6687. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  6688. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  6689. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  6690. window.removeEventListener("keydown", this._onKeyDown);
  6691. window.removeEventListener("keyup", this._onKeyUp);
  6692. };
  6693. Scene.prototype.isReady = function () {
  6694. if (this._pendingData.length > 0) {
  6695. return false;
  6696. }
  6697. for (var index = 0; index < this._geometries.length; index++) {
  6698. var geometry = this._geometries[index];
  6699. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  6700. return false;
  6701. }
  6702. }
  6703. for (index = 0; index < this.meshes.length; index++) {
  6704. var mesh = this.meshes[index];
  6705. if (!mesh.isReady()) {
  6706. return false;
  6707. }
  6708. var mat = mesh.material;
  6709. if (mat) {
  6710. if (!mat.isReady(mesh)) {
  6711. return false;
  6712. }
  6713. }
  6714. }
  6715. return true;
  6716. };
  6717. Scene.prototype.registerBeforeRender = function (func) {
  6718. this._onBeforeRenderCallbacks.push(func);
  6719. };
  6720. Scene.prototype.unregisterBeforeRender = function (func) {
  6721. var index = this._onBeforeRenderCallbacks.indexOf(func);
  6722. if (index > -1) {
  6723. this._onBeforeRenderCallbacks.splice(index, 1);
  6724. }
  6725. };
  6726. Scene.prototype._addPendingData = function (data) {
  6727. this._pendingData.push(data);
  6728. };
  6729. Scene.prototype._removePendingData = function (data) {
  6730. var index = this._pendingData.indexOf(data);
  6731. if (index !== -1) {
  6732. this._pendingData.splice(index, 1);
  6733. }
  6734. };
  6735. Scene.prototype.getWaitingItemsCount = function () {
  6736. return this._pendingData.length;
  6737. };
  6738. Scene.prototype.executeWhenReady = function (func) {
  6739. var _this = this;
  6740. this._onReadyCallbacks.push(func);
  6741. if (this._executeWhenReadyTimeoutId !== -1) {
  6742. return;
  6743. }
  6744. this._executeWhenReadyTimeoutId = setTimeout(function () {
  6745. _this._checkIsReady();
  6746. }, 150);
  6747. };
  6748. Scene.prototype._checkIsReady = function () {
  6749. var _this = this;
  6750. if (this.isReady()) {
  6751. this._onReadyCallbacks.forEach(function (func) {
  6752. func();
  6753. });
  6754. this._onReadyCallbacks = [];
  6755. this._executeWhenReadyTimeoutId = -1;
  6756. return;
  6757. }
  6758. this._executeWhenReadyTimeoutId = setTimeout(function () {
  6759. _this._checkIsReady();
  6760. }, 150);
  6761. };
  6762. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  6763. if (speedRatio === undefined) {
  6764. speedRatio = 1.0;
  6765. }
  6766. this.stopAnimation(target);
  6767. if (!animatable) {
  6768. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  6769. }
  6770. if (target.animations) {
  6771. animatable.appendAnimations(target, target.animations);
  6772. }
  6773. if (target.getAnimatables) {
  6774. var animatables = target.getAnimatables();
  6775. for (var index = 0; index < animatables.length; index++) {
  6776. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  6777. }
  6778. }
  6779. return animatable;
  6780. };
  6781. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  6782. if (speedRatio === undefined) {
  6783. speedRatio = 1.0;
  6784. }
  6785. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  6786. return animatable;
  6787. };
  6788. Scene.prototype.getAnimatableByTarget = function (target) {
  6789. for (var index = 0; index < this._activeAnimatables.length; index++) {
  6790. if (this._activeAnimatables[index].target === target) {
  6791. return this._activeAnimatables[index];
  6792. }
  6793. }
  6794. return null;
  6795. };
  6796. Scene.prototype.stopAnimation = function (target) {
  6797. var animatable = this.getAnimatableByTarget(target);
  6798. if (animatable) {
  6799. animatable.stop();
  6800. }
  6801. };
  6802. Scene.prototype._animate = function () {
  6803. if (!this._animationStartDate) {
  6804. this._animationStartDate = BABYLON.Tools.Now;
  6805. }
  6806. var now = BABYLON.Tools.Now;
  6807. var delay = now - this._animationStartDate;
  6808. for (var index = 0; index < this._activeAnimatables.length; index++) {
  6809. if (!this._activeAnimatables[index]._animate(delay)) {
  6810. this._activeAnimatables.splice(index, 1);
  6811. index--;
  6812. }
  6813. }
  6814. };
  6815. Scene.prototype.getViewMatrix = function () {
  6816. return this._viewMatrix;
  6817. };
  6818. Scene.prototype.getProjectionMatrix = function () {
  6819. return this._projectionMatrix;
  6820. };
  6821. Scene.prototype.getTransformMatrix = function () {
  6822. return this._transformMatrix;
  6823. };
  6824. Scene.prototype.setTransformMatrix = function (view, projection) {
  6825. this._viewMatrix = view;
  6826. this._projectionMatrix = projection;
  6827. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  6828. };
  6829. Scene.prototype.setActiveCameraByID = function (id) {
  6830. var camera = this.getCameraByID(id);
  6831. if (camera) {
  6832. this.activeCamera = camera;
  6833. return camera;
  6834. }
  6835. return null;
  6836. };
  6837. Scene.prototype.setActiveCameraByName = function (name) {
  6838. var camera = this.getCameraByName(name);
  6839. if (camera) {
  6840. this.activeCamera = camera;
  6841. return camera;
  6842. }
  6843. return null;
  6844. };
  6845. Scene.prototype.getMaterialByID = function (id) {
  6846. for (var index = 0; index < this.materials.length; index++) {
  6847. if (this.materials[index].id === id) {
  6848. return this.materials[index];
  6849. }
  6850. }
  6851. return null;
  6852. };
  6853. Scene.prototype.getMaterialByName = function (name) {
  6854. for (var index = 0; index < this.materials.length; index++) {
  6855. if (this.materials[index].name === name) {
  6856. return this.materials[index];
  6857. }
  6858. }
  6859. return null;
  6860. };
  6861. Scene.prototype.getCameraByID = function (id) {
  6862. for (var index = 0; index < this.cameras.length; index++) {
  6863. if (this.cameras[index].id === id) {
  6864. return this.cameras[index];
  6865. }
  6866. }
  6867. return null;
  6868. };
  6869. Scene.prototype.getCameraByName = function (name) {
  6870. for (var index = 0; index < this.cameras.length; index++) {
  6871. if (this.cameras[index].name === name) {
  6872. return this.cameras[index];
  6873. }
  6874. }
  6875. return null;
  6876. };
  6877. Scene.prototype.getLightByName = function (name) {
  6878. for (var index = 0; index < this.lights.length; index++) {
  6879. if (this.lights[index].name === name) {
  6880. return this.lights[index];
  6881. }
  6882. }
  6883. return null;
  6884. };
  6885. Scene.prototype.getLightByID = function (id) {
  6886. for (var index = 0; index < this.lights.length; index++) {
  6887. if (this.lights[index].id === id) {
  6888. return this.lights[index];
  6889. }
  6890. }
  6891. return null;
  6892. };
  6893. Scene.prototype.getGeometryByID = function (id) {
  6894. for (var index = 0; index < this._geometries.length; index++) {
  6895. if (this._geometries[index].id === id) {
  6896. return this._geometries[index];
  6897. }
  6898. }
  6899. return null;
  6900. };
  6901. Scene.prototype.pushGeometry = function (geometry, force) {
  6902. if (!force && this.getGeometryByID(geometry.id)) {
  6903. return false;
  6904. }
  6905. this._geometries.push(geometry);
  6906. return true;
  6907. };
  6908. Scene.prototype.getGeometries = function () {
  6909. return this._geometries;
  6910. };
  6911. Scene.prototype.getMeshByID = function (id) {
  6912. for (var index = 0; index < this.meshes.length; index++) {
  6913. if (this.meshes[index].id === id) {
  6914. return this.meshes[index];
  6915. }
  6916. }
  6917. return null;
  6918. };
  6919. Scene.prototype.getLastMeshByID = function (id) {
  6920. for (var index = this.meshes.length - 1; index >= 0; index--) {
  6921. if (this.meshes[index].id === id) {
  6922. return this.meshes[index];
  6923. }
  6924. }
  6925. return null;
  6926. };
  6927. Scene.prototype.getLastEntryByID = function (id) {
  6928. for (var index = this.meshes.length - 1; index >= 0; index--) {
  6929. if (this.meshes[index].id === id) {
  6930. return this.meshes[index];
  6931. }
  6932. }
  6933. for (index = this.cameras.length - 1; index >= 0; index--) {
  6934. if (this.cameras[index].id === id) {
  6935. return this.cameras[index];
  6936. }
  6937. }
  6938. for (index = this.lights.length - 1; index >= 0; index--) {
  6939. if (this.lights[index].id === id) {
  6940. return this.lights[index];
  6941. }
  6942. }
  6943. return null;
  6944. };
  6945. Scene.prototype.getMeshByName = function (name) {
  6946. for (var index = 0; index < this.meshes.length; index++) {
  6947. if (this.meshes[index].name === name) {
  6948. return this.meshes[index];
  6949. }
  6950. }
  6951. return null;
  6952. };
  6953. Scene.prototype.getLastSkeletonByID = function (id) {
  6954. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  6955. if (this.skeletons[index].id === id) {
  6956. return this.skeletons[index];
  6957. }
  6958. }
  6959. return null;
  6960. };
  6961. Scene.prototype.getSkeletonById = function (id) {
  6962. for (var index = 0; index < this.skeletons.length; index++) {
  6963. if (this.skeletons[index].id === id) {
  6964. return this.skeletons[index];
  6965. }
  6966. }
  6967. return null;
  6968. };
  6969. Scene.prototype.getSkeletonByName = function (name) {
  6970. for (var index = 0; index < this.skeletons.length; index++) {
  6971. if (this.skeletons[index].name === name) {
  6972. return this.skeletons[index];
  6973. }
  6974. }
  6975. return null;
  6976. };
  6977. Scene.prototype.isActiveMesh = function (mesh) {
  6978. return (this._activeMeshes.indexOf(mesh) !== -1);
  6979. };
  6980. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  6981. if (mesh.subMeshes.length == 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  6982. var material = subMesh.getMaterial();
  6983. if (mesh.showSubMeshesBoundingBox) {
  6984. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  6985. }
  6986. if (material) {
  6987. if (material.getRenderTargetTextures) {
  6988. if (this._processedMaterials.indexOf(material) === -1) {
  6989. this._processedMaterials.push(material);
  6990. this._renderTargets.concat(material.getRenderTargetTextures());
  6991. }
  6992. }
  6993. this._activeVertices += subMesh.verticesCount;
  6994. this._renderingManager.dispatch(subMesh);
  6995. }
  6996. }
  6997. };
  6998. Scene.prototype._evaluateActiveMeshes = function () {
  6999. this._activeMeshes.reset();
  7000. this._renderingManager.reset();
  7001. this._processedMaterials.reset();
  7002. this._activeParticleSystems.reset();
  7003. this._activeSkeletons.reset();
  7004. this._boundingBoxRenderer.reset();
  7005. if (!this._frustumPlanes) {
  7006. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  7007. } else {
  7008. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  7009. }
  7010. var meshes;
  7011. var len;
  7012. if (this._selectionOctree) {
  7013. var selection = this._selectionOctree.select(this._frustumPlanes);
  7014. meshes = selection.data;
  7015. len = selection.length;
  7016. } else {
  7017. len = this.meshes.length;
  7018. meshes = this.meshes;
  7019. }
  7020. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  7021. var mesh = meshes[meshIndex];
  7022. if (mesh.isBlocked) {
  7023. continue;
  7024. }
  7025. this._totalVertices += mesh.getTotalVertices();
  7026. if (!mesh.isReady()) {
  7027. continue;
  7028. }
  7029. mesh.computeWorldMatrix();
  7030. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  7031. this._meshesForIntersections.pushNoDuplicate(mesh);
  7032. }
  7033. var meshLOD = mesh.getLOD(this.activeCamera);
  7034. if (!meshLOD) {
  7035. continue;
  7036. }
  7037. mesh._preActivate();
  7038. if (mesh.isEnabled() && mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) != 0) && mesh.isInFrustum(this._frustumPlanes)) {
  7039. this._activeMeshes.push(mesh);
  7040. mesh._activate(this._renderId);
  7041. this._activeMesh(meshLOD);
  7042. }
  7043. }
  7044. var beforeParticlesDate = BABYLON.Tools.Now;
  7045. if (this.particlesEnabled) {
  7046. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  7047. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  7048. var particleSystem = this.particleSystems[particleIndex];
  7049. if (!particleSystem.isStarted()) {
  7050. continue;
  7051. }
  7052. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  7053. this._activeParticleSystems.push(particleSystem);
  7054. particleSystem.animate();
  7055. }
  7056. }
  7057. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  7058. }
  7059. this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  7060. };
  7061. Scene.prototype._activeMesh = function (mesh) {
  7062. if (mesh.skeleton) {
  7063. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  7064. }
  7065. if (mesh.showBoundingBox) {
  7066. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  7067. }
  7068. if (mesh && mesh.subMeshes) {
  7069. var len;
  7070. var subMeshes;
  7071. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  7072. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  7073. len = intersections.length;
  7074. subMeshes = intersections.data;
  7075. } else {
  7076. subMeshes = mesh.subMeshes;
  7077. len = subMeshes.length;
  7078. }
  7079. for (var subIndex = 0; subIndex < len; subIndex++) {
  7080. var subMesh = subMeshes[subIndex];
  7081. this._evaluateSubMesh(subMesh, mesh);
  7082. }
  7083. }
  7084. };
  7085. Scene.prototype.updateTransformMatrix = function (force) {
  7086. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  7087. };
  7088. Scene.prototype._renderForCamera = function (camera) {
  7089. var engine = this._engine;
  7090. this.activeCamera = camera;
  7091. if (!this.activeCamera)
  7092. throw new Error("Active camera not set");
  7093. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  7094. engine.setViewport(this.activeCamera.viewport);
  7095. this._renderId++;
  7096. this.updateTransformMatrix();
  7097. if (this.beforeCameraRender) {
  7098. this.beforeCameraRender(this.activeCamera);
  7099. }
  7100. var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
  7101. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  7102. this._evaluateActiveMeshes();
  7103. this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
  7104. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  7105. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  7106. var skeleton = this._activeSkeletons.data[skeletonIndex];
  7107. skeleton.prepare();
  7108. }
  7109. var beforeRenderTargetDate = BABYLON.Tools.Now;
  7110. if (this.renderTargetsEnabled) {
  7111. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  7112. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  7113. var renderTarget = this._renderTargets.data[renderIndex];
  7114. if (renderTarget._shouldRender()) {
  7115. this._renderId++;
  7116. renderTarget.render();
  7117. }
  7118. }
  7119. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  7120. this._renderId++;
  7121. }
  7122. if (this._renderTargets.length > 0) {
  7123. engine.restoreDefaultFramebuffer();
  7124. }
  7125. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  7126. this.postProcessManager._prepareFrame();
  7127. var beforeRenderDate = BABYLON.Tools.Now;
  7128. if (this.layers.length) {
  7129. engine.setDepthBuffer(false);
  7130. var layerIndex;
  7131. var layer;
  7132. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  7133. layer = this.layers[layerIndex];
  7134. if (layer.isBackground) {
  7135. layer.render();
  7136. }
  7137. }
  7138. engine.setDepthBuffer(true);
  7139. }
  7140. BABYLON.Tools.StartPerformanceCounter("Main render");
  7141. this._renderingManager.render(null, null, true, true);
  7142. BABYLON.Tools.EndPerformanceCounter("Main render");
  7143. this._boundingBoxRenderer.render();
  7144. if (this.lensFlaresEnabled) {
  7145. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  7146. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  7147. this.lensFlareSystems[lensFlareSystemIndex].render();
  7148. }
  7149. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  7150. }
  7151. if (this.layers.length) {
  7152. engine.setDepthBuffer(false);
  7153. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  7154. layer = this.layers[layerIndex];
  7155. if (!layer.isBackground) {
  7156. layer.render();
  7157. }
  7158. }
  7159. engine.setDepthBuffer(true);
  7160. }
  7161. this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
  7162. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  7163. this.activeCamera._updateFromScene();
  7164. this._renderTargets.reset();
  7165. if (this.afterCameraRender) {
  7166. this.afterCameraRender(this.activeCamera);
  7167. }
  7168. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  7169. };
  7170. Scene.prototype._processSubCameras = function (camera) {
  7171. if (camera.subCameras.length == 0) {
  7172. this._renderForCamera(camera);
  7173. return;
  7174. }
  7175. for (var index = 0; index < camera.subCameras.length; index++) {
  7176. this._renderForCamera(camera.subCameras[index]);
  7177. }
  7178. this.activeCamera = camera;
  7179. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  7180. this.activeCamera._updateFromScene();
  7181. };
  7182. Scene.prototype._checkIntersections = function () {
  7183. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  7184. var sourceMesh = this._meshesForIntersections.data[index];
  7185. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  7186. var action = sourceMesh.actionManager.actions[actionIndex];
  7187. if (action.trigger == BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger == BABYLON.ActionManager.OnIntersectionExitTrigger) {
  7188. var otherMesh = action.getTriggerParameter();
  7189. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, false);
  7190. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  7191. if (areIntersecting && currentIntersectionInProgress === -1 && action.trigger == BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  7192. sourceMesh.actionManager.processTrigger(BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionEvent.CreateNew(sourceMesh));
  7193. sourceMesh._intersectionsInProgress.push(otherMesh);
  7194. } else if (!areIntersecting && currentIntersectionInProgress > -1 && action.trigger == BABYLON.ActionManager.OnIntersectionExitTrigger) {
  7195. sourceMesh.actionManager.processTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, BABYLON.ActionEvent.CreateNew(sourceMesh));
  7196. var indexOfOther = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  7197. if (indexOfOther > -1) {
  7198. sourceMesh._intersectionsInProgress.splice(indexOfOther, 1);
  7199. }
  7200. }
  7201. }
  7202. }
  7203. }
  7204. };
  7205. Scene.prototype.render = function () {
  7206. var startDate = BABYLON.Tools.Now;
  7207. this._particlesDuration = 0;
  7208. this._spritesDuration = 0;
  7209. this._activeParticles = 0;
  7210. this._renderDuration = 0;
  7211. this._evaluateActiveMeshesDuration = 0;
  7212. this._totalVertices = 0;
  7213. this._activeVertices = 0;
  7214. this._meshesForIntersections.reset();
  7215. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  7216. if (this.actionManager) {
  7217. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  7218. }
  7219. if (this.beforeRender) {
  7220. this.beforeRender();
  7221. }
  7222. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  7223. this._onBeforeRenderCallbacks[callbackIndex]();
  7224. }
  7225. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(BABYLON.Tools.GetDeltaTime(), Scene.MaxDeltaTime));
  7226. this._animationRatio = deltaTime * (60.0 / 1000.0);
  7227. this._animate();
  7228. if (this._physicsEngine) {
  7229. BABYLON.Tools.StartPerformanceCounter("Physics");
  7230. this._physicsEngine._runOneStep(deltaTime / 1000.0);
  7231. BABYLON.Tools.EndPerformanceCounter("Physics");
  7232. }
  7233. var beforeRenderTargetDate = BABYLON.Tools.Now;
  7234. var engine = this.getEngine();
  7235. if (this.renderTargetsEnabled) {
  7236. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  7237. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  7238. var renderTarget = this.customRenderTargets[customIndex];
  7239. if (renderTarget._shouldRender()) {
  7240. this._renderId++;
  7241. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  7242. if (!this.activeCamera)
  7243. throw new Error("Active camera not set");
  7244. engine.setViewport(this.activeCamera.viewport);
  7245. this.updateTransformMatrix();
  7246. renderTarget.render();
  7247. }
  7248. }
  7249. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  7250. this._renderId++;
  7251. }
  7252. if (this.customRenderTargets.length > 0) {
  7253. engine.restoreDefaultFramebuffer();
  7254. }
  7255. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  7256. if (this.proceduralTexturesEnabled) {
  7257. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  7258. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  7259. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  7260. if (proceduralTexture._shouldRender()) {
  7261. proceduralTexture.render();
  7262. }
  7263. }
  7264. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  7265. }
  7266. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe, true);
  7267. if (this.shadowsEnabled) {
  7268. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  7269. var light = this.lights[lightIndex];
  7270. var shadowGenerator = light.getShadowGenerator();
  7271. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  7272. this._renderTargets.push(shadowGenerator.getShadowMap());
  7273. }
  7274. }
  7275. }
  7276. this.postProcessRenderPipelineManager.update();
  7277. if (this.activeCameras.length > 0) {
  7278. var currentRenderId = this._renderId;
  7279. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  7280. this._renderId = currentRenderId;
  7281. this._processSubCameras(this.activeCameras[cameraIndex]);
  7282. }
  7283. } else {
  7284. if (!this.activeCamera) {
  7285. throw new Error("No camera defined");
  7286. }
  7287. this._processSubCameras(this.activeCamera);
  7288. }
  7289. this._checkIntersections();
  7290. this._updateAudioParameters();
  7291. if (this.afterRender) {
  7292. this.afterRender();
  7293. }
  7294. for (var index = 0; index < this._toBeDisposed.length; index++) {
  7295. this._toBeDisposed.data[index].dispose();
  7296. this._toBeDisposed[index] = null;
  7297. }
  7298. this._toBeDisposed.reset();
  7299. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  7300. this._lastFrameDuration = BABYLON.Tools.Now - startDate;
  7301. };
  7302. Scene.prototype._updateAudioParameters = function () {
  7303. var listeningCamera;
  7304. var audioEngine = this._engine.getAudioEngine();
  7305. if (this.activeCameras.length > 0) {
  7306. listeningCamera = this.activeCameras[0];
  7307. } else {
  7308. listeningCamera = this.activeCamera;
  7309. }
  7310. if (listeningCamera && audioEngine.canUseWebAudio) {
  7311. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  7312. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  7313. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  7314. cameraDirection.normalize();
  7315. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  7316. }
  7317. };
  7318. Scene.prototype.dispose = function () {
  7319. this.beforeRender = null;
  7320. this.afterRender = null;
  7321. this.skeletons = [];
  7322. this._boundingBoxRenderer.dispose();
  7323. if (this.onDispose) {
  7324. this.onDispose();
  7325. }
  7326. this._onBeforeRenderCallbacks = [];
  7327. this.detachControl();
  7328. var canvas = this._engine.getRenderingCanvas();
  7329. var index;
  7330. for (index = 0; index < this.cameras.length; index++) {
  7331. this.cameras[index].detachControl(canvas);
  7332. }
  7333. while (this.lights.length) {
  7334. this.lights[0].dispose();
  7335. }
  7336. while (this.meshes.length) {
  7337. this.meshes[0].dispose(true);
  7338. }
  7339. while (this.cameras.length) {
  7340. this.cameras[0].dispose();
  7341. }
  7342. while (this.materials.length) {
  7343. this.materials[0].dispose();
  7344. }
  7345. while (this.particleSystems.length) {
  7346. this.particleSystems[0].dispose();
  7347. }
  7348. while (this.spriteManagers.length) {
  7349. this.spriteManagers[0].dispose();
  7350. }
  7351. while (this.layers.length) {
  7352. this.layers[0].dispose();
  7353. }
  7354. while (this.textures.length) {
  7355. this.textures[0].dispose();
  7356. }
  7357. this.postProcessManager.dispose();
  7358. if (this._physicsEngine) {
  7359. this.disablePhysicsEngine();
  7360. }
  7361. index = this._engine.scenes.indexOf(this);
  7362. if (index > -1) {
  7363. this._engine.scenes.splice(index, 1);
  7364. }
  7365. this._engine.wipeCaches();
  7366. };
  7367. Scene.prototype._getNewPosition = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  7368. if (typeof excludedMesh === "undefined") { excludedMesh = null; }
  7369. position.divideToRef(collider.radius, this._scaledPosition);
  7370. velocity.divideToRef(collider.radius, this._scaledVelocity);
  7371. collider.retry = 0;
  7372. collider.initialVelocity = this._scaledVelocity;
  7373. collider.initialPosition = this._scaledPosition;
  7374. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, finalPosition, excludedMesh);
  7375. finalPosition.multiplyInPlace(collider.radius);
  7376. };
  7377. Scene.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  7378. if (typeof excludedMesh === "undefined") { excludedMesh = null; }
  7379. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  7380. if (collider.retry >= maximumRetry) {
  7381. finalPosition.copyFrom(position);
  7382. return;
  7383. }
  7384. collider._initialize(position, velocity, closeDistance);
  7385. for (var index = 0; index < this.meshes.length; index++) {
  7386. var mesh = this.meshes[index];
  7387. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  7388. mesh._checkCollision(collider);
  7389. }
  7390. }
  7391. if (!collider.collisionFound) {
  7392. position.addToRef(velocity, finalPosition);
  7393. return;
  7394. }
  7395. if (velocity.x != 0 || velocity.y != 0 || velocity.z != 0) {
  7396. collider._getResponse(position, velocity);
  7397. }
  7398. if (velocity.length() <= closeDistance) {
  7399. finalPosition.copyFrom(position);
  7400. return;
  7401. }
  7402. collider.retry++;
  7403. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  7404. };
  7405. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  7406. if (typeof maxCapacity === "undefined") { maxCapacity = 64; }
  7407. if (typeof maxDepth === "undefined") { maxDepth = 2; }
  7408. if (!this._selectionOctree) {
  7409. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  7410. }
  7411. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7412. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  7413. for (var index = 0; index < this.meshes.length; index++) {
  7414. var mesh = this.meshes[index];
  7415. mesh.computeWorldMatrix(true);
  7416. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  7417. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  7418. BABYLON.Tools.CheckExtends(minBox, min, max);
  7419. BABYLON.Tools.CheckExtends(maxBox, min, max);
  7420. }
  7421. this._selectionOctree.update(min, max, this.meshes);
  7422. return this._selectionOctree;
  7423. };
  7424. Scene.prototype.createPickingRay = function (x, y, world, camera) {
  7425. var engine = this._engine;
  7426. if (!camera) {
  7427. if (!this.activeCamera)
  7428. throw new Error("Active camera not set");
  7429. camera = this.activeCamera;
  7430. }
  7431. var cameraViewport = camera.viewport;
  7432. var viewport = cameraViewport.toGlobal(engine);
  7433. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  7434. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  7435. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  7436. };
  7437. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  7438. var pickingInfo = null;
  7439. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  7440. var mesh = this.meshes[meshIndex];
  7441. if (predicate) {
  7442. if (!predicate(mesh)) {
  7443. continue;
  7444. }
  7445. } else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  7446. continue;
  7447. }
  7448. var world = mesh.getWorldMatrix();
  7449. var ray = rayFunction(world);
  7450. var result = mesh.intersects(ray, fastCheck);
  7451. if (!result || !result.hit)
  7452. continue;
  7453. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  7454. continue;
  7455. pickingInfo = result;
  7456. if (fastCheck) {
  7457. break;
  7458. }
  7459. }
  7460. return pickingInfo || new BABYLON.PickingInfo();
  7461. };
  7462. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  7463. var _this = this;
  7464. return this._internalPick(function (world) {
  7465. return _this.createPickingRay(x, y, world, camera);
  7466. }, predicate, fastCheck);
  7467. };
  7468. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  7469. var _this = this;
  7470. return this._internalPick(function (world) {
  7471. if (!_this._pickWithRayInverseMatrix) {
  7472. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  7473. }
  7474. world.invertToRef(_this._pickWithRayInverseMatrix);
  7475. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  7476. }, predicate, fastCheck);
  7477. };
  7478. Scene.prototype.setPointerOverMesh = function (mesh) {
  7479. if (this._pointerOverMesh === mesh) {
  7480. return;
  7481. }
  7482. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  7483. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  7484. }
  7485. this._pointerOverMesh = mesh;
  7486. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  7487. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  7488. }
  7489. };
  7490. Scene.prototype.getPointerOverMesh = function () {
  7491. return this._pointerOverMesh;
  7492. };
  7493. Scene.prototype.getPhysicsEngine = function () {
  7494. return this._physicsEngine;
  7495. };
  7496. Scene.prototype.enablePhysics = function (gravity, plugin) {
  7497. if (this._physicsEngine) {
  7498. return true;
  7499. }
  7500. this._physicsEngine = new BABYLON.PhysicsEngine(plugin);
  7501. if (!this._physicsEngine.isSupported()) {
  7502. this._physicsEngine = null;
  7503. return false;
  7504. }
  7505. this._physicsEngine._initialize(gravity);
  7506. return true;
  7507. };
  7508. Scene.prototype.disablePhysicsEngine = function () {
  7509. if (!this._physicsEngine) {
  7510. return;
  7511. }
  7512. this._physicsEngine.dispose();
  7513. this._physicsEngine = undefined;
  7514. };
  7515. Scene.prototype.isPhysicsEnabled = function () {
  7516. return this._physicsEngine !== undefined;
  7517. };
  7518. Scene.prototype.setGravity = function (gravity) {
  7519. if (!this._physicsEngine) {
  7520. return;
  7521. }
  7522. this._physicsEngine._setGravity(gravity);
  7523. };
  7524. Scene.prototype.createCompoundImpostor = function (parts, options) {
  7525. if (parts.parts) {
  7526. options = parts;
  7527. parts = parts.parts;
  7528. }
  7529. if (!this._physicsEngine) {
  7530. return null;
  7531. }
  7532. for (var index = 0; index < parts.length; index++) {
  7533. var mesh = parts[index].mesh;
  7534. mesh._physicImpostor = parts[index].impostor;
  7535. mesh._physicsMass = options.mass / parts.length;
  7536. mesh._physicsFriction = options.friction;
  7537. mesh._physicRestitution = options.restitution;
  7538. }
  7539. return this._physicsEngine._registerMeshesAsCompound(parts, options);
  7540. };
  7541. Scene.prototype.deleteCompoundImpostor = function (compound) {
  7542. for (var index = 0; index < compound.parts.length; index++) {
  7543. var mesh = compound.parts[index].mesh;
  7544. mesh._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  7545. this._physicsEngine._unregisterMesh(mesh);
  7546. }
  7547. };
  7548. Scene.prototype._getByTags = function (list, tagsQuery) {
  7549. if (tagsQuery === undefined) {
  7550. return list;
  7551. }
  7552. var listByTags = [];
  7553. for (var i in list) {
  7554. var item = list[i];
  7555. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  7556. listByTags.push(item);
  7557. }
  7558. }
  7559. return listByTags;
  7560. };
  7561. Scene.prototype.getMeshesByTags = function (tagsQuery) {
  7562. return this._getByTags(this.meshes, tagsQuery);
  7563. };
  7564. Scene.prototype.getCamerasByTags = function (tagsQuery) {
  7565. return this._getByTags(this.cameras, tagsQuery);
  7566. };
  7567. Scene.prototype.getLightsByTags = function (tagsQuery) {
  7568. return this._getByTags(this.lights, tagsQuery);
  7569. };
  7570. Scene.prototype.getMaterialByTags = function (tagsQuery) {
  7571. return this._getByTags(this.materials, tagsQuery).concat(this._getByTags(this.multiMaterials, tagsQuery));
  7572. };
  7573. Scene.FOGMODE_NONE = 0;
  7574. Scene.FOGMODE_EXP = 1;
  7575. Scene.FOGMODE_EXP2 = 2;
  7576. Scene.FOGMODE_LINEAR = 3;
  7577. Scene.MinDeltaTime = 1.0;
  7578. Scene.MaxDeltaTime = 1000.0;
  7579. return Scene;
  7580. })();
  7581. BABYLON.Scene = Scene;
  7582. })(BABYLON || (BABYLON = {}));
  7583. var BABYLON;
  7584. (function (BABYLON) {
  7585. var VertexBuffer = (function () {
  7586. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride) {
  7587. if (engine instanceof BABYLON.Mesh) {
  7588. this._engine = engine.getScene().getEngine();
  7589. } else {
  7590. this._engine = engine;
  7591. }
  7592. this._updatable = updatable;
  7593. this._data = data;
  7594. if (!postponeInternalCreation) {
  7595. this.create();
  7596. }
  7597. this._kind = kind;
  7598. if (stride) {
  7599. this._strideSize = stride;
  7600. return;
  7601. }
  7602. switch (kind) {
  7603. case VertexBuffer.PositionKind:
  7604. this._strideSize = 3;
  7605. break;
  7606. case VertexBuffer.NormalKind:
  7607. this._strideSize = 3;
  7608. break;
  7609. case VertexBuffer.UVKind:
  7610. this._strideSize = 2;
  7611. break;
  7612. case VertexBuffer.UV2Kind:
  7613. this._strideSize = 2;
  7614. break;
  7615. case VertexBuffer.ColorKind:
  7616. this._strideSize = 4;
  7617. break;
  7618. case VertexBuffer.MatricesIndicesKind:
  7619. this._strideSize = 4;
  7620. break;
  7621. case VertexBuffer.MatricesWeightsKind:
  7622. this._strideSize = 4;
  7623. break;
  7624. }
  7625. }
  7626. VertexBuffer.prototype.isUpdatable = function () {
  7627. return this._updatable;
  7628. };
  7629. VertexBuffer.prototype.getData = function () {
  7630. return this._data;
  7631. };
  7632. VertexBuffer.prototype.getBuffer = function () {
  7633. return this._buffer;
  7634. };
  7635. VertexBuffer.prototype.getStrideSize = function () {
  7636. return this._strideSize;
  7637. };
  7638. VertexBuffer.prototype.create = function (data) {
  7639. if (!data && this._buffer) {
  7640. return;
  7641. }
  7642. data = data || this._data;
  7643. if (!this._buffer) {
  7644. if (this._updatable) {
  7645. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  7646. } else {
  7647. this._buffer = this._engine.createVertexBuffer(data);
  7648. }
  7649. }
  7650. if (this._updatable) {
  7651. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  7652. this._data = data;
  7653. }
  7654. };
  7655. VertexBuffer.prototype.update = function (data) {
  7656. this.create(data);
  7657. };
  7658. VertexBuffer.prototype.updateDirectly = function (data) {
  7659. if (!this._buffer) {
  7660. return;
  7661. }
  7662. if (this._updatable) {
  7663. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  7664. this._data = null;
  7665. }
  7666. };
  7667. VertexBuffer.prototype.dispose = function () {
  7668. if (!this._buffer) {
  7669. return;
  7670. }
  7671. if (this._engine._releaseBuffer(this._buffer)) {
  7672. this._buffer = null;
  7673. }
  7674. };
  7675. Object.defineProperty(VertexBuffer, "PositionKind", {
  7676. get: function () {
  7677. return VertexBuffer._PositionKind;
  7678. },
  7679. enumerable: true,
  7680. configurable: true
  7681. });
  7682. Object.defineProperty(VertexBuffer, "NormalKind", {
  7683. get: function () {
  7684. return VertexBuffer._NormalKind;
  7685. },
  7686. enumerable: true,
  7687. configurable: true
  7688. });
  7689. Object.defineProperty(VertexBuffer, "UVKind", {
  7690. get: function () {
  7691. return VertexBuffer._UVKind;
  7692. },
  7693. enumerable: true,
  7694. configurable: true
  7695. });
  7696. Object.defineProperty(VertexBuffer, "UV2Kind", {
  7697. get: function () {
  7698. return VertexBuffer._UV2Kind;
  7699. },
  7700. enumerable: true,
  7701. configurable: true
  7702. });
  7703. Object.defineProperty(VertexBuffer, "ColorKind", {
  7704. get: function () {
  7705. return VertexBuffer._ColorKind;
  7706. },
  7707. enumerable: true,
  7708. configurable: true
  7709. });
  7710. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  7711. get: function () {
  7712. return VertexBuffer._MatricesIndicesKind;
  7713. },
  7714. enumerable: true,
  7715. configurable: true
  7716. });
  7717. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  7718. get: function () {
  7719. return VertexBuffer._MatricesWeightsKind;
  7720. },
  7721. enumerable: true,
  7722. configurable: true
  7723. });
  7724. VertexBuffer._PositionKind = "position";
  7725. VertexBuffer._NormalKind = "normal";
  7726. VertexBuffer._UVKind = "uv";
  7727. VertexBuffer._UV2Kind = "uv2";
  7728. VertexBuffer._ColorKind = "color";
  7729. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  7730. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  7731. return VertexBuffer;
  7732. })();
  7733. BABYLON.VertexBuffer = VertexBuffer;
  7734. })(BABYLON || (BABYLON = {}));
  7735. var __extends = this.__extends || function (d, b) {
  7736. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  7737. function __() { this.constructor = d; }
  7738. __.prototype = b.prototype;
  7739. d.prototype = new __();
  7740. };
  7741. var BABYLON;
  7742. (function (BABYLON) {
  7743. var AbstractMesh = (function (_super) {
  7744. __extends(AbstractMesh, _super);
  7745. function AbstractMesh(name, scene) {
  7746. _super.call(this, name, scene);
  7747. this.position = new BABYLON.Vector3(0, 0, 0);
  7748. this.rotation = new BABYLON.Vector3(0, 0, 0);
  7749. this.scaling = new BABYLON.Vector3(1, 1, 1);
  7750. this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_NONE;
  7751. this.visibility = 1.0;
  7752. this.infiniteDistance = false;
  7753. this.isVisible = true;
  7754. this.isPickable = true;
  7755. this.showBoundingBox = false;
  7756. this.showSubMeshesBoundingBox = false;
  7757. this.onDispose = null;
  7758. this.checkCollisions = false;
  7759. this.isBlocker = false;
  7760. this.renderingGroupId = 0;
  7761. this.receiveShadows = false;
  7762. this.renderOutline = false;
  7763. this.outlineColor = BABYLON.Color3.Red();
  7764. this.outlineWidth = 0.02;
  7765. this.hasVertexAlpha = false;
  7766. this.useOctreeForRenderingSelection = true;
  7767. this.useOctreeForPicking = true;
  7768. this.useOctreeForCollisions = true;
  7769. this.layerMask = 0xFFFFFFFF;
  7770. this._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  7771. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  7772. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  7773. this._collider = new BABYLON.Collider();
  7774. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7775. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7776. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7777. this._localScaling = BABYLON.Matrix.Zero();
  7778. this._localRotation = BABYLON.Matrix.Zero();
  7779. this._localTranslation = BABYLON.Matrix.Zero();
  7780. this._localBillboard = BABYLON.Matrix.Zero();
  7781. this._localPivotScaling = BABYLON.Matrix.Zero();
  7782. this._localPivotScalingRotation = BABYLON.Matrix.Zero();
  7783. this._localWorld = BABYLON.Matrix.Zero();
  7784. this._worldMatrix = BABYLON.Matrix.Zero();
  7785. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  7786. this._absolutePosition = BABYLON.Vector3.Zero();
  7787. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  7788. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  7789. this._isDirty = false;
  7790. this._pivotMatrix = BABYLON.Matrix.Identity();
  7791. this._isDisposed = false;
  7792. this._renderId = 0;
  7793. this._intersectionsInProgress = new Array();
  7794. this._onAfterWorldMatrixUpdate = new Array();
  7795. scene.meshes.push(this);
  7796. }
  7797. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  7798. get: function () {
  7799. return AbstractMesh._BILLBOARDMODE_NONE;
  7800. },
  7801. enumerable: true,
  7802. configurable: true
  7803. });
  7804. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  7805. get: function () {
  7806. return AbstractMesh._BILLBOARDMODE_X;
  7807. },
  7808. enumerable: true,
  7809. configurable: true
  7810. });
  7811. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  7812. get: function () {
  7813. return AbstractMesh._BILLBOARDMODE_Y;
  7814. },
  7815. enumerable: true,
  7816. configurable: true
  7817. });
  7818. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  7819. get: function () {
  7820. return AbstractMesh._BILLBOARDMODE_Z;
  7821. },
  7822. enumerable: true,
  7823. configurable: true
  7824. });
  7825. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  7826. get: function () {
  7827. return AbstractMesh._BILLBOARDMODE_ALL;
  7828. },
  7829. enumerable: true,
  7830. configurable: true
  7831. });
  7832. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  7833. get: function () {
  7834. return false;
  7835. },
  7836. enumerable: true,
  7837. configurable: true
  7838. });
  7839. AbstractMesh.prototype.getLOD = function (camera) {
  7840. return this;
  7841. };
  7842. AbstractMesh.prototype.getTotalVertices = function () {
  7843. return 0;
  7844. };
  7845. AbstractMesh.prototype.getIndices = function () {
  7846. return null;
  7847. };
  7848. AbstractMesh.prototype.getVerticesData = function (kind) {
  7849. return null;
  7850. };
  7851. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  7852. return false;
  7853. };
  7854. AbstractMesh.prototype.getBoundingInfo = function () {
  7855. if (this._masterMesh) {
  7856. return this._masterMesh.getBoundingInfo();
  7857. }
  7858. if (!this._boundingInfo) {
  7859. this._updateBoundingInfo();
  7860. }
  7861. return this._boundingInfo;
  7862. };
  7863. AbstractMesh.prototype._preActivate = function () {
  7864. };
  7865. AbstractMesh.prototype._activate = function (renderId) {
  7866. this._renderId = renderId;
  7867. };
  7868. AbstractMesh.prototype.getWorldMatrix = function () {
  7869. if (this._masterMesh) {
  7870. return this._masterMesh.getWorldMatrix();
  7871. }
  7872. if (this._currentRenderId !== this.getScene().getRenderId()) {
  7873. this.computeWorldMatrix();
  7874. }
  7875. return this._worldMatrix;
  7876. };
  7877. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  7878. get: function () {
  7879. return this._worldMatrix;
  7880. },
  7881. enumerable: true,
  7882. configurable: true
  7883. });
  7884. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  7885. get: function () {
  7886. return this._absolutePosition;
  7887. },
  7888. enumerable: true,
  7889. configurable: true
  7890. });
  7891. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  7892. if (!this.rotationQuaternion) {
  7893. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  7894. this.rotation = BABYLON.Vector3.Zero();
  7895. }
  7896. if (!space || space == 0 /* LOCAL */) {
  7897. var rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  7898. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  7899. } else {
  7900. if (this.parent) {
  7901. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  7902. invertParentWorldMatrix.invert();
  7903. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  7904. }
  7905. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  7906. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  7907. }
  7908. };
  7909. AbstractMesh.prototype.translate = function (axis, distance, space) {
  7910. var displacementVector = axis.scale(distance);
  7911. if (!space || space == 0 /* LOCAL */) {
  7912. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  7913. this.setPositionWithLocalVector(tempV3);
  7914. } else {
  7915. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  7916. }
  7917. };
  7918. AbstractMesh.prototype.getAbsolutePosition = function () {
  7919. this.computeWorldMatrix();
  7920. return this._absolutePosition;
  7921. };
  7922. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  7923. if (!absolutePosition) {
  7924. return;
  7925. }
  7926. var absolutePositionX;
  7927. var absolutePositionY;
  7928. var absolutePositionZ;
  7929. if (absolutePosition.x === undefined) {
  7930. if (arguments.length < 3) {
  7931. return;
  7932. }
  7933. absolutePositionX = arguments[0];
  7934. absolutePositionY = arguments[1];
  7935. absolutePositionZ = arguments[2];
  7936. } else {
  7937. absolutePositionX = absolutePosition.x;
  7938. absolutePositionY = absolutePosition.y;
  7939. absolutePositionZ = absolutePosition.z;
  7940. }
  7941. if (this.parent) {
  7942. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  7943. invertParentWorldMatrix.invert();
  7944. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  7945. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  7946. } else {
  7947. this.position.x = absolutePositionX;
  7948. this.position.y = absolutePositionY;
  7949. this.position.z = absolutePositionZ;
  7950. }
  7951. };
  7952. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  7953. this._pivotMatrix = matrix;
  7954. this._cache.pivotMatrixUpdated = true;
  7955. };
  7956. AbstractMesh.prototype.getPivotMatrix = function () {
  7957. return this._pivotMatrix;
  7958. };
  7959. AbstractMesh.prototype._isSynchronized = function () {
  7960. if (this._isDirty) {
  7961. return false;
  7962. }
  7963. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  7964. return false;
  7965. if (this._cache.pivotMatrixUpdated) {
  7966. return false;
  7967. }
  7968. if (this.infiniteDistance) {
  7969. return false;
  7970. }
  7971. if (!this._cache.position.equals(this.position))
  7972. return false;
  7973. if (this.rotationQuaternion) {
  7974. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  7975. return false;
  7976. } else {
  7977. if (!this._cache.rotation.equals(this.rotation))
  7978. return false;
  7979. }
  7980. if (!this._cache.scaling.equals(this.scaling))
  7981. return false;
  7982. return true;
  7983. };
  7984. AbstractMesh.prototype._initCache = function () {
  7985. _super.prototype._initCache.call(this);
  7986. this._cache.localMatrixUpdated = false;
  7987. this._cache.position = BABYLON.Vector3.Zero();
  7988. this._cache.scaling = BABYLON.Vector3.Zero();
  7989. this._cache.rotation = BABYLON.Vector3.Zero();
  7990. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  7991. };
  7992. AbstractMesh.prototype.markAsDirty = function (property) {
  7993. if (property === "rotation") {
  7994. this.rotationQuaternion = null;
  7995. }
  7996. this._currentRenderId = Number.MAX_VALUE;
  7997. this._isDirty = true;
  7998. };
  7999. AbstractMesh.prototype._updateBoundingInfo = function () {
  8000. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  8001. this._boundingInfo._update(this.worldMatrixFromCache);
  8002. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  8003. };
  8004. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  8005. if (!this.subMeshes) {
  8006. return;
  8007. }
  8008. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  8009. var subMesh = this.subMeshes[subIndex];
  8010. subMesh.updateBoundingInfo(matrix);
  8011. }
  8012. };
  8013. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  8014. if (!force && (this._currentRenderId == this.getScene().getRenderId() || this.isSynchronized(true))) {
  8015. return this._worldMatrix;
  8016. }
  8017. this._cache.position.copyFrom(this.position);
  8018. this._cache.scaling.copyFrom(this.scaling);
  8019. this._cache.pivotMatrixUpdated = false;
  8020. this._currentRenderId = this.getScene().getRenderId();
  8021. this._isDirty = false;
  8022. BABYLON.Matrix.ScalingToRef(this.scaling.x, this.scaling.y, this.scaling.z, this._localScaling);
  8023. if (this.rotationQuaternion) {
  8024. this.rotationQuaternion.toRotationMatrix(this._localRotation);
  8025. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  8026. } else {
  8027. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._localRotation);
  8028. this._cache.rotation.copyFrom(this.rotation);
  8029. }
  8030. if (this.infiniteDistance && !this.parent) {
  8031. var camera = this.getScene().activeCamera;
  8032. var cameraWorldMatrix = camera.getWorldMatrix();
  8033. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  8034. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, this._localTranslation);
  8035. } else {
  8036. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._localTranslation);
  8037. }
  8038. this._pivotMatrix.multiplyToRef(this._localScaling, this._localPivotScaling);
  8039. this._localPivotScaling.multiplyToRef(this._localRotation, this._localPivotScalingRotation);
  8040. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  8041. var localPosition = this.position.clone();
  8042. var zero = this.getScene().activeCamera.position.clone();
  8043. if (this.parent && this.parent.position) {
  8044. localPosition.addInPlace(this.parent.position);
  8045. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, this._localTranslation);
  8046. }
  8047. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) === AbstractMesh.BILLBOARDMODE_ALL) {
  8048. zero = this.getScene().activeCamera.position;
  8049. } else {
  8050. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X)
  8051. zero.x = localPosition.x + BABYLON.Engine.Epsilon;
  8052. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y)
  8053. zero.y = localPosition.y + 0.001;
  8054. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z)
  8055. zero.z = localPosition.z + 0.001;
  8056. }
  8057. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), this._localBillboard);
  8058. this._localBillboard.m[12] = this._localBillboard.m[13] = this._localBillboard.m[14] = 0;
  8059. this._localBillboard.invert();
  8060. this._localPivotScalingRotation.multiplyToRef(this._localBillboard, this._localWorld);
  8061. this._rotateYByPI.multiplyToRef(this._localWorld, this._localPivotScalingRotation);
  8062. }
  8063. this._localPivotScalingRotation.multiplyToRef(this._localTranslation, this._localWorld);
  8064. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  8065. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  8066. } else {
  8067. this._worldMatrix.copyFrom(this._localWorld);
  8068. }
  8069. this._updateBoundingInfo();
  8070. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  8071. for (var callbackIndex = 0; callbackIndex < this._onAfterWorldMatrixUpdate.length; callbackIndex++) {
  8072. this._onAfterWorldMatrixUpdate[callbackIndex](this);
  8073. }
  8074. return this._worldMatrix;
  8075. };
  8076. /**
  8077. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  8078. * @param func: callback function to add
  8079. */
  8080. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  8081. this._onAfterWorldMatrixUpdate.push(func);
  8082. };
  8083. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  8084. var index = this._onAfterWorldMatrixUpdate.indexOf(func);
  8085. if (index > -1) {
  8086. this._onAfterWorldMatrixUpdate.splice(index, 1);
  8087. }
  8088. };
  8089. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  8090. this.computeWorldMatrix();
  8091. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  8092. };
  8093. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  8094. this.computeWorldMatrix();
  8095. var invLocalWorldMatrix = this._localWorld.clone();
  8096. invLocalWorldMatrix.invert();
  8097. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  8098. };
  8099. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  8100. this.computeWorldMatrix();
  8101. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  8102. };
  8103. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  8104. yawCor = yawCor || 0;
  8105. pitchCor = pitchCor || 0;
  8106. rollCor = rollCor || 0;
  8107. var dv = targetPoint.subtract(this.position);
  8108. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  8109. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  8110. var pitch = Math.atan2(dv.y, len);
  8111. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  8112. };
  8113. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  8114. if (!this._boundingInfo.isInFrustum(frustumPlanes)) {
  8115. return false;
  8116. }
  8117. return true;
  8118. };
  8119. AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
  8120. if (!camera) {
  8121. camera = this.getScene().activeCamera;
  8122. }
  8123. var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
  8124. if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
  8125. return false;
  8126. }
  8127. return true;
  8128. };
  8129. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  8130. if (!this._boundingInfo || !mesh._boundingInfo) {
  8131. return false;
  8132. }
  8133. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  8134. };
  8135. AbstractMesh.prototype.intersectsPoint = function (point) {
  8136. if (!this._boundingInfo) {
  8137. return false;
  8138. }
  8139. return this._boundingInfo.intersectsPoint(point);
  8140. };
  8141. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  8142. var physicsEngine = this.getScene().getPhysicsEngine();
  8143. if (!physicsEngine) {
  8144. return;
  8145. }
  8146. if (impostor.impostor) {
  8147. options = impostor;
  8148. impostor = impostor.impostor;
  8149. }
  8150. impostor = impostor || BABYLON.PhysicsEngine.NoImpostor;
  8151. if (impostor === BABYLON.PhysicsEngine.NoImpostor) {
  8152. physicsEngine._unregisterMesh(this);
  8153. return;
  8154. }
  8155. options.mass = options.mass || 0;
  8156. options.friction = options.friction || 0.2;
  8157. options.restitution = options.restitution || 0.2;
  8158. this._physicImpostor = impostor;
  8159. this._physicsMass = options.mass;
  8160. this._physicsFriction = options.friction;
  8161. this._physicRestitution = options.restitution;
  8162. physicsEngine._registerMesh(this, impostor, options);
  8163. };
  8164. AbstractMesh.prototype.getPhysicsImpostor = function () {
  8165. if (!this._physicImpostor) {
  8166. return BABYLON.PhysicsEngine.NoImpostor;
  8167. }
  8168. return this._physicImpostor;
  8169. };
  8170. AbstractMesh.prototype.getPhysicsMass = function () {
  8171. if (!this._physicsMass) {
  8172. return 0;
  8173. }
  8174. return this._physicsMass;
  8175. };
  8176. AbstractMesh.prototype.getPhysicsFriction = function () {
  8177. if (!this._physicsFriction) {
  8178. return 0;
  8179. }
  8180. return this._physicsFriction;
  8181. };
  8182. AbstractMesh.prototype.getPhysicsRestitution = function () {
  8183. if (!this._physicRestitution) {
  8184. return 0;
  8185. }
  8186. return this._physicRestitution;
  8187. };
  8188. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  8189. if (!camera) {
  8190. camera = this.getScene().activeCamera;
  8191. }
  8192. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  8193. };
  8194. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  8195. if (!camera) {
  8196. camera = this.getScene().activeCamera;
  8197. }
  8198. return this.absolutePosition.subtract(camera.position);
  8199. };
  8200. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  8201. if (!this._physicImpostor) {
  8202. return;
  8203. }
  8204. this.getScene().getPhysicsEngine()._applyImpulse(this, force, contactPoint);
  8205. };
  8206. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  8207. if (!this._physicImpostor) {
  8208. return;
  8209. }
  8210. this.getScene().getPhysicsEngine()._createLink(this, otherMesh, pivot1, pivot2, options);
  8211. };
  8212. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  8213. if (!this._physicImpostor) {
  8214. return;
  8215. }
  8216. this.getScene().getPhysicsEngine()._updateBodyPosition(this);
  8217. };
  8218. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  8219. var globalPosition = this.getAbsolutePosition();
  8220. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  8221. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  8222. this._collider.radius = this.ellipsoid;
  8223. this.getScene()._getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this._newPositionForCollisions, this);
  8224. this._newPositionForCollisions.subtractToRef(this._oldPositionForCollisions, this._diffPositionForCollisions);
  8225. if (this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  8226. this.position.addInPlace(this._diffPositionForCollisions);
  8227. }
  8228. };
  8229. /**
  8230. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  8231. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  8232. */
  8233. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  8234. if (typeof maxCapacity === "undefined") { maxCapacity = 64; }
  8235. if (typeof maxDepth === "undefined") { maxDepth = 2; }
  8236. if (!this._submeshesOctree) {
  8237. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  8238. }
  8239. this.computeWorldMatrix(true);
  8240. var bbox = this.getBoundingInfo().boundingBox;
  8241. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  8242. return this._submeshesOctree;
  8243. };
  8244. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  8245. this._generatePointsArray();
  8246. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  8247. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  8248. subMesh._lastColliderWorldVertices = [];
  8249. subMesh._trianglePlanes = [];
  8250. var start = subMesh.verticesStart;
  8251. var end = (subMesh.verticesStart + subMesh.verticesCount);
  8252. for (var i = start; i < end; i++) {
  8253. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  8254. }
  8255. }
  8256. collider._collide(subMesh, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart);
  8257. };
  8258. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  8259. var subMeshes;
  8260. var len;
  8261. if (this._submeshesOctree && this.useOctreeForCollisions) {
  8262. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  8263. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  8264. len = intersections.length;
  8265. subMeshes = intersections.data;
  8266. } else {
  8267. subMeshes = this.subMeshes;
  8268. len = subMeshes.length;
  8269. }
  8270. for (var index = 0; index < len; index++) {
  8271. var subMesh = subMeshes[index];
  8272. if (len > 1 && !subMesh._checkCollision(collider))
  8273. continue;
  8274. this._collideForSubMesh(subMesh, transformMatrix, collider);
  8275. }
  8276. };
  8277. AbstractMesh.prototype._checkCollision = function (collider) {
  8278. if (!this._boundingInfo._checkCollision(collider))
  8279. return;
  8280. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  8281. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  8282. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  8283. };
  8284. AbstractMesh.prototype._generatePointsArray = function () {
  8285. return false;
  8286. };
  8287. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  8288. var pickingInfo = new BABYLON.PickingInfo();
  8289. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  8290. return pickingInfo;
  8291. }
  8292. if (!this._generatePointsArray()) {
  8293. return pickingInfo;
  8294. }
  8295. var intersectInfo = null;
  8296. var subMeshes;
  8297. var len;
  8298. if (this._submeshesOctree && this.useOctreeForPicking) {
  8299. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  8300. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  8301. len = intersections.length;
  8302. subMeshes = intersections.data;
  8303. } else {
  8304. subMeshes = this.subMeshes;
  8305. len = subMeshes.length;
  8306. }
  8307. for (var index = 0; index < len; index++) {
  8308. var subMesh = subMeshes[index];
  8309. if (len > 1 && !subMesh.canIntersects(ray))
  8310. continue;
  8311. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  8312. if (currentIntersectInfo) {
  8313. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  8314. intersectInfo = currentIntersectInfo;
  8315. if (fastCheck) {
  8316. break;
  8317. }
  8318. }
  8319. }
  8320. }
  8321. if (intersectInfo) {
  8322. var world = this.getWorldMatrix();
  8323. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  8324. var direction = ray.direction.clone();
  8325. direction.normalize();
  8326. direction = direction.scale(intersectInfo.distance);
  8327. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  8328. var pickedPoint = worldOrigin.add(worldDirection);
  8329. pickingInfo.hit = true;
  8330. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  8331. pickingInfo.pickedPoint = pickedPoint;
  8332. pickingInfo.pickedMesh = this;
  8333. pickingInfo.bu = intersectInfo.bu;
  8334. pickingInfo.bv = intersectInfo.bv;
  8335. pickingInfo.faceId = intersectInfo.faceId;
  8336. return pickingInfo;
  8337. }
  8338. return pickingInfo;
  8339. };
  8340. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  8341. return null;
  8342. };
  8343. AbstractMesh.prototype.releaseSubMeshes = function () {
  8344. if (this.subMeshes) {
  8345. while (this.subMeshes.length) {
  8346. this.subMeshes[0].dispose();
  8347. }
  8348. } else {
  8349. this.subMeshes = new Array();
  8350. }
  8351. };
  8352. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  8353. if (this.getPhysicsImpostor() != BABYLON.PhysicsEngine.NoImpostor) {
  8354. this.setPhysicsState(BABYLON.PhysicsEngine.NoImpostor);
  8355. }
  8356. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  8357. var other = this._intersectionsInProgress[index];
  8358. var pos = other._intersectionsInProgress.indexOf(this);
  8359. other._intersectionsInProgress.splice(pos, 1);
  8360. }
  8361. this._intersectionsInProgress = [];
  8362. this.releaseSubMeshes();
  8363. var index = this.getScene().meshes.indexOf(this);
  8364. if (index != -1) {
  8365. this.getScene().meshes.splice(index, 1);
  8366. }
  8367. if (!doNotRecurse) {
  8368. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  8369. if (this.getScene().particleSystems[index].emitter == this) {
  8370. this.getScene().particleSystems[index].dispose();
  8371. index--;
  8372. }
  8373. }
  8374. var objects = this.getScene().meshes.slice(0);
  8375. for (index = 0; index < objects.length; index++) {
  8376. if (objects[index].parent == this) {
  8377. objects[index].dispose();
  8378. }
  8379. }
  8380. } else {
  8381. for (index = 0; index < this.getScene().meshes.length; index++) {
  8382. var obj = this.getScene().meshes[index];
  8383. if (obj.parent === this) {
  8384. obj.parent = null;
  8385. obj.computeWorldMatrix(true);
  8386. }
  8387. }
  8388. }
  8389. this._onAfterWorldMatrixUpdate = [];
  8390. this._isDisposed = true;
  8391. if (this.onDispose) {
  8392. this.onDispose();
  8393. }
  8394. };
  8395. AbstractMesh._BILLBOARDMODE_NONE = 0;
  8396. AbstractMesh._BILLBOARDMODE_X = 1;
  8397. AbstractMesh._BILLBOARDMODE_Y = 2;
  8398. AbstractMesh._BILLBOARDMODE_Z = 4;
  8399. AbstractMesh._BILLBOARDMODE_ALL = 7;
  8400. return AbstractMesh;
  8401. })(BABYLON.Node);
  8402. BABYLON.AbstractMesh = AbstractMesh;
  8403. })(BABYLON || (BABYLON = {}));
  8404. var __extends = this.__extends || function (d, b) {
  8405. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  8406. function __() { this.constructor = d; }
  8407. __.prototype = b.prototype;
  8408. d.prototype = new __();
  8409. };
  8410. var BABYLON;
  8411. (function (BABYLON) {
  8412. var _InstancesBatch = (function () {
  8413. function _InstancesBatch() {
  8414. this.mustReturn = false;
  8415. this.visibleInstances = new Array();
  8416. this.renderSelf = new Array();
  8417. }
  8418. return _InstancesBatch;
  8419. })();
  8420. BABYLON._InstancesBatch = _InstancesBatch;
  8421. var Mesh = (function (_super) {
  8422. __extends(Mesh, _super);
  8423. function Mesh(name, scene) {
  8424. _super.call(this, name, scene);
  8425. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  8426. this.instances = new Array();
  8427. this._LODLevels = new Array();
  8428. this._onBeforeRenderCallbacks = new Array();
  8429. this._onAfterRenderCallbacks = new Array();
  8430. this._visibleInstances = {};
  8431. this._renderIdForInstances = new Array();
  8432. this._batchCache = new _InstancesBatch();
  8433. this._instancesBufferSize = 32 * 16 * 4;
  8434. }
  8435. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  8436. get: function () {
  8437. return this._LODLevels.length > 0;
  8438. },
  8439. enumerable: true,
  8440. configurable: true
  8441. });
  8442. Mesh.prototype._sortLODLevels = function () {
  8443. this._LODLevels.sort(function (a, b) {
  8444. if (a.distance < b.distance) {
  8445. return 1;
  8446. }
  8447. if (a.distance > b.distance) {
  8448. return -1;
  8449. }
  8450. return 0;
  8451. });
  8452. };
  8453. Mesh.prototype.addLODLevel = function (distance, mesh) {
  8454. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  8455. this._LODLevels.push(level);
  8456. if (mesh) {
  8457. mesh._masterMesh = this;
  8458. }
  8459. this._sortLODLevels();
  8460. return this;
  8461. };
  8462. Mesh.prototype.removeLODLevel = function (mesh) {
  8463. for (var index = 0; index < this._LODLevels.length; index++) {
  8464. if (this._LODLevels[index].mesh === mesh) {
  8465. this._LODLevels.splice(index, 1);
  8466. if (mesh) {
  8467. mesh._masterMesh = null;
  8468. }
  8469. }
  8470. }
  8471. this._sortLODLevels();
  8472. return this;
  8473. };
  8474. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  8475. if (!this._LODLevels || this._LODLevels.length === 0) {
  8476. return this;
  8477. }
  8478. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.position).length();
  8479. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  8480. return this;
  8481. }
  8482. for (var index = 0; index < this._LODLevels.length; index++) {
  8483. var level = this._LODLevels[index];
  8484. if (level.distance < distanceToCamera) {
  8485. if (level.mesh) {
  8486. level.mesh._preActivate();
  8487. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  8488. }
  8489. return level.mesh;
  8490. }
  8491. }
  8492. return this;
  8493. };
  8494. Object.defineProperty(Mesh.prototype, "geometry", {
  8495. get: function () {
  8496. return this._geometry;
  8497. },
  8498. enumerable: true,
  8499. configurable: true
  8500. });
  8501. Mesh.prototype.getTotalVertices = function () {
  8502. if (!this._geometry) {
  8503. return 0;
  8504. }
  8505. return this._geometry.getTotalVertices();
  8506. };
  8507. Mesh.prototype.getVerticesData = function (kind) {
  8508. if (!this._geometry) {
  8509. return null;
  8510. }
  8511. return this._geometry.getVerticesData(kind);
  8512. };
  8513. Mesh.prototype.getVertexBuffer = function (kind) {
  8514. if (!this._geometry) {
  8515. return undefined;
  8516. }
  8517. return this._geometry.getVertexBuffer(kind);
  8518. };
  8519. Mesh.prototype.isVerticesDataPresent = function (kind) {
  8520. if (!this._geometry) {
  8521. if (this._delayInfo) {
  8522. return this._delayInfo.indexOf(kind) !== -1;
  8523. }
  8524. return false;
  8525. }
  8526. return this._geometry.isVerticesDataPresent(kind);
  8527. };
  8528. Mesh.prototype.getVerticesDataKinds = function () {
  8529. if (!this._geometry) {
  8530. var result = [];
  8531. if (this._delayInfo) {
  8532. for (var kind in this._delayInfo) {
  8533. result.push(kind);
  8534. }
  8535. }
  8536. return result;
  8537. }
  8538. return this._geometry.getVerticesDataKinds();
  8539. };
  8540. Mesh.prototype.getTotalIndices = function () {
  8541. if (!this._geometry) {
  8542. return 0;
  8543. }
  8544. return this._geometry.getTotalIndices();
  8545. };
  8546. Mesh.prototype.getIndices = function () {
  8547. if (!this._geometry) {
  8548. return [];
  8549. }
  8550. return this._geometry.getIndices();
  8551. };
  8552. Object.defineProperty(Mesh.prototype, "isBlocked", {
  8553. get: function () {
  8554. return this._masterMesh !== null && this._masterMesh !== undefined;
  8555. },
  8556. enumerable: true,
  8557. configurable: true
  8558. });
  8559. Mesh.prototype.isReady = function () {
  8560. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  8561. return false;
  8562. }
  8563. return _super.prototype.isReady.call(this);
  8564. };
  8565. Mesh.prototype.isDisposed = function () {
  8566. return this._isDisposed;
  8567. };
  8568. Mesh.prototype._preActivate = function () {
  8569. var sceneRenderId = this.getScene().getRenderId();
  8570. if (this._preActivateId == sceneRenderId) {
  8571. return;
  8572. }
  8573. this._preActivateId = sceneRenderId;
  8574. this._visibleInstances = null;
  8575. };
  8576. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  8577. if (!this._visibleInstances) {
  8578. this._visibleInstances = {};
  8579. this._visibleInstances.defaultRenderId = renderId;
  8580. this._visibleInstances.selfDefaultRenderId = this._renderId;
  8581. }
  8582. if (!this._visibleInstances[renderId]) {
  8583. this._visibleInstances[renderId] = new Array();
  8584. }
  8585. this._visibleInstances[renderId].push(instance);
  8586. };
  8587. Mesh.prototype.refreshBoundingInfo = function () {
  8588. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  8589. if (data) {
  8590. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  8591. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  8592. }
  8593. if (this.subMeshes) {
  8594. for (var index = 0; index < this.subMeshes.length; index++) {
  8595. this.subMeshes[index].refreshBoundingInfo();
  8596. }
  8597. }
  8598. this._updateBoundingInfo();
  8599. };
  8600. Mesh.prototype._createGlobalSubMesh = function () {
  8601. var totalVertices = this.getTotalVertices();
  8602. if (!totalVertices || !this.getIndices()) {
  8603. return null;
  8604. }
  8605. this.releaseSubMeshes();
  8606. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  8607. };
  8608. Mesh.prototype.subdivide = function (count) {
  8609. if (count < 1) {
  8610. return;
  8611. }
  8612. var totalIndices = this.getTotalIndices();
  8613. var subdivisionSize = (totalIndices / count) | 0;
  8614. var offset = 0;
  8615. while (subdivisionSize % 3 != 0) {
  8616. subdivisionSize++;
  8617. }
  8618. this.releaseSubMeshes();
  8619. for (var index = 0; index < count; index++) {
  8620. if (offset >= totalIndices) {
  8621. break;
  8622. }
  8623. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  8624. offset += subdivisionSize;
  8625. }
  8626. this.synchronizeInstances();
  8627. };
  8628. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  8629. if (kind instanceof Array) {
  8630. var temp = data;
  8631. data = kind;
  8632. kind = temp;
  8633. BABYLON.Tools.Warn("Deprecated usage of setVerticesData detected (since v1.12). Current signature is setVerticesData(kind, data, updatable).");
  8634. }
  8635. if (!this._geometry) {
  8636. var vertexData = new BABYLON.VertexData();
  8637. vertexData.set(data, kind);
  8638. var scene = this.getScene();
  8639. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  8640. } else {
  8641. this._geometry.setVerticesData(kind, data, updatable, stride);
  8642. }
  8643. };
  8644. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  8645. if (!this._geometry) {
  8646. return;
  8647. }
  8648. if (!makeItUnique) {
  8649. this._geometry.updateVerticesData(kind, data, updateExtends);
  8650. } else {
  8651. this.makeGeometryUnique();
  8652. this.updateVerticesData(kind, data, updateExtends, false);
  8653. }
  8654. };
  8655. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, makeItUnique) {
  8656. if (!this._geometry) {
  8657. return;
  8658. }
  8659. if (!makeItUnique) {
  8660. this._geometry.updateVerticesDataDirectly(kind, data);
  8661. } else {
  8662. this.makeGeometryUnique();
  8663. this.updateVerticesDataDirectly(kind, data, false);
  8664. }
  8665. };
  8666. Mesh.prototype.makeGeometryUnique = function () {
  8667. if (!this._geometry) {
  8668. return;
  8669. }
  8670. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  8671. geometry.applyToMesh(this);
  8672. };
  8673. Mesh.prototype.setIndices = function (indices) {
  8674. if (!this._geometry) {
  8675. var vertexData = new BABYLON.VertexData();
  8676. vertexData.indices = indices;
  8677. var scene = this.getScene();
  8678. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  8679. } else {
  8680. this._geometry.setIndices(indices);
  8681. }
  8682. };
  8683. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  8684. var engine = this.getScene().getEngine();
  8685. var indexToBind;
  8686. switch (fillMode) {
  8687. case BABYLON.Material.PointFillMode:
  8688. indexToBind = null;
  8689. break;
  8690. case BABYLON.Material.WireFrameFillMode:
  8691. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  8692. break;
  8693. default:
  8694. case BABYLON.Material.TriangleFillMode:
  8695. indexToBind = this._geometry.getIndexBuffer();
  8696. break;
  8697. }
  8698. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  8699. };
  8700. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  8701. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  8702. return;
  8703. }
  8704. var engine = this.getScene().getEngine();
  8705. switch (fillMode) {
  8706. case BABYLON.Material.PointFillMode:
  8707. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  8708. break;
  8709. case BABYLON.Material.WireFrameFillMode:
  8710. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  8711. break;
  8712. default:
  8713. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  8714. }
  8715. };
  8716. Mesh.prototype.registerBeforeRender = function (func) {
  8717. this._onBeforeRenderCallbacks.push(func);
  8718. };
  8719. Mesh.prototype.unregisterBeforeRender = function (func) {
  8720. var index = this._onBeforeRenderCallbacks.indexOf(func);
  8721. if (index > -1) {
  8722. this._onBeforeRenderCallbacks.splice(index, 1);
  8723. }
  8724. };
  8725. Mesh.prototype.registerAfterRender = function (func) {
  8726. this._onAfterRenderCallbacks.push(func);
  8727. };
  8728. Mesh.prototype.unregisterAfterRender = function (func) {
  8729. var index = this._onAfterRenderCallbacks.indexOf(func);
  8730. if (index > -1) {
  8731. this._onAfterRenderCallbacks.splice(index, 1);
  8732. }
  8733. };
  8734. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  8735. var scene = this.getScene();
  8736. this._batchCache.mustReturn = false;
  8737. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  8738. this._batchCache.visibleInstances[subMeshId] = null;
  8739. if (this._visibleInstances) {
  8740. var currentRenderId = scene.getRenderId();
  8741. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  8742. var selfRenderId = this._renderId;
  8743. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  8744. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  8745. currentRenderId = this._visibleInstances.defaultRenderId;
  8746. selfRenderId = this._visibleInstances.selfDefaultRenderId;
  8747. }
  8748. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  8749. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  8750. this._batchCache.mustReturn = true;
  8751. return this._batchCache;
  8752. }
  8753. if (currentRenderId !== selfRenderId) {
  8754. this._batchCache.renderSelf[subMeshId] = false;
  8755. }
  8756. }
  8757. this._renderIdForInstances[subMeshId] = currentRenderId;
  8758. }
  8759. return this._batchCache;
  8760. };
  8761. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  8762. var visibleInstances = batch.visibleInstances[subMesh._id];
  8763. var matricesCount = visibleInstances.length + 1;
  8764. var bufferSize = matricesCount * 16 * 4;
  8765. while (this._instancesBufferSize < bufferSize) {
  8766. this._instancesBufferSize *= 2;
  8767. }
  8768. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  8769. if (this._worldMatricesInstancesBuffer) {
  8770. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  8771. }
  8772. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  8773. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  8774. }
  8775. var offset = 0;
  8776. var instancesCount = 0;
  8777. var world = this.getWorldMatrix();
  8778. if (batch.renderSelf[subMesh._id]) {
  8779. world.copyToArray(this._worldMatricesInstancesArray, offset);
  8780. offset += 16;
  8781. instancesCount++;
  8782. }
  8783. if (visibleInstances) {
  8784. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  8785. var instance = visibleInstances[instanceIndex];
  8786. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  8787. offset += 16;
  8788. instancesCount++;
  8789. }
  8790. }
  8791. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  8792. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  8793. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  8794. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  8795. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  8796. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  8797. this._draw(subMesh, fillMode, instancesCount);
  8798. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  8799. };
  8800. Mesh.prototype.render = function (subMesh) {
  8801. var scene = this.getScene();
  8802. var batch = this._getInstancesRenderList(subMesh._id);
  8803. if (batch.mustReturn) {
  8804. return;
  8805. }
  8806. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  8807. return;
  8808. }
  8809. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  8810. this._onBeforeRenderCallbacks[callbackIndex]();
  8811. }
  8812. var engine = scene.getEngine();
  8813. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  8814. var effectiveMaterial = subMesh.getMaterial();
  8815. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  8816. return;
  8817. }
  8818. var savedDepthWrite = engine.getDepthWrite();
  8819. if (this.renderOutline) {
  8820. engine.setDepthWrite(false);
  8821. scene.getOutlineRenderer().render(subMesh, batch);
  8822. }
  8823. effectiveMaterial._preBind();
  8824. var effect = effectiveMaterial.getEffect();
  8825. var fillMode = engine.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode;
  8826. this._bind(subMesh, effect, fillMode);
  8827. var world = this.getWorldMatrix();
  8828. effectiveMaterial.bind(world, this);
  8829. if (hardwareInstancedRendering) {
  8830. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  8831. } else {
  8832. if (batch.renderSelf[subMesh._id]) {
  8833. this._draw(subMesh, fillMode);
  8834. }
  8835. if (batch.visibleInstances[subMesh._id]) {
  8836. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  8837. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  8838. world = instance.getWorldMatrix();
  8839. effectiveMaterial.bindOnlyWorldMatrix(world);
  8840. this._draw(subMesh, fillMode);
  8841. }
  8842. }
  8843. }
  8844. effectiveMaterial.unbind();
  8845. if (this.renderOutline && savedDepthWrite) {
  8846. engine.setDepthWrite(true);
  8847. engine.setColorWrite(false);
  8848. scene.getOutlineRenderer().render(subMesh, batch);
  8849. engine.setColorWrite(true);
  8850. }
  8851. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  8852. this._onAfterRenderCallbacks[callbackIndex]();
  8853. }
  8854. };
  8855. Mesh.prototype.getEmittedParticleSystems = function () {
  8856. var results = new Array();
  8857. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  8858. var particleSystem = this.getScene().particleSystems[index];
  8859. if (particleSystem.emitter === this) {
  8860. results.push(particleSystem);
  8861. }
  8862. }
  8863. return results;
  8864. };
  8865. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  8866. var results = new Array();
  8867. var descendants = this.getDescendants();
  8868. descendants.push(this);
  8869. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  8870. var particleSystem = this.getScene().particleSystems[index];
  8871. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  8872. results.push(particleSystem);
  8873. }
  8874. }
  8875. return results;
  8876. };
  8877. Mesh.prototype.getChildren = function () {
  8878. var results = [];
  8879. for (var index = 0; index < this.getScene().meshes.length; index++) {
  8880. var mesh = this.getScene().meshes[index];
  8881. if (mesh.parent == this) {
  8882. results.push(mesh);
  8883. }
  8884. }
  8885. return results;
  8886. };
  8887. Mesh.prototype._checkDelayState = function () {
  8888. var _this = this;
  8889. var that = this;
  8890. var scene = this.getScene();
  8891. if (this._geometry) {
  8892. this._geometry.load(scene);
  8893. } else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  8894. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  8895. scene._addPendingData(that);
  8896. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1) ? true : false;
  8897. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  8898. if (data instanceof ArrayBuffer) {
  8899. _this._delayLoadingFunction(data, _this);
  8900. } else {
  8901. _this._delayLoadingFunction(JSON.parse(data), _this);
  8902. }
  8903. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  8904. scene._removePendingData(_this);
  8905. }, function () {
  8906. }, scene.database, getBinaryData);
  8907. }
  8908. };
  8909. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  8910. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  8911. return false;
  8912. }
  8913. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  8914. return false;
  8915. }
  8916. this._checkDelayState();
  8917. return true;
  8918. };
  8919. Mesh.prototype.setMaterialByID = function (id) {
  8920. var materials = this.getScene().materials;
  8921. for (var index = 0; index < materials.length; index++) {
  8922. if (materials[index].id == id) {
  8923. this.material = materials[index];
  8924. return;
  8925. }
  8926. }
  8927. var multiMaterials = this.getScene().multiMaterials;
  8928. for (index = 0; index < multiMaterials.length; index++) {
  8929. if (multiMaterials[index].id == id) {
  8930. this.material = multiMaterials[index];
  8931. return;
  8932. }
  8933. }
  8934. };
  8935. Mesh.prototype.getAnimatables = function () {
  8936. var results = [];
  8937. if (this.material) {
  8938. results.push(this.material);
  8939. }
  8940. if (this.skeleton) {
  8941. results.push(this.skeleton);
  8942. }
  8943. return results;
  8944. };
  8945. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  8946. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  8947. return;
  8948. }
  8949. this._resetPointsArrayCache();
  8950. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  8951. var temp = [];
  8952. for (var index = 0; index < data.length; index += 3) {
  8953. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  8954. }
  8955. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  8956. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  8957. return;
  8958. }
  8959. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  8960. for (index = 0; index < data.length; index += 3) {
  8961. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  8962. }
  8963. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  8964. };
  8965. Mesh.prototype._resetPointsArrayCache = function () {
  8966. this._positions = null;
  8967. };
  8968. Mesh.prototype._generatePointsArray = function () {
  8969. if (this._positions)
  8970. return true;
  8971. this._positions = [];
  8972. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  8973. if (!data) {
  8974. return false;
  8975. }
  8976. for (var index = 0; index < data.length; index += 3) {
  8977. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  8978. }
  8979. return true;
  8980. };
  8981. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  8982. var result = new BABYLON.Mesh(name, this.getScene());
  8983. this._geometry.applyToMesh(result);
  8984. BABYLON.Tools.DeepCopy(this, result, ["name", "material", "skeleton"], []);
  8985. result.material = this.material;
  8986. if (newParent) {
  8987. result.parent = newParent;
  8988. }
  8989. if (!doNotCloneChildren) {
  8990. for (var index = 0; index < this.getScene().meshes.length; index++) {
  8991. var mesh = this.getScene().meshes[index];
  8992. if (mesh.parent == this) {
  8993. mesh.clone(mesh.name, result);
  8994. }
  8995. }
  8996. }
  8997. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  8998. var system = this.getScene().particleSystems[index];
  8999. if (system.emitter == this) {
  9000. system.clone(system.name, result);
  9001. }
  9002. }
  9003. result.computeWorldMatrix(true);
  9004. return result;
  9005. };
  9006. Mesh.prototype.dispose = function (doNotRecurse) {
  9007. if (this._geometry) {
  9008. this._geometry.releaseForMesh(this, true);
  9009. }
  9010. if (this._worldMatricesInstancesBuffer) {
  9011. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  9012. this._worldMatricesInstancesBuffer = null;
  9013. }
  9014. while (this.instances.length) {
  9015. this.instances[0].dispose();
  9016. }
  9017. _super.prototype.dispose.call(this, doNotRecurse);
  9018. };
  9019. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight) {
  9020. var _this = this;
  9021. var scene = this.getScene();
  9022. var onload = function (img) {
  9023. var canvas = document.createElement("canvas");
  9024. var context = canvas.getContext("2d");
  9025. var heightMapWidth = img.width;
  9026. var heightMapHeight = img.height;
  9027. canvas.width = heightMapWidth;
  9028. canvas.height = heightMapHeight;
  9029. context.drawImage(img, 0, 0);
  9030. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  9031. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  9032. };
  9033. BABYLON.Tools.LoadImage(url, onload, function () {
  9034. }, scene.database);
  9035. };
  9036. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  9037. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  9038. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  9039. return;
  9040. }
  9041. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  9042. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  9043. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  9044. var position = BABYLON.Vector3.Zero();
  9045. var normal = BABYLON.Vector3.Zero();
  9046. var uv = BABYLON.Vector2.Zero();
  9047. for (var index = 0; index < positions.length; index += 3) {
  9048. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  9049. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  9050. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  9051. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  9052. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  9053. var pos = (u + v * heightMapWidth) * 4;
  9054. var r = buffer[pos] / 255.0;
  9055. var g = buffer[pos + 1] / 255.0;
  9056. var b = buffer[pos + 2] / 255.0;
  9057. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  9058. normal.normalize();
  9059. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  9060. position = position.add(normal);
  9061. position.toArray(positions, index);
  9062. }
  9063. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  9064. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  9065. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  9066. };
  9067. Mesh.prototype.convertToFlatShadedMesh = function () {
  9068. var kinds = this.getVerticesDataKinds();
  9069. var vbs = [];
  9070. var data = [];
  9071. var newdata = [];
  9072. var updatableNormals = false;
  9073. for (var kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  9074. var kind = kinds[kindIndex];
  9075. var vertexBuffer = this.getVertexBuffer(kind);
  9076. if (kind === BABYLON.VertexBuffer.NormalKind) {
  9077. updatableNormals = vertexBuffer.isUpdatable();
  9078. kinds.splice(kindIndex, 1);
  9079. kindIndex--;
  9080. continue;
  9081. }
  9082. vbs[kind] = vertexBuffer;
  9083. data[kind] = vbs[kind].getData();
  9084. newdata[kind] = [];
  9085. }
  9086. var previousSubmeshes = this.subMeshes.slice(0);
  9087. var indices = this.getIndices();
  9088. var totalIndices = this.getTotalIndices();
  9089. for (index = 0; index < totalIndices; index++) {
  9090. var vertexIndex = indices[index];
  9091. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  9092. kind = kinds[kindIndex];
  9093. var stride = vbs[kind].getStrideSize();
  9094. for (var offset = 0; offset < stride; offset++) {
  9095. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  9096. }
  9097. }
  9098. }
  9099. var normals = [];
  9100. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  9101. for (var index = 0; index < totalIndices; index += 3) {
  9102. indices[index] = index;
  9103. indices[index + 1] = index + 1;
  9104. indices[index + 2] = index + 2;
  9105. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  9106. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  9107. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  9108. var p1p2 = p1.subtract(p2);
  9109. var p3p2 = p3.subtract(p2);
  9110. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  9111. for (var localIndex = 0; localIndex < 3; localIndex++) {
  9112. normals.push(normal.x);
  9113. normals.push(normal.y);
  9114. normals.push(normal.z);
  9115. }
  9116. }
  9117. this.setIndices(indices);
  9118. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  9119. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  9120. kind = kinds[kindIndex];
  9121. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  9122. }
  9123. this.releaseSubMeshes();
  9124. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  9125. var previousOne = previousSubmeshes[submeshIndex];
  9126. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  9127. }
  9128. this.synchronizeInstances();
  9129. };
  9130. Mesh.prototype.createInstance = function (name) {
  9131. return new BABYLON.InstancedMesh(name, this);
  9132. };
  9133. Mesh.prototype.synchronizeInstances = function () {
  9134. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  9135. var instance = this.instances[instanceIndex];
  9136. instance._syncSubMeshes();
  9137. }
  9138. };
  9139. Mesh.CreateBox = function (name, size, scene, updatable) {
  9140. var box = new BABYLON.Mesh(name, scene);
  9141. var vertexData = BABYLON.VertexData.CreateBox(size);
  9142. vertexData.applyToMesh(box, updatable);
  9143. return box;
  9144. };
  9145. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable) {
  9146. var sphere = new BABYLON.Mesh(name, scene);
  9147. var vertexData = BABYLON.VertexData.CreateSphere(segments, diameter);
  9148. vertexData.applyToMesh(sphere, updatable);
  9149. return sphere;
  9150. };
  9151. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable) {
  9152. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  9153. if (scene !== undefined) {
  9154. updatable = scene;
  9155. }
  9156. scene = subdivisions;
  9157. subdivisions = 1;
  9158. }
  9159. var cylinder = new BABYLON.Mesh(name, scene);
  9160. var vertexData = BABYLON.VertexData.CreateCylinder(height, diameterTop, diameterBottom, tessellation, subdivisions);
  9161. vertexData.applyToMesh(cylinder, updatable);
  9162. return cylinder;
  9163. };
  9164. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable) {
  9165. var torus = new BABYLON.Mesh(name, scene);
  9166. var vertexData = BABYLON.VertexData.CreateTorus(diameter, thickness, tessellation);
  9167. vertexData.applyToMesh(torus, updatable);
  9168. return torus;
  9169. };
  9170. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable) {
  9171. var torusKnot = new BABYLON.Mesh(name, scene);
  9172. var vertexData = BABYLON.VertexData.CreateTorusKnot(radius, tube, radialSegments, tubularSegments, p, q);
  9173. vertexData.applyToMesh(torusKnot, updatable);
  9174. return torusKnot;
  9175. };
  9176. Mesh.CreateLines = function (name, points, scene, updatable) {
  9177. var lines = new BABYLON.LinesMesh(name, scene, updatable);
  9178. var vertexData = BABYLON.VertexData.CreateLines(points);
  9179. vertexData.applyToMesh(lines, updatable);
  9180. return lines;
  9181. };
  9182. Mesh.CreatePlane = function (name, size, scene, updatable) {
  9183. var plane = new BABYLON.Mesh(name, scene);
  9184. var vertexData = BABYLON.VertexData.CreatePlane(size);
  9185. vertexData.applyToMesh(plane, updatable);
  9186. return plane;
  9187. };
  9188. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  9189. var ground = new BABYLON.GroundMesh(name, scene);
  9190. ground._setReady(false);
  9191. ground._subdivisions = subdivisions;
  9192. var vertexData = BABYLON.VertexData.CreateGround(width, height, subdivisions);
  9193. vertexData.applyToMesh(ground, updatable);
  9194. ground._setReady(true);
  9195. return ground;
  9196. };
  9197. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  9198. var tiledGround = new BABYLON.Mesh(name, scene);
  9199. var vertexData = BABYLON.VertexData.CreateTiledGround(xmin, zmin, xmax, zmax, subdivisions, precision);
  9200. vertexData.applyToMesh(tiledGround, updatable);
  9201. return tiledGround;
  9202. };
  9203. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable) {
  9204. var ground = new BABYLON.GroundMesh(name, scene);
  9205. ground._subdivisions = subdivisions;
  9206. ground._setReady(false);
  9207. var onload = function (img) {
  9208. var canvas = document.createElement("canvas");
  9209. var context = canvas.getContext("2d");
  9210. var heightMapWidth = img.width;
  9211. var heightMapHeight = img.height;
  9212. canvas.width = heightMapWidth;
  9213. canvas.height = heightMapHeight;
  9214. context.drawImage(img, 0, 0);
  9215. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  9216. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap(width, height, subdivisions, minHeight, maxHeight, buffer, heightMapWidth, heightMapHeight);
  9217. vertexData.applyToMesh(ground, updatable);
  9218. ground._setReady(true);
  9219. };
  9220. BABYLON.Tools.LoadImage(url, onload, function () {
  9221. }, scene.database);
  9222. return ground;
  9223. };
  9224. Mesh.MinMax = function (meshes) {
  9225. var minVector = null;
  9226. var maxVector = null;
  9227. for (var i in meshes) {
  9228. var mesh = meshes[i];
  9229. var boundingBox = mesh.getBoundingInfo().boundingBox;
  9230. if (!minVector) {
  9231. minVector = boundingBox.minimumWorld;
  9232. maxVector = boundingBox.maximumWorld;
  9233. continue;
  9234. }
  9235. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  9236. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  9237. }
  9238. return {
  9239. min: minVector,
  9240. max: maxVector
  9241. };
  9242. };
  9243. Mesh.Center = function (meshesOrMinMaxVector) {
  9244. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  9245. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  9246. };
  9247. return Mesh;
  9248. })(BABYLON.AbstractMesh);
  9249. BABYLON.Mesh = Mesh;
  9250. })(BABYLON || (BABYLON = {}));
  9251. var __extends = this.__extends || function (d, b) {
  9252. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9253. function __() { this.constructor = d; }
  9254. __.prototype = b.prototype;
  9255. d.prototype = new __();
  9256. };
  9257. var BABYLON;
  9258. (function (BABYLON) {
  9259. var GroundMesh = (function (_super) {
  9260. __extends(GroundMesh, _super);
  9261. function GroundMesh(name, scene) {
  9262. _super.call(this, name, scene);
  9263. this.generateOctree = false;
  9264. this._worldInverse = new BABYLON.Matrix();
  9265. }
  9266. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  9267. get: function () {
  9268. return this._subdivisions;
  9269. },
  9270. enumerable: true,
  9271. configurable: true
  9272. });
  9273. GroundMesh.prototype.optimize = function (chunksCount) {
  9274. this.subdivide(this._subdivisions);
  9275. this.createOrUpdateSubmeshesOctree(32);
  9276. };
  9277. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  9278. var ray = new BABYLON.Ray(new BABYLON.Vector3(x, this.getBoundingInfo().boundingBox.maximumWorld.y + 1, z), new BABYLON.Vector3(0, -1, 0));
  9279. this.getWorldMatrix().invertToRef(this._worldInverse);
  9280. ray = BABYLON.Ray.Transform(ray, this._worldInverse);
  9281. var pickInfo = this.intersects(ray);
  9282. if (pickInfo.hit) {
  9283. return pickInfo.pickedPoint.y;
  9284. }
  9285. return 0;
  9286. };
  9287. return GroundMesh;
  9288. })(BABYLON.Mesh);
  9289. BABYLON.GroundMesh = GroundMesh;
  9290. })(BABYLON || (BABYLON = {}));
  9291. var __extends = this.__extends || function (d, b) {
  9292. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9293. function __() { this.constructor = d; }
  9294. __.prototype = b.prototype;
  9295. d.prototype = new __();
  9296. };
  9297. var BABYLON;
  9298. (function (BABYLON) {
  9299. var InstancedMesh = (function (_super) {
  9300. __extends(InstancedMesh, _super);
  9301. function InstancedMesh(name, source) {
  9302. _super.call(this, name, source.getScene());
  9303. source.instances.push(this);
  9304. this._sourceMesh = source;
  9305. this.position.copyFrom(source.position);
  9306. this.rotation.copyFrom(source.rotation);
  9307. this.scaling.copyFrom(source.scaling);
  9308. if (source.rotationQuaternion) {
  9309. this.rotationQuaternion = source.rotationQuaternion.clone();
  9310. }
  9311. this.infiniteDistance = source.infiniteDistance;
  9312. this.setPivotMatrix(source.getPivotMatrix());
  9313. this.refreshBoundingInfo();
  9314. this._syncSubMeshes();
  9315. }
  9316. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  9317. get: function () {
  9318. return this._sourceMesh.receiveShadows;
  9319. },
  9320. enumerable: true,
  9321. configurable: true
  9322. });
  9323. Object.defineProperty(InstancedMesh.prototype, "material", {
  9324. get: function () {
  9325. return this._sourceMesh.material;
  9326. },
  9327. enumerable: true,
  9328. configurable: true
  9329. });
  9330. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  9331. get: function () {
  9332. return this._sourceMesh.visibility;
  9333. },
  9334. enumerable: true,
  9335. configurable: true
  9336. });
  9337. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  9338. get: function () {
  9339. return this._sourceMesh.skeleton;
  9340. },
  9341. enumerable: true,
  9342. configurable: true
  9343. });
  9344. InstancedMesh.prototype.getTotalVertices = function () {
  9345. return this._sourceMesh.getTotalVertices();
  9346. };
  9347. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  9348. get: function () {
  9349. return this._sourceMesh;
  9350. },
  9351. enumerable: true,
  9352. configurable: true
  9353. });
  9354. InstancedMesh.prototype.getVerticesData = function (kind) {
  9355. return this._sourceMesh.getVerticesData(kind);
  9356. };
  9357. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  9358. return this._sourceMesh.isVerticesDataPresent(kind);
  9359. };
  9360. InstancedMesh.prototype.getIndices = function () {
  9361. return this._sourceMesh.getIndices();
  9362. };
  9363. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  9364. get: function () {
  9365. return this._sourceMesh._positions;
  9366. },
  9367. enumerable: true,
  9368. configurable: true
  9369. });
  9370. InstancedMesh.prototype.refreshBoundingInfo = function () {
  9371. var data = this._sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  9372. if (data) {
  9373. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._sourceMesh.getTotalVertices());
  9374. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  9375. }
  9376. this._updateBoundingInfo();
  9377. };
  9378. InstancedMesh.prototype._preActivate = function () {
  9379. if (this._currentLOD) {
  9380. this._currentLOD._preActivate();
  9381. }
  9382. };
  9383. InstancedMesh.prototype._activate = function (renderId) {
  9384. if (this._currentLOD) {
  9385. this._currentLOD._registerInstanceForRenderId(this, renderId);
  9386. }
  9387. };
  9388. InstancedMesh.prototype.getLOD = function (camera) {
  9389. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  9390. return this._currentLOD;
  9391. };
  9392. InstancedMesh.prototype._syncSubMeshes = function () {
  9393. this.releaseSubMeshes();
  9394. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  9395. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  9396. }
  9397. };
  9398. InstancedMesh.prototype._generatePointsArray = function () {
  9399. return this._sourceMesh._generatePointsArray();
  9400. };
  9401. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  9402. var result = this._sourceMesh.createInstance(name);
  9403. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  9404. this.refreshBoundingInfo();
  9405. if (newParent) {
  9406. result.parent = newParent;
  9407. }
  9408. if (!doNotCloneChildren) {
  9409. for (var index = 0; index < this.getScene().meshes.length; index++) {
  9410. var mesh = this.getScene().meshes[index];
  9411. if (mesh.parent == this) {
  9412. mesh.clone(mesh.name, result);
  9413. }
  9414. }
  9415. }
  9416. result.computeWorldMatrix(true);
  9417. return result;
  9418. };
  9419. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  9420. var index = this._sourceMesh.instances.indexOf(this);
  9421. this._sourceMesh.instances.splice(index, 1);
  9422. _super.prototype.dispose.call(this, doNotRecurse);
  9423. };
  9424. return InstancedMesh;
  9425. })(BABYLON.AbstractMesh);
  9426. BABYLON.InstancedMesh = InstancedMesh;
  9427. })(BABYLON || (BABYLON = {}));
  9428. var BABYLON;
  9429. (function (BABYLON) {
  9430. var SubMesh = (function () {
  9431. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  9432. if (typeof createBoundingBox === "undefined") { createBoundingBox = true; }
  9433. this.materialIndex = materialIndex;
  9434. this.verticesStart = verticesStart;
  9435. this.verticesCount = verticesCount;
  9436. this.indexStart = indexStart;
  9437. this.indexCount = indexCount;
  9438. this._renderId = 0;
  9439. this._mesh = mesh;
  9440. this._renderingMesh = renderingMesh || mesh;
  9441. mesh.subMeshes.push(this);
  9442. this._id = mesh.subMeshes.length - 1;
  9443. if (createBoundingBox) {
  9444. this.refreshBoundingInfo();
  9445. }
  9446. }
  9447. SubMesh.prototype.getBoundingInfo = function () {
  9448. return this._boundingInfo;
  9449. };
  9450. SubMesh.prototype.getMesh = function () {
  9451. return this._mesh;
  9452. };
  9453. SubMesh.prototype.getRenderingMesh = function () {
  9454. return this._renderingMesh;
  9455. };
  9456. SubMesh.prototype.getMaterial = function () {
  9457. var rootMaterial = this._renderingMesh.material;
  9458. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  9459. var multiMaterial = rootMaterial;
  9460. return multiMaterial.getSubMaterial(this.materialIndex);
  9461. }
  9462. if (!rootMaterial) {
  9463. return this._mesh.getScene().defaultMaterial;
  9464. }
  9465. return rootMaterial;
  9466. };
  9467. SubMesh.prototype.refreshBoundingInfo = function () {
  9468. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  9469. if (!data) {
  9470. this._boundingInfo = this._mesh._boundingInfo;
  9471. return;
  9472. }
  9473. var indices = this._renderingMesh.getIndices();
  9474. var extend;
  9475. if (this.indexStart === 0 && this.indexCount === indices.length) {
  9476. extend = BABYLON.Tools.ExtractMinAndMax(data, this.verticesStart, this.verticesCount);
  9477. } else {
  9478. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
  9479. }
  9480. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  9481. };
  9482. SubMesh.prototype._checkCollision = function (collider) {
  9483. return this._boundingInfo._checkCollision(collider);
  9484. };
  9485. SubMesh.prototype.updateBoundingInfo = function (world) {
  9486. if (!this._boundingInfo) {
  9487. this.refreshBoundingInfo();
  9488. }
  9489. this._boundingInfo._update(world);
  9490. };
  9491. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  9492. return this._boundingInfo.isInFrustum(frustumPlanes);
  9493. };
  9494. SubMesh.prototype.render = function () {
  9495. this._renderingMesh.render(this);
  9496. };
  9497. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  9498. if (!this._linesIndexBuffer) {
  9499. var linesIndices = [];
  9500. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  9501. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  9502. }
  9503. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  9504. this.linesIndexCount = linesIndices.length;
  9505. }
  9506. return this._linesIndexBuffer;
  9507. };
  9508. SubMesh.prototype.canIntersects = function (ray) {
  9509. return ray.intersectsBox(this._boundingInfo.boundingBox);
  9510. };
  9511. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  9512. var intersectInfo = null;
  9513. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  9514. var p0 = positions[indices[index]];
  9515. var p1 = positions[indices[index + 1]];
  9516. var p2 = positions[indices[index + 2]];
  9517. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  9518. if (currentIntersectInfo) {
  9519. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  9520. intersectInfo = currentIntersectInfo;
  9521. intersectInfo.faceId = index / 3;
  9522. if (fastCheck) {
  9523. break;
  9524. }
  9525. }
  9526. }
  9527. }
  9528. return intersectInfo;
  9529. };
  9530. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  9531. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  9532. result._boundingInfo = new BABYLON.BoundingInfo(this._boundingInfo.minimum, this._boundingInfo.maximum);
  9533. return result;
  9534. };
  9535. SubMesh.prototype.dispose = function () {
  9536. if (this._linesIndexBuffer) {
  9537. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  9538. this._linesIndexBuffer = null;
  9539. }
  9540. var index = this._mesh.subMeshes.indexOf(this);
  9541. this._mesh.subMeshes.splice(index, 1);
  9542. };
  9543. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  9544. var minVertexIndex = Number.MAX_VALUE;
  9545. var maxVertexIndex = -Number.MAX_VALUE;
  9546. renderingMesh = renderingMesh || mesh;
  9547. var indices = renderingMesh.getIndices();
  9548. for (var index = startIndex; index < startIndex + indexCount; index++) {
  9549. var vertexIndex = indices[index];
  9550. if (vertexIndex < minVertexIndex)
  9551. minVertexIndex = vertexIndex;
  9552. if (vertexIndex > maxVertexIndex)
  9553. maxVertexIndex = vertexIndex;
  9554. }
  9555. return new BABYLON.SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  9556. };
  9557. return SubMesh;
  9558. })();
  9559. BABYLON.SubMesh = SubMesh;
  9560. })(BABYLON || (BABYLON = {}));
  9561. var BABYLON;
  9562. (function (BABYLON) {
  9563. var BaseTexture = (function () {
  9564. function BaseTexture(scene) {
  9565. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  9566. this.hasAlpha = false;
  9567. this.getAlphaFromRGB = false;
  9568. this.level = 1;
  9569. this.isCube = false;
  9570. this.isRenderTarget = false;
  9571. this.animations = new Array();
  9572. this.coordinatesIndex = 0;
  9573. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  9574. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  9575. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  9576. this.anisotropicFilteringLevel = 4;
  9577. this._scene = scene;
  9578. this._scene.textures.push(this);
  9579. }
  9580. BaseTexture.prototype.getScene = function () {
  9581. return this._scene;
  9582. };
  9583. BaseTexture.prototype.getTextureMatrix = function () {
  9584. return null;
  9585. };
  9586. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  9587. return null;
  9588. };
  9589. BaseTexture.prototype.getInternalTexture = function () {
  9590. return this._texture;
  9591. };
  9592. BaseTexture.prototype.isReady = function () {
  9593. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  9594. return true;
  9595. }
  9596. if (this._texture) {
  9597. return this._texture.isReady;
  9598. }
  9599. return false;
  9600. };
  9601. BaseTexture.prototype.getSize = function () {
  9602. if (this._texture._width) {
  9603. return { width: this._texture._width, height: this._texture._height };
  9604. }
  9605. if (this._texture._size) {
  9606. return { width: this._texture._size, height: this._texture._size };
  9607. }
  9608. return { width: 0, height: 0 };
  9609. };
  9610. BaseTexture.prototype.getBaseSize = function () {
  9611. if (!this.isReady())
  9612. return { width: 0, height: 0 };
  9613. if (this._texture._size) {
  9614. return { width: this._texture._size, height: this._texture._size };
  9615. }
  9616. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  9617. };
  9618. BaseTexture.prototype.scale = function (ratio) {
  9619. };
  9620. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  9621. get: function () {
  9622. return false;
  9623. },
  9624. enumerable: true,
  9625. configurable: true
  9626. });
  9627. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  9628. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  9629. for (var index = 0; index < texturesCache.length; index++) {
  9630. var texturesCacheEntry = texturesCache[index];
  9631. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  9632. texturesCache.splice(index, 1);
  9633. return;
  9634. }
  9635. }
  9636. };
  9637. BaseTexture.prototype._getFromCache = function (url, noMipmap) {
  9638. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  9639. for (var index = 0; index < texturesCache.length; index++) {
  9640. var texturesCacheEntry = texturesCache[index];
  9641. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  9642. texturesCacheEntry.references++;
  9643. return texturesCacheEntry;
  9644. }
  9645. }
  9646. return null;
  9647. };
  9648. BaseTexture.prototype.delayLoad = function () {
  9649. };
  9650. BaseTexture.prototype.releaseInternalTexture = function () {
  9651. if (!this._texture) {
  9652. return;
  9653. }
  9654. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  9655. this._texture.references--;
  9656. if (this._texture.references == 0) {
  9657. var index = texturesCache.indexOf(this._texture);
  9658. texturesCache.splice(index, 1);
  9659. this._scene.getEngine()._releaseTexture(this._texture);
  9660. delete this._texture;
  9661. }
  9662. };
  9663. BaseTexture.prototype.clone = function () {
  9664. return null;
  9665. };
  9666. BaseTexture.prototype.dispose = function () {
  9667. var index = this._scene.textures.indexOf(this);
  9668. if (index >= 0) {
  9669. this._scene.textures.splice(index, 1);
  9670. }
  9671. if (this._texture === undefined) {
  9672. return;
  9673. }
  9674. this.releaseInternalTexture();
  9675. if (this.onDispose) {
  9676. this.onDispose();
  9677. }
  9678. };
  9679. return BaseTexture;
  9680. })();
  9681. BABYLON.BaseTexture = BaseTexture;
  9682. })(BABYLON || (BABYLON = {}));
  9683. var BABYLON;
  9684. (function (BABYLON) {
  9685. var RenderingGroup = (function () {
  9686. function RenderingGroup(index, scene) {
  9687. this.index = index;
  9688. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  9689. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  9690. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  9691. this._scene = scene;
  9692. }
  9693. RenderingGroup.prototype.render = function (customRenderFunction, beforeTransparents) {
  9694. if (customRenderFunction) {
  9695. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, beforeTransparents);
  9696. return true;
  9697. }
  9698. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  9699. return false;
  9700. }
  9701. var engine = this._scene.getEngine();
  9702. var subIndex;
  9703. var submesh;
  9704. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  9705. submesh = this._opaqueSubMeshes.data[subIndex];
  9706. this._activeVertices += submesh.verticesCount;
  9707. submesh.render();
  9708. }
  9709. engine.setAlphaTesting(true);
  9710. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  9711. submesh = this._alphaTestSubMeshes.data[subIndex];
  9712. this._activeVertices += submesh.verticesCount;
  9713. submesh.render();
  9714. }
  9715. engine.setAlphaTesting(false);
  9716. if (beforeTransparents) {
  9717. beforeTransparents();
  9718. }
  9719. if (this._transparentSubMeshes.length) {
  9720. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  9721. submesh = this._transparentSubMeshes.data[subIndex];
  9722. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.position).length();
  9723. }
  9724. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  9725. sortedArray.sort(function (a, b) {
  9726. if (a._distanceToCamera < b._distanceToCamera) {
  9727. return 1;
  9728. }
  9729. if (a._distanceToCamera > b._distanceToCamera) {
  9730. return -1;
  9731. }
  9732. return 0;
  9733. });
  9734. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  9735. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  9736. submesh = sortedArray[subIndex];
  9737. this._activeVertices += submesh.verticesCount;
  9738. submesh.render();
  9739. }
  9740. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  9741. }
  9742. return true;
  9743. };
  9744. RenderingGroup.prototype.prepare = function () {
  9745. this._opaqueSubMeshes.reset();
  9746. this._transparentSubMeshes.reset();
  9747. this._alphaTestSubMeshes.reset();
  9748. };
  9749. RenderingGroup.prototype.dispatch = function (subMesh) {
  9750. var material = subMesh.getMaterial();
  9751. var mesh = subMesh.getMesh();
  9752. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  9753. if (material.alpha > 0 || mesh.visibility < 1.0) {
  9754. this._transparentSubMeshes.push(subMesh);
  9755. }
  9756. } else if (material.needAlphaTesting()) {
  9757. this._alphaTestSubMeshes.push(subMesh);
  9758. } else {
  9759. this._opaqueSubMeshes.push(subMesh);
  9760. }
  9761. };
  9762. return RenderingGroup;
  9763. })();
  9764. BABYLON.RenderingGroup = RenderingGroup;
  9765. })(BABYLON || (BABYLON = {}));
  9766. var BABYLON;
  9767. (function (BABYLON) {
  9768. var RenderingManager = (function () {
  9769. function RenderingManager(scene) {
  9770. this._renderingGroups = new Array();
  9771. this._scene = scene;
  9772. }
  9773. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  9774. if (this._scene._activeParticleSystems.length === 0) {
  9775. return;
  9776. }
  9777. var beforeParticlesDate = BABYLON.Tools.Now;
  9778. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  9779. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  9780. if (particleSystem.renderingGroupId !== index) {
  9781. continue;
  9782. }
  9783. this._clearDepthBuffer();
  9784. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  9785. this._scene._activeParticles += particleSystem.render();
  9786. }
  9787. }
  9788. this._scene._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  9789. };
  9790. RenderingManager.prototype._renderSprites = function (index) {
  9791. if (this._scene.spriteManagers.length === 0) {
  9792. return;
  9793. }
  9794. var beforeSpritessDate = BABYLON.Tools.Now;
  9795. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  9796. var spriteManager = this._scene.spriteManagers[id];
  9797. if (spriteManager.renderingGroupId === index) {
  9798. this._clearDepthBuffer();
  9799. spriteManager.render();
  9800. }
  9801. }
  9802. this._scene._spritesDuration += BABYLON.Tools.Now - beforeSpritessDate;
  9803. };
  9804. RenderingManager.prototype._clearDepthBuffer = function () {
  9805. if (this._depthBufferAlreadyCleaned) {
  9806. return;
  9807. }
  9808. this._scene.getEngine().clear(0, false, true);
  9809. this._depthBufferAlreadyCleaned = true;
  9810. };
  9811. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  9812. var _this = this;
  9813. for (var index = 0; index < BABYLON.RenderingManager.MAX_RENDERINGGROUPS; index++) {
  9814. this._depthBufferAlreadyCleaned = false;
  9815. var renderingGroup = this._renderingGroups[index];
  9816. if (renderingGroup) {
  9817. this._clearDepthBuffer();
  9818. if (!renderingGroup.render(customRenderFunction, function () {
  9819. if (renderSprites) {
  9820. _this._renderSprites(index);
  9821. }
  9822. })) {
  9823. this._renderingGroups.splice(index, 1);
  9824. }
  9825. } else if (renderSprites) {
  9826. this._renderSprites(index);
  9827. }
  9828. if (renderParticles) {
  9829. this._renderParticles(index, activeMeshes);
  9830. }
  9831. }
  9832. };
  9833. RenderingManager.prototype.reset = function () {
  9834. for (var index in this._renderingGroups) {
  9835. var renderingGroup = this._renderingGroups[index];
  9836. renderingGroup.prepare();
  9837. }
  9838. };
  9839. RenderingManager.prototype.dispatch = function (subMesh) {
  9840. var mesh = subMesh.getMesh();
  9841. var renderingGroupId = mesh.renderingGroupId || 0;
  9842. if (!this._renderingGroups[renderingGroupId]) {
  9843. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  9844. }
  9845. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  9846. };
  9847. RenderingManager.MAX_RENDERINGGROUPS = 4;
  9848. return RenderingManager;
  9849. })();
  9850. BABYLON.RenderingManager = RenderingManager;
  9851. })(BABYLON || (BABYLON = {}));
  9852. var __extends = this.__extends || function (d, b) {
  9853. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9854. function __() { this.constructor = d; }
  9855. __.prototype = b.prototype;
  9856. d.prototype = new __();
  9857. };
  9858. var BABYLON;
  9859. (function (BABYLON) {
  9860. var Texture = (function (_super) {
  9861. __extends(Texture, _super);
  9862. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  9863. if (typeof samplingMode === "undefined") { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  9864. if (typeof onLoad === "undefined") { onLoad = null; }
  9865. if (typeof onError === "undefined") { onError = null; }
  9866. if (typeof buffer === "undefined") { buffer = null; }
  9867. if (typeof deleteBuffer === "undefined") { deleteBuffer = false; }
  9868. _super.call(this, scene);
  9869. this.uOffset = 0;
  9870. this.vOffset = 0;
  9871. this.uScale = 1.0;
  9872. this.vScale = 1.0;
  9873. this.uAng = 0;
  9874. this.vAng = 0;
  9875. this.wAng = 0;
  9876. this.name = url;
  9877. this.url = url;
  9878. this._noMipmap = noMipmap;
  9879. this._invertY = invertY;
  9880. this._samplingMode = samplingMode;
  9881. this._buffer = buffer;
  9882. this._deleteBuffer = deleteBuffer;
  9883. if (!url) {
  9884. return;
  9885. }
  9886. this._texture = this._getFromCache(url, noMipmap);
  9887. if (!this._texture) {
  9888. if (!scene.useDelayedTextureLoading) {
  9889. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  9890. if (deleteBuffer) {
  9891. delete this._buffer;
  9892. }
  9893. } else {
  9894. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  9895. }
  9896. }
  9897. }
  9898. Texture.prototype.delayLoad = function () {
  9899. if (this.delayLoadState != BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  9900. return;
  9901. }
  9902. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  9903. this._texture = this._getFromCache(this.url, this._noMipmap);
  9904. if (!this._texture) {
  9905. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, null, null, this._buffer);
  9906. if (this._deleteBuffer) {
  9907. delete this._buffer;
  9908. }
  9909. }
  9910. };
  9911. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  9912. x -= this.uOffset + 0.5;
  9913. y -= this.vOffset + 0.5;
  9914. z -= 0.5;
  9915. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  9916. t.x *= this.uScale;
  9917. t.y *= this.vScale;
  9918. t.x += 0.5;
  9919. t.y += 0.5;
  9920. t.z += 0.5;
  9921. };
  9922. Texture.prototype.getTextureMatrix = function () {
  9923. 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) {
  9924. return this._cachedTextureMatrix;
  9925. }
  9926. this._cachedUOffset = this.uOffset;
  9927. this._cachedVOffset = this.vOffset;
  9928. this._cachedUScale = this.uScale;
  9929. this._cachedVScale = this.vScale;
  9930. this._cachedUAng = this.uAng;
  9931. this._cachedVAng = this.vAng;
  9932. this._cachedWAng = this.wAng;
  9933. if (!this._cachedTextureMatrix) {
  9934. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  9935. this._rowGenerationMatrix = new BABYLON.Matrix();
  9936. this._t0 = BABYLON.Vector3.Zero();
  9937. this._t1 = BABYLON.Vector3.Zero();
  9938. this._t2 = BABYLON.Vector3.Zero();
  9939. }
  9940. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  9941. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  9942. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  9943. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  9944. this._t1.subtractInPlace(this._t0);
  9945. this._t2.subtractInPlace(this._t0);
  9946. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  9947. this._cachedTextureMatrix.m[0] = this._t1.x;
  9948. this._cachedTextureMatrix.m[1] = this._t1.y;
  9949. this._cachedTextureMatrix.m[2] = this._t1.z;
  9950. this._cachedTextureMatrix.m[4] = this._t2.x;
  9951. this._cachedTextureMatrix.m[5] = this._t2.y;
  9952. this._cachedTextureMatrix.m[6] = this._t2.z;
  9953. this._cachedTextureMatrix.m[8] = this._t0.x;
  9954. this._cachedTextureMatrix.m[9] = this._t0.y;
  9955. this._cachedTextureMatrix.m[10] = this._t0.z;
  9956. return this._cachedTextureMatrix;
  9957. };
  9958. Texture.prototype.getReflectionTextureMatrix = function () {
  9959. if (this.uOffset === this._cachedUOffset && this.vOffset === this._cachedVOffset && this.uScale === this._cachedUScale && this.vScale === this._cachedVScale && this.coordinatesMode === this._cachedCoordinatesMode) {
  9960. return this._cachedTextureMatrix;
  9961. }
  9962. if (!this._cachedTextureMatrix) {
  9963. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  9964. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  9965. }
  9966. switch (this.coordinatesMode) {
  9967. case BABYLON.Texture.SPHERICAL_MODE:
  9968. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  9969. this._cachedTextureMatrix[0] = -0.5 * this.uScale;
  9970. this._cachedTextureMatrix[5] = -0.5 * this.vScale;
  9971. this._cachedTextureMatrix[12] = 0.5 + this.uOffset;
  9972. this._cachedTextureMatrix[13] = 0.5 + this.vOffset;
  9973. break;
  9974. case BABYLON.Texture.PLANAR_MODE:
  9975. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  9976. this._cachedTextureMatrix[0] = this.uScale;
  9977. this._cachedTextureMatrix[5] = this.vScale;
  9978. this._cachedTextureMatrix[12] = this.uOffset;
  9979. this._cachedTextureMatrix[13] = this.vOffset;
  9980. break;
  9981. case BABYLON.Texture.PROJECTION_MODE:
  9982. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  9983. this._projectionModeMatrix.m[0] = 0.5;
  9984. this._projectionModeMatrix.m[5] = -0.5;
  9985. this._projectionModeMatrix.m[10] = 0.0;
  9986. this._projectionModeMatrix.m[12] = 0.5;
  9987. this._projectionModeMatrix.m[13] = 0.5;
  9988. this._projectionModeMatrix.m[14] = 1.0;
  9989. this._projectionModeMatrix.m[15] = 1.0;
  9990. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  9991. break;
  9992. default:
  9993. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  9994. break;
  9995. }
  9996. return this._cachedTextureMatrix;
  9997. };
  9998. Texture.prototype.clone = function () {
  9999. var newTexture = new BABYLON.Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY);
  10000. newTexture.hasAlpha = this.hasAlpha;
  10001. newTexture.level = this.level;
  10002. newTexture.wrapU = this.wrapU;
  10003. newTexture.wrapV = this.wrapV;
  10004. newTexture.coordinatesIndex = this.coordinatesIndex;
  10005. newTexture.coordinatesMode = this.coordinatesMode;
  10006. newTexture.uOffset = this.uOffset;
  10007. newTexture.vOffset = this.vOffset;
  10008. newTexture.uScale = this.uScale;
  10009. newTexture.vScale = this.vScale;
  10010. newTexture.uAng = this.uAng;
  10011. newTexture.vAng = this.vAng;
  10012. newTexture.wAng = this.wAng;
  10013. return newTexture;
  10014. };
  10015. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  10016. if (typeof samplingMode === "undefined") { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  10017. if (typeof onLoad === "undefined") { onLoad = null; }
  10018. if (typeof onError === "undefined") { onError = null; }
  10019. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  10020. };
  10021. Texture.NEAREST_SAMPLINGMODE = 1;
  10022. Texture.BILINEAR_SAMPLINGMODE = 2;
  10023. Texture.TRILINEAR_SAMPLINGMODE = 3;
  10024. Texture.EXPLICIT_MODE = 0;
  10025. Texture.SPHERICAL_MODE = 1;
  10026. Texture.PLANAR_MODE = 2;
  10027. Texture.CUBIC_MODE = 3;
  10028. Texture.PROJECTION_MODE = 4;
  10029. Texture.SKYBOX_MODE = 5;
  10030. Texture.CLAMP_ADDRESSMODE = 0;
  10031. Texture.WRAP_ADDRESSMODE = 1;
  10032. Texture.MIRROR_ADDRESSMODE = 2;
  10033. return Texture;
  10034. })(BABYLON.BaseTexture);
  10035. BABYLON.Texture = Texture;
  10036. })(BABYLON || (BABYLON = {}));
  10037. var __extends = this.__extends || function (d, b) {
  10038. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  10039. function __() { this.constructor = d; }
  10040. __.prototype = b.prototype;
  10041. d.prototype = new __();
  10042. };
  10043. var BABYLON;
  10044. (function (BABYLON) {
  10045. var CubeTexture = (function (_super) {
  10046. __extends(CubeTexture, _super);
  10047. function CubeTexture(rootUrl, scene, extensions, noMipmap) {
  10048. _super.call(this, scene);
  10049. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  10050. this.name = rootUrl;
  10051. this.url = rootUrl;
  10052. this._noMipmap = noMipmap;
  10053. this.hasAlpha = false;
  10054. this._texture = this._getFromCache(rootUrl, noMipmap);
  10055. if (!extensions) {
  10056. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  10057. }
  10058. this._extensions = extensions;
  10059. if (!this._texture) {
  10060. if (!scene.useDelayedTextureLoading) {
  10061. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, extensions, noMipmap);
  10062. } else {
  10063. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  10064. }
  10065. }
  10066. this.isCube = true;
  10067. this._textureMatrix = BABYLON.Matrix.Identity();
  10068. }
  10069. CubeTexture.prototype.clone = function () {
  10070. var newTexture = new BABYLON.CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap);
  10071. newTexture.level = this.level;
  10072. newTexture.wrapU = this.wrapU;
  10073. newTexture.wrapV = this.wrapV;
  10074. newTexture.coordinatesIndex = this.coordinatesIndex;
  10075. newTexture.coordinatesMode = this.coordinatesMode;
  10076. return newTexture;
  10077. };
  10078. CubeTexture.prototype.delayLoad = function () {
  10079. if (this.delayLoadState != BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  10080. return;
  10081. }
  10082. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  10083. this._texture = this._getFromCache(this.url, this._noMipmap);
  10084. if (!this._texture) {
  10085. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  10086. }
  10087. };
  10088. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  10089. return this._textureMatrix;
  10090. };
  10091. return CubeTexture;
  10092. })(BABYLON.BaseTexture);
  10093. BABYLON.CubeTexture = CubeTexture;
  10094. })(BABYLON || (BABYLON = {}));
  10095. var __extends = this.__extends || function (d, b) {
  10096. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  10097. function __() { this.constructor = d; }
  10098. __.prototype = b.prototype;
  10099. d.prototype = new __();
  10100. };
  10101. var BABYLON;
  10102. (function (BABYLON) {
  10103. var RenderTargetTexture = (function (_super) {
  10104. __extends(RenderTargetTexture, _super);
  10105. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio) {
  10106. if (typeof doNotChangeAspectRatio === "undefined") { doNotChangeAspectRatio = true; }
  10107. _super.call(this, null, scene, !generateMipMaps);
  10108. this.renderList = new Array();
  10109. this.renderParticles = true;
  10110. this.renderSprites = false;
  10111. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  10112. this._currentRefreshId = -1;
  10113. this._refreshRate = 1;
  10114. this.name = name;
  10115. this.isRenderTarget = true;
  10116. this._size = size;
  10117. this._generateMipMaps = generateMipMaps;
  10118. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  10119. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  10120. this._renderingManager = new BABYLON.RenderingManager(scene);
  10121. }
  10122. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  10123. this._currentRefreshId = -1;
  10124. };
  10125. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  10126. get: function () {
  10127. return this._refreshRate;
  10128. },
  10129. set: function (value) {
  10130. this._refreshRate = value;
  10131. this.resetRefreshCounter();
  10132. },
  10133. enumerable: true,
  10134. configurable: true
  10135. });
  10136. RenderTargetTexture.prototype._shouldRender = function () {
  10137. if (this._currentRefreshId === -1) {
  10138. this._currentRefreshId = 1;
  10139. return true;
  10140. }
  10141. if (this.refreshRate == this._currentRefreshId) {
  10142. this._currentRefreshId = 1;
  10143. return true;
  10144. }
  10145. this._currentRefreshId++;
  10146. return false;
  10147. };
  10148. RenderTargetTexture.prototype.isReady = function () {
  10149. if (!this.getScene().renderTargetsEnabled) {
  10150. return false;
  10151. }
  10152. return _super.prototype.isReady.call(this);
  10153. };
  10154. RenderTargetTexture.prototype.getRenderSize = function () {
  10155. return this._size;
  10156. };
  10157. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  10158. get: function () {
  10159. return true;
  10160. },
  10161. enumerable: true,
  10162. configurable: true
  10163. });
  10164. RenderTargetTexture.prototype.scale = function (ratio) {
  10165. var newSize = this._size * ratio;
  10166. this.resize(newSize, this._generateMipMaps);
  10167. };
  10168. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  10169. this.releaseInternalTexture();
  10170. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  10171. };
  10172. RenderTargetTexture.prototype.render = function (useCameraPostProcess) {
  10173. var scene = this.getScene();
  10174. var engine = scene.getEngine();
  10175. if (this._waitingRenderList) {
  10176. this.renderList = [];
  10177. for (var index = 0; index < this._waitingRenderList.length; index++) {
  10178. var id = this._waitingRenderList[index];
  10179. this.renderList.push(scene.getMeshByID(id));
  10180. }
  10181. delete this._waitingRenderList;
  10182. }
  10183. if (!this.renderList) {
  10184. return;
  10185. }
  10186. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  10187. engine.bindFramebuffer(this._texture);
  10188. }
  10189. engine.clear(scene.clearColor, true, true);
  10190. this._renderingManager.reset();
  10191. for (var meshIndex = 0; meshIndex < this.renderList.length; meshIndex++) {
  10192. var mesh = this.renderList[meshIndex];
  10193. if (mesh) {
  10194. if (!mesh.isReady() || (mesh.material && !mesh.material.isReady())) {
  10195. this.resetRefreshCounter();
  10196. continue;
  10197. }
  10198. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) != 0)) {
  10199. mesh._activate(scene.getRenderId());
  10200. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  10201. var subMesh = mesh.subMeshes[subIndex];
  10202. scene._activeVertices += subMesh.verticesCount;
  10203. this._renderingManager.dispatch(subMesh);
  10204. }
  10205. }
  10206. }
  10207. }
  10208. if (!this._doNotChangeAspectRatio) {
  10209. scene.updateTransformMatrix(true);
  10210. }
  10211. if (this.onBeforeRender) {
  10212. this.onBeforeRender();
  10213. }
  10214. this._renderingManager.render(this.customRenderFunction, this.renderList, this.renderParticles, this.renderSprites);
  10215. if (useCameraPostProcess) {
  10216. scene.postProcessManager._finalizeFrame(false, this._texture);
  10217. }
  10218. if (this.onAfterRender) {
  10219. this.onAfterRender();
  10220. }
  10221. engine.unBindFramebuffer(this._texture);
  10222. if (!this._doNotChangeAspectRatio) {
  10223. scene.updateTransformMatrix(true);
  10224. }
  10225. };
  10226. RenderTargetTexture.prototype.clone = function () {
  10227. var textureSize = this.getSize();
  10228. var newTexture = new BABYLON.RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  10229. newTexture.hasAlpha = this.hasAlpha;
  10230. newTexture.level = this.level;
  10231. newTexture.coordinatesMode = this.coordinatesMode;
  10232. newTexture.renderList = this.renderList.slice(0);
  10233. return newTexture;
  10234. };
  10235. return RenderTargetTexture;
  10236. })(BABYLON.Texture);
  10237. BABYLON.RenderTargetTexture = RenderTargetTexture;
  10238. })(BABYLON || (BABYLON = {}));
  10239. var __extends = this.__extends || function (d, b) {
  10240. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  10241. function __() { this.constructor = d; }
  10242. __.prototype = b.prototype;
  10243. d.prototype = new __();
  10244. };
  10245. var BABYLON;
  10246. (function (BABYLON) {
  10247. var ProceduralTexture = (function (_super) {
  10248. __extends(ProceduralTexture, _super);
  10249. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps) {
  10250. _super.call(this, null, scene, !generateMipMaps);
  10251. this._currentRefreshId = -1;
  10252. this._refreshRate = 1;
  10253. this._vertexDeclaration = [2];
  10254. this._vertexStrideSize = 2 * 4;
  10255. this._uniforms = new Array();
  10256. this._samplers = new Array();
  10257. this._textures = new Array();
  10258. this._floats = new Array();
  10259. this._floatsArrays = {};
  10260. this._colors3 = new Array();
  10261. this._colors4 = new Array();
  10262. this._vectors2 = new Array();
  10263. this._vectors3 = new Array();
  10264. this._matrices = new Array();
  10265. scene._proceduralTextures.push(this);
  10266. this.name = name;
  10267. this.isRenderTarget = true;
  10268. this._size = size;
  10269. this._generateMipMaps = generateMipMaps;
  10270. this._fragment = fragment;
  10271. this._fallbackTexture = fallbackTexture;
  10272. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  10273. var vertices = [];
  10274. vertices.push(1, 1);
  10275. vertices.push(-1, 1);
  10276. vertices.push(-1, -1);
  10277. vertices.push(1, -1);
  10278. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  10279. var indices = [];
  10280. indices.push(0);
  10281. indices.push(1);
  10282. indices.push(2);
  10283. indices.push(0);
  10284. indices.push(2);
  10285. indices.push(3);
  10286. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  10287. }
  10288. ProceduralTexture.prototype.reset = function () {
  10289. var engine = this.getScene().getEngine();
  10290. engine._releaseEffect(this._effect);
  10291. };
  10292. ProceduralTexture.prototype.isReady = function () {
  10293. var _this = this;
  10294. var engine = this.getScene().getEngine();
  10295. this._effect = engine.createEffect({ vertex: "procedural", fragment: this._fragment }, ["position"], this._uniforms, this._samplers, "", null, null, function () {
  10296. _this.releaseInternalTexture();
  10297. _this._texture = _this._fallbackTexture._texture;
  10298. _this._texture.references++;
  10299. });
  10300. return this._effect.isReady();
  10301. };
  10302. ProceduralTexture.prototype.resetRefreshCounter = function () {
  10303. this._currentRefreshId = -1;
  10304. };
  10305. ProceduralTexture.prototype.setFragment = function (fragment) {
  10306. this._fragment = fragment;
  10307. };
  10308. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  10309. get: function () {
  10310. return this._refreshRate;
  10311. },
  10312. set: function (value) {
  10313. this._refreshRate = value;
  10314. this.resetRefreshCounter();
  10315. },
  10316. enumerable: true,
  10317. configurable: true
  10318. });
  10319. ProceduralTexture.prototype._shouldRender = function () {
  10320. if (!this.isReady() || !this._texture) {
  10321. return false;
  10322. }
  10323. if (this._currentRefreshId === -1) {
  10324. this._currentRefreshId = 1;
  10325. return true;
  10326. }
  10327. if (this.refreshRate == this._currentRefreshId) {
  10328. this._currentRefreshId = 1;
  10329. return true;
  10330. }
  10331. this._currentRefreshId++;
  10332. return false;
  10333. };
  10334. ProceduralTexture.prototype.getRenderSize = function () {
  10335. return this._size;
  10336. };
  10337. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  10338. this.releaseInternalTexture();
  10339. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  10340. };
  10341. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  10342. if (this._uniforms.indexOf(uniformName) === -1) {
  10343. this._uniforms.push(uniformName);
  10344. }
  10345. };
  10346. ProceduralTexture.prototype.setTexture = function (name, texture) {
  10347. if (this._samplers.indexOf(name) === -1) {
  10348. this._samplers.push(name);
  10349. }
  10350. this._textures[name] = texture;
  10351. return this;
  10352. };
  10353. ProceduralTexture.prototype.setFloat = function (name, value) {
  10354. this._checkUniform(name);
  10355. this._floats[name] = value;
  10356. return this;
  10357. };
  10358. ProceduralTexture.prototype.setFloats = function (name, value) {
  10359. this._checkUniform(name);
  10360. this._floatsArrays[name] = value;
  10361. return this;
  10362. };
  10363. ProceduralTexture.prototype.setColor3 = function (name, value) {
  10364. this._checkUniform(name);
  10365. this._colors3[name] = value;
  10366. return this;
  10367. };
  10368. ProceduralTexture.prototype.setColor4 = function (name, value) {
  10369. this._checkUniform(name);
  10370. this._colors4[name] = value;
  10371. return this;
  10372. };
  10373. ProceduralTexture.prototype.setVector2 = function (name, value) {
  10374. this._checkUniform(name);
  10375. this._vectors2[name] = value;
  10376. return this;
  10377. };
  10378. ProceduralTexture.prototype.setVector3 = function (name, value) {
  10379. this._checkUniform(name);
  10380. this._vectors3[name] = value;
  10381. return this;
  10382. };
  10383. ProceduralTexture.prototype.setMatrix = function (name, value) {
  10384. this._checkUniform(name);
  10385. this._matrices[name] = value;
  10386. return this;
  10387. };
  10388. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  10389. var scene = this.getScene();
  10390. var engine = scene.getEngine();
  10391. engine.bindFramebuffer(this._texture);
  10392. engine.clear(scene.clearColor, true, true);
  10393. engine.enableEffect(this._effect);
  10394. engine.setState(false);
  10395. for (var name in this._textures) {
  10396. this._effect.setTexture(name, this._textures[name]);
  10397. }
  10398. for (name in this._floats) {
  10399. this._effect.setFloat(name, this._floats[name]);
  10400. }
  10401. for (name in this._floatsArrays) {
  10402. this._effect.setArray(name, this._floatsArrays[name]);
  10403. }
  10404. for (name in this._colors3) {
  10405. this._effect.setColor3(name, this._colors3[name]);
  10406. }
  10407. for (name in this._colors4) {
  10408. var color = this._colors4[name];
  10409. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  10410. }
  10411. for (name in this._vectors2) {
  10412. this._effect.setVector2(name, this._vectors2[name]);
  10413. }
  10414. for (name in this._vectors3) {
  10415. this._effect.setVector3(name, this._vectors3[name]);
  10416. }
  10417. for (name in this._matrices) {
  10418. this._effect.setMatrix(name, this._matrices[name]);
  10419. }
  10420. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  10421. engine.draw(true, 0, 6);
  10422. engine.unBindFramebuffer(this._texture);
  10423. };
  10424. ProceduralTexture.prototype.clone = function () {
  10425. var textureSize = this.getSize();
  10426. var newTexture = new BABYLON.ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  10427. newTexture.hasAlpha = this.hasAlpha;
  10428. newTexture.level = this.level;
  10429. newTexture.coordinatesMode = this.coordinatesMode;
  10430. return newTexture;
  10431. };
  10432. ProceduralTexture.prototype.dispose = function () {
  10433. var index = this.getScene()._proceduralTextures.indexOf(this);
  10434. if (index >= 0) {
  10435. this.getScene()._proceduralTextures.splice(index, 1);
  10436. }
  10437. _super.prototype.dispose.call(this);
  10438. };
  10439. return ProceduralTexture;
  10440. })(BABYLON.Texture);
  10441. BABYLON.ProceduralTexture = ProceduralTexture;
  10442. })(BABYLON || (BABYLON = {}));
  10443. var __extends = this.__extends || function (d, b) {
  10444. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  10445. function __() { this.constructor = d; }
  10446. __.prototype = b.prototype;
  10447. d.prototype = new __();
  10448. };
  10449. var BABYLON;
  10450. (function (BABYLON) {
  10451. var WoodProceduralTexture = (function (_super) {
  10452. __extends(WoodProceduralTexture, _super);
  10453. function WoodProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  10454. _super.call(this, name, size, "wood", scene, fallbackTexture, generateMipMaps);
  10455. this._ampScale = 100.0;
  10456. this._woodColor = new BABYLON.Color3(0.32, 0.17, 0.09);
  10457. this.updateShaderUniforms();
  10458. this.refreshRate = 0;
  10459. }
  10460. WoodProceduralTexture.prototype.updateShaderUniforms = function () {
  10461. this.setFloat("ampScale", this._ampScale);
  10462. this.setColor3("woodColor", this._woodColor);
  10463. };
  10464. Object.defineProperty(WoodProceduralTexture.prototype, "ampScale", {
  10465. get: function () {
  10466. return this._ampScale;
  10467. },
  10468. set: function (value) {
  10469. this._ampScale = value;
  10470. this.updateShaderUniforms();
  10471. },
  10472. enumerable: true,
  10473. configurable: true
  10474. });
  10475. Object.defineProperty(WoodProceduralTexture.prototype, "woodColor", {
  10476. get: function () {
  10477. return this._woodColor;
  10478. },
  10479. set: function (value) {
  10480. this._woodColor = value;
  10481. this.updateShaderUniforms();
  10482. },
  10483. enumerable: true,
  10484. configurable: true
  10485. });
  10486. return WoodProceduralTexture;
  10487. })(BABYLON.ProceduralTexture);
  10488. BABYLON.WoodProceduralTexture = WoodProceduralTexture;
  10489. var FireProceduralTexture = (function (_super) {
  10490. __extends(FireProceduralTexture, _super);
  10491. function FireProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  10492. _super.call(this, name, size, "fire", scene, fallbackTexture, generateMipMaps);
  10493. this._time = 0.0;
  10494. this._speed = new BABYLON.Vector2(0.5, 0.3);
  10495. this._shift = 1.6;
  10496. this._alpha = 1.0;
  10497. this._autoGenerateTime = true;
  10498. this._fireColors = FireProceduralTexture.RedFireColors;
  10499. this.updateShaderUniforms();
  10500. this.refreshRate = 1;
  10501. }
  10502. FireProceduralTexture.prototype.updateShaderUniforms = function () {
  10503. this.setFloat("iGlobalTime", this._time);
  10504. this.setVector2("speed", this._speed);
  10505. this.setFloat("shift", this._shift);
  10506. this.setFloat("alpha", this._alpha);
  10507. this.setColor3("c1", new BABYLON.Color3(this._fireColors[0][0], this._fireColors[0][1], this._fireColors[0][2]));
  10508. this.setColor3("c2", new BABYLON.Color3(this._fireColors[1][0], this._fireColors[1][1], this._fireColors[1][2]));
  10509. this.setColor3("c3", new BABYLON.Color3(this._fireColors[2][0], this._fireColors[2][1], this._fireColors[2][2]));
  10510. this.setColor3("c4", new BABYLON.Color3(this._fireColors[3][0], this._fireColors[3][1], this._fireColors[3][2]));
  10511. this.setColor3("c5", new BABYLON.Color3(this._fireColors[4][0], this._fireColors[4][1], this._fireColors[4][2]));
  10512. this.setColor3("c6", new BABYLON.Color3(this._fireColors[5][0], this._fireColors[5][1], this._fireColors[5][2]));
  10513. };
  10514. FireProceduralTexture.prototype.render = function (useCameraPostProcess) {
  10515. if (this._autoGenerateTime) {
  10516. this._time += this.getScene().getAnimationRatio() * 0.03;
  10517. this.updateShaderUniforms();
  10518. }
  10519. _super.prototype.render.call(this, useCameraPostProcess);
  10520. };
  10521. Object.defineProperty(FireProceduralTexture, "PurpleFireColors", {
  10522. get: function () {
  10523. return [
  10524. [0.5, 0.0, 1.0],
  10525. [0.9, 0.0, 1.0],
  10526. [0.2, 0.0, 1.0],
  10527. [1.0, 0.9, 1.0],
  10528. [0.1, 0.1, 1.0],
  10529. [0.9, 0.9, 1.0]
  10530. ];
  10531. },
  10532. enumerable: true,
  10533. configurable: true
  10534. });
  10535. Object.defineProperty(FireProceduralTexture, "GreenFireColors", {
  10536. get: function () {
  10537. return [
  10538. [0.5, 1.0, 0.0],
  10539. [0.5, 1.0, 0.0],
  10540. [0.3, 0.4, 0.0],
  10541. [0.5, 1.0, 0.0],
  10542. [0.2, 0.0, 0.0],
  10543. [0.5, 1.0, 0.0]
  10544. ];
  10545. },
  10546. enumerable: true,
  10547. configurable: true
  10548. });
  10549. Object.defineProperty(FireProceduralTexture, "RedFireColors", {
  10550. get: function () {
  10551. return [
  10552. [0.5, 0.0, 0.1],
  10553. [0.9, 0.0, 0.0],
  10554. [0.2, 0.0, 0.0],
  10555. [1.0, 0.9, 0.0],
  10556. [0.1, 0.1, 0.1],
  10557. [0.9, 0.9, 0.9]
  10558. ];
  10559. },
  10560. enumerable: true,
  10561. configurable: true
  10562. });
  10563. Object.defineProperty(FireProceduralTexture, "BlueFireColors", {
  10564. get: function () {
  10565. return [
  10566. [0.1, 0.0, 0.5],
  10567. [0.0, 0.0, 0.5],
  10568. [0.1, 0.0, 0.2],
  10569. [0.0, 0.0, 1.0],
  10570. [0.1, 0.2, 0.3],
  10571. [0.0, 0.2, 0.9]
  10572. ];
  10573. },
  10574. enumerable: true,
  10575. configurable: true
  10576. });
  10577. Object.defineProperty(FireProceduralTexture.prototype, "fireColors", {
  10578. get: function () {
  10579. return this._fireColors;
  10580. },
  10581. set: function (value) {
  10582. this._fireColors = value;
  10583. this.updateShaderUniforms();
  10584. },
  10585. enumerable: true,
  10586. configurable: true
  10587. });
  10588. Object.defineProperty(FireProceduralTexture.prototype, "time", {
  10589. get: function () {
  10590. return this._time;
  10591. },
  10592. set: function (value) {
  10593. this._time = value;
  10594. this.updateShaderUniforms();
  10595. },
  10596. enumerable: true,
  10597. configurable: true
  10598. });
  10599. Object.defineProperty(FireProceduralTexture.prototype, "speed", {
  10600. get: function () {
  10601. return this._speed;
  10602. },
  10603. set: function (value) {
  10604. this._speed = value;
  10605. this.updateShaderUniforms();
  10606. },
  10607. enumerable: true,
  10608. configurable: true
  10609. });
  10610. Object.defineProperty(FireProceduralTexture.prototype, "shift", {
  10611. get: function () {
  10612. return this._shift;
  10613. },
  10614. set: function (value) {
  10615. this._shift = value;
  10616. this.updateShaderUniforms();
  10617. },
  10618. enumerable: true,
  10619. configurable: true
  10620. });
  10621. Object.defineProperty(FireProceduralTexture.prototype, "alpha", {
  10622. get: function () {
  10623. return this._alpha;
  10624. },
  10625. set: function (value) {
  10626. this._alpha = value;
  10627. this.updateShaderUniforms();
  10628. },
  10629. enumerable: true,
  10630. configurable: true
  10631. });
  10632. return FireProceduralTexture;
  10633. })(BABYLON.ProceduralTexture);
  10634. BABYLON.FireProceduralTexture = FireProceduralTexture;
  10635. var CloudProceduralTexture = (function (_super) {
  10636. __extends(CloudProceduralTexture, _super);
  10637. function CloudProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  10638. _super.call(this, name, size, "cloud", scene, fallbackTexture, generateMipMaps);
  10639. this._skyColor = new BABYLON.Color3(0.15, 0.68, 1.0);
  10640. this._cloudColor = new BABYLON.Color3(1, 1, 1);
  10641. this.updateShaderUniforms();
  10642. this.refreshRate = 0;
  10643. }
  10644. CloudProceduralTexture.prototype.updateShaderUniforms = function () {
  10645. this.setColor3("skyColor", this._skyColor);
  10646. this.setColor3("cloudColor", this._cloudColor);
  10647. };
  10648. Object.defineProperty(CloudProceduralTexture.prototype, "skyColor", {
  10649. get: function () {
  10650. return this._skyColor;
  10651. },
  10652. set: function (value) {
  10653. this._skyColor = value;
  10654. this.updateShaderUniforms();
  10655. },
  10656. enumerable: true,
  10657. configurable: true
  10658. });
  10659. Object.defineProperty(CloudProceduralTexture.prototype, "cloudColor", {
  10660. get: function () {
  10661. return this._cloudColor;
  10662. },
  10663. set: function (value) {
  10664. this._cloudColor = value;
  10665. this.updateShaderUniforms();
  10666. },
  10667. enumerable: true,
  10668. configurable: true
  10669. });
  10670. return CloudProceduralTexture;
  10671. })(BABYLON.ProceduralTexture);
  10672. BABYLON.CloudProceduralTexture = CloudProceduralTexture;
  10673. var GrassProceduralTexture = (function (_super) {
  10674. __extends(GrassProceduralTexture, _super);
  10675. function GrassProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  10676. _super.call(this, name, size, "grass", scene, fallbackTexture, generateMipMaps);
  10677. this.refreshRate = 0;
  10678. }
  10679. return GrassProceduralTexture;
  10680. })(BABYLON.ProceduralTexture);
  10681. BABYLON.GrassProceduralTexture = GrassProceduralTexture;
  10682. var RockProceduralTexture = (function (_super) {
  10683. __extends(RockProceduralTexture, _super);
  10684. function RockProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  10685. _super.call(this, name, size, "rock", scene, fallbackTexture, generateMipMaps);
  10686. this.refreshRate = 0;
  10687. }
  10688. return RockProceduralTexture;
  10689. })(BABYLON.ProceduralTexture);
  10690. BABYLON.RockProceduralTexture = RockProceduralTexture;
  10691. var RoadProceduralTexture = (function (_super) {
  10692. __extends(RoadProceduralTexture, _super);
  10693. function RoadProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  10694. _super.call(this, name, size, "road", scene, fallbackTexture, generateMipMaps);
  10695. this.refreshRate = 0;
  10696. }
  10697. return RoadProceduralTexture;
  10698. })(BABYLON.ProceduralTexture);
  10699. BABYLON.RoadProceduralTexture = RoadProceduralTexture;
  10700. var BrickProceduralTexture = (function (_super) {
  10701. __extends(BrickProceduralTexture, _super);
  10702. function BrickProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  10703. _super.call(this, name, size, "brick", scene, fallbackTexture, generateMipMaps);
  10704. this._numberOfBricksHeight = 15;
  10705. this._numberOfBricksWidth = 5;
  10706. this.updateShaderUniforms();
  10707. this.refreshRate = 0;
  10708. }
  10709. BrickProceduralTexture.prototype.updateShaderUniforms = function () {
  10710. this.setFloat("numberOfBricksHeight", this._numberOfBricksHeight);
  10711. this.setFloat("numberOfBricksWidth", this._numberOfBricksWidth);
  10712. };
  10713. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksHeight", {
  10714. get: function () {
  10715. return this._numberOfBricksHeight;
  10716. },
  10717. enumerable: true,
  10718. configurable: true
  10719. });
  10720. Object.defineProperty(BrickProceduralTexture.prototype, "cloudColor", {
  10721. set: function (value) {
  10722. this._numberOfBricksHeight = value;
  10723. this.updateShaderUniforms();
  10724. },
  10725. enumerable: true,
  10726. configurable: true
  10727. });
  10728. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksWidth", {
  10729. get: function () {
  10730. return this._numberOfBricksWidth;
  10731. },
  10732. set: function (value) {
  10733. this._numberOfBricksHeight = value;
  10734. this.updateShaderUniforms();
  10735. },
  10736. enumerable: true,
  10737. configurable: true
  10738. });
  10739. return BrickProceduralTexture;
  10740. })(BABYLON.ProceduralTexture);
  10741. BABYLON.BrickProceduralTexture = BrickProceduralTexture;
  10742. var MarbleProceduralTexture = (function (_super) {
  10743. __extends(MarbleProceduralTexture, _super);
  10744. function MarbleProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  10745. _super.call(this, name, size, "marble", scene, fallbackTexture, generateMipMaps);
  10746. this._numberOfBricksHeight = 3;
  10747. this._numberOfBricksWidth = 3;
  10748. this.updateShaderUniforms();
  10749. this.refreshRate = 0;
  10750. }
  10751. MarbleProceduralTexture.prototype.updateShaderUniforms = function () {
  10752. this.setFloat("numberOfBricksHeight", this._numberOfBricksHeight);
  10753. this.setFloat("numberOfBricksWidth", this._numberOfBricksWidth);
  10754. };
  10755. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfBricksHeight", {
  10756. get: function () {
  10757. return this._numberOfBricksHeight;
  10758. },
  10759. enumerable: true,
  10760. configurable: true
  10761. });
  10762. Object.defineProperty(MarbleProceduralTexture.prototype, "cloudColor", {
  10763. set: function (value) {
  10764. this._numberOfBricksHeight = value;
  10765. this.updateShaderUniforms();
  10766. },
  10767. enumerable: true,
  10768. configurable: true
  10769. });
  10770. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfBricksWidth", {
  10771. get: function () {
  10772. return this._numberOfBricksWidth;
  10773. },
  10774. set: function (value) {
  10775. this._numberOfBricksHeight = value;
  10776. this.updateShaderUniforms();
  10777. },
  10778. enumerable: true,
  10779. configurable: true
  10780. });
  10781. return MarbleProceduralTexture;
  10782. })(BABYLON.ProceduralTexture);
  10783. BABYLON.MarbleProceduralTexture = MarbleProceduralTexture;
  10784. })(BABYLON || (BABYLON = {}));
  10785. var __extends = this.__extends || function (d, b) {
  10786. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  10787. function __() { this.constructor = d; }
  10788. __.prototype = b.prototype;
  10789. d.prototype = new __();
  10790. };
  10791. var BABYLON;
  10792. (function (BABYLON) {
  10793. var CustomProceduralTexture = (function (_super) {
  10794. __extends(CustomProceduralTexture, _super);
  10795. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  10796. _super.call(this, name, size, "empty", scene, fallbackTexture, generateMipMaps);
  10797. this._animate = true;
  10798. this._time = 0;
  10799. this._shaderLoaded = false;
  10800. this._updateTexture = false;
  10801. this._texturePath = texturePath;
  10802. this.loadJson(texturePath);
  10803. this.refreshRate = 1;
  10804. }
  10805. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  10806. function noConfigFile() {
  10807. BABYLON.Tools.Log("No config file found in " + jsonUrl);
  10808. }
  10809. var that = this;
  10810. var configFileUrl = jsonUrl + "/config.json";
  10811. var xhr = new XMLHttpRequest();
  10812. xhr.open("GET", configFileUrl, true);
  10813. xhr.addEventListener("load", function () {
  10814. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  10815. try {
  10816. that._config = JSON.parse(xhr.response);
  10817. that._updateTexture = true;
  10818. that._shaderLoaded = true;
  10819. } catch (ex) {
  10820. noConfigFile();
  10821. }
  10822. } else {
  10823. noConfigFile();
  10824. }
  10825. }, false);
  10826. xhr.addEventListener("error", function (event) {
  10827. noConfigFile();
  10828. }, false);
  10829. try {
  10830. xhr.send();
  10831. } catch (ex) {
  10832. BABYLON.Tools.Error("Error on XHR send request.");
  10833. }
  10834. };
  10835. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  10836. if (!this._shaderLoaded)
  10837. return;
  10838. if (this._updateTexture) {
  10839. this.reset();
  10840. this.setFragment(this._texturePath + "/custom");
  10841. this.updateTextures();
  10842. this.updateShaderUniforms();
  10843. this._shaderLoaded = true;
  10844. this._animate = this._config.animate;
  10845. this.refreshRate = this._config.refreshrate;
  10846. this.isReady();
  10847. this._updateTexture = false;
  10848. return;
  10849. }
  10850. if (this._animate) {
  10851. this._time += this.getScene().getAnimationRatio() * 0.03;
  10852. this.updateShaderUniforms();
  10853. }
  10854. _super.prototype.render.call(this, useCameraPostProcess);
  10855. };
  10856. CustomProceduralTexture.prototype.updateTextures = function () {
  10857. for (var i = 0; i < this._config.texture2Ds.length; i++) {
  10858. this.setTexture(this._config.texture2Ds[i].textureName, new BABYLON.Texture(this._texturePath + "/" + this._config.texture2Ds[i].textureRelativeUrl, this.getScene(), false, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, null, null, null, true));
  10859. }
  10860. };
  10861. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  10862. for (var j = 0; j < this._config.uniforms.length; j++) {
  10863. var uniform = this._config.uniforms[j];
  10864. switch (uniform.type) {
  10865. case "float":
  10866. this.setFloat(uniform.name, uniform.value);
  10867. break;
  10868. case "color3":
  10869. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  10870. break;
  10871. case "color4":
  10872. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  10873. break;
  10874. case "vector2":
  10875. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  10876. break;
  10877. case "vector3":
  10878. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  10879. break;
  10880. }
  10881. }
  10882. };
  10883. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  10884. get: function () {
  10885. return this._animate;
  10886. },
  10887. set: function (value) {
  10888. this._animate = value;
  10889. this.updateShaderUniforms();
  10890. },
  10891. enumerable: true,
  10892. configurable: true
  10893. });
  10894. return CustomProceduralTexture;
  10895. })(BABYLON.ProceduralTexture);
  10896. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  10897. })(BABYLON || (BABYLON = {}));
  10898. var __extends = this.__extends || function (d, b) {
  10899. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  10900. function __() { this.constructor = d; }
  10901. __.prototype = b.prototype;
  10902. d.prototype = new __();
  10903. };
  10904. var BABYLON;
  10905. (function (BABYLON) {
  10906. var MirrorTexture = (function (_super) {
  10907. __extends(MirrorTexture, _super);
  10908. function MirrorTexture(name, size, scene, generateMipMaps) {
  10909. var _this = this;
  10910. _super.call(this, name, size, scene, generateMipMaps, true);
  10911. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  10912. this._transformMatrix = BABYLON.Matrix.Zero();
  10913. this._mirrorMatrix = BABYLON.Matrix.Zero();
  10914. this.onBeforeRender = function () {
  10915. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  10916. _this._savedViewMatrix = scene.getViewMatrix();
  10917. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  10918. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  10919. scene.clipPlane = _this.mirrorPlane;
  10920. scene.getEngine().cullBackFaces = false;
  10921. };
  10922. this.onAfterRender = function () {
  10923. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  10924. scene.getEngine().cullBackFaces = true;
  10925. delete scene.clipPlane;
  10926. };
  10927. }
  10928. MirrorTexture.prototype.clone = function () {
  10929. var textureSize = this.getSize();
  10930. var newTexture = new BABYLON.MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  10931. newTexture.hasAlpha = this.hasAlpha;
  10932. newTexture.level = this.level;
  10933. newTexture.mirrorPlane = this.mirrorPlane.clone();
  10934. newTexture.renderList = this.renderList.slice(0);
  10935. return newTexture;
  10936. };
  10937. return MirrorTexture;
  10938. })(BABYLON.RenderTargetTexture);
  10939. BABYLON.MirrorTexture = MirrorTexture;
  10940. })(BABYLON || (BABYLON = {}));
  10941. var __extends = this.__extends || function (d, b) {
  10942. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  10943. function __() { this.constructor = d; }
  10944. __.prototype = b.prototype;
  10945. d.prototype = new __();
  10946. };
  10947. var BABYLON;
  10948. (function (BABYLON) {
  10949. var DynamicTexture = (function (_super) {
  10950. __extends(DynamicTexture, _super);
  10951. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  10952. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  10953. _super.call(this, null, scene, !generateMipMaps);
  10954. this.name = name;
  10955. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  10956. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  10957. this._generateMipMaps = generateMipMaps;
  10958. if (options.getContext) {
  10959. this._canvas = options;
  10960. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  10961. } else {
  10962. this._canvas = document.createElement("canvas");
  10963. if (options.width) {
  10964. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  10965. } else {
  10966. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  10967. }
  10968. }
  10969. var textureSize = this.getSize();
  10970. this._canvas.width = textureSize.width;
  10971. this._canvas.height = textureSize.height;
  10972. this._context = this._canvas.getContext("2d");
  10973. }
  10974. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  10975. get: function () {
  10976. return true;
  10977. },
  10978. enumerable: true,
  10979. configurable: true
  10980. });
  10981. DynamicTexture.prototype.scale = function (ratio) {
  10982. var textureSize = this.getSize();
  10983. textureSize.width *= ratio;
  10984. textureSize.height *= ratio;
  10985. this._canvas.width = textureSize.width;
  10986. this._canvas.height = textureSize.height;
  10987. this.releaseInternalTexture();
  10988. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  10989. };
  10990. DynamicTexture.prototype.getContext = function () {
  10991. return this._context;
  10992. };
  10993. DynamicTexture.prototype.update = function (invertY) {
  10994. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  10995. };
  10996. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY) {
  10997. var size = this.getSize();
  10998. if (clearColor) {
  10999. this._context.fillStyle = clearColor;
  11000. this._context.fillRect(0, 0, size.width, size.height);
  11001. }
  11002. this._context.font = font;
  11003. if (x === null) {
  11004. var textSize = this._context.measureText(text);
  11005. x = (size.width - textSize.width) / 2;
  11006. }
  11007. this._context.fillStyle = color;
  11008. this._context.fillText(text, x, y);
  11009. this.update(invertY);
  11010. };
  11011. DynamicTexture.prototype.clone = function () {
  11012. var textureSize = this.getSize();
  11013. var newTexture = new BABYLON.DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  11014. newTexture.hasAlpha = this.hasAlpha;
  11015. newTexture.level = this.level;
  11016. newTexture.wrapU = this.wrapU;
  11017. newTexture.wrapV = this.wrapV;
  11018. return newTexture;
  11019. };
  11020. return DynamicTexture;
  11021. })(BABYLON.Texture);
  11022. BABYLON.DynamicTexture = DynamicTexture;
  11023. })(BABYLON || (BABYLON = {}));
  11024. var __extends = this.__extends || function (d, b) {
  11025. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  11026. function __() { this.constructor = d; }
  11027. __.prototype = b.prototype;
  11028. d.prototype = new __();
  11029. };
  11030. var BABYLON;
  11031. (function (BABYLON) {
  11032. var VideoTexture = (function (_super) {
  11033. __extends(VideoTexture, _super);
  11034. function VideoTexture(name, urls, size, scene, generateMipMaps, invertY, samplingMode) {
  11035. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  11036. var _this = this;
  11037. _super.call(this, null, scene, !generateMipMaps, invertY);
  11038. this._autoLaunch = true;
  11039. this.name = name;
  11040. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  11041. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  11042. var requiredWidth = size.width || size;
  11043. var requiredHeight = size.height || size;
  11044. this._texture = scene.getEngine().createDynamicTexture(requiredWidth, requiredHeight, generateMipMaps, samplingMode);
  11045. var textureSize = this.getSize();
  11046. this.video = document.createElement("video");
  11047. this.video.width = textureSize.width;
  11048. this.video.height = textureSize.height;
  11049. this.video.autoplay = false;
  11050. this.video.loop = true;
  11051. this.video.addEventListener("canplaythrough", function () {
  11052. if (_this._texture) {
  11053. _this._texture.isReady = true;
  11054. }
  11055. });
  11056. urls.forEach(function (url) {
  11057. var source = document.createElement("source");
  11058. source.src = url;
  11059. _this.video.appendChild(source);
  11060. });
  11061. this._lastUpdate = BABYLON.Tools.Now;
  11062. }
  11063. VideoTexture.prototype.update = function () {
  11064. if (this._autoLaunch) {
  11065. this._autoLaunch = false;
  11066. this.video.play();
  11067. }
  11068. var now = BABYLON.Tools.Now;
  11069. if (now - this._lastUpdate < 15) {
  11070. return false;
  11071. }
  11072. this._lastUpdate = now;
  11073. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  11074. return true;
  11075. };
  11076. return VideoTexture;
  11077. })(BABYLON.Texture);
  11078. BABYLON.VideoTexture = VideoTexture;
  11079. })(BABYLON || (BABYLON = {}));
  11080. var BABYLON;
  11081. (function (BABYLON) {
  11082. var EffectFallbacks = (function () {
  11083. function EffectFallbacks() {
  11084. this._defines = {};
  11085. this._currentRank = 32;
  11086. this._maxRank = -1;
  11087. }
  11088. EffectFallbacks.prototype.addFallback = function (rank, define) {
  11089. if (!this._defines[rank]) {
  11090. if (rank < this._currentRank) {
  11091. this._currentRank = rank;
  11092. }
  11093. if (rank > this._maxRank) {
  11094. this._maxRank = rank;
  11095. }
  11096. this._defines[rank] = new Array();
  11097. }
  11098. this._defines[rank].push(define);
  11099. };
  11100. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  11101. get: function () {
  11102. return this._currentRank <= this._maxRank;
  11103. },
  11104. enumerable: true,
  11105. configurable: true
  11106. });
  11107. EffectFallbacks.prototype.reduce = function (currentDefines) {
  11108. var currentFallbacks = this._defines[this._currentRank];
  11109. for (var index = 0; index < currentFallbacks.length; index++) {
  11110. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  11111. }
  11112. this._currentRank++;
  11113. return currentDefines;
  11114. };
  11115. return EffectFallbacks;
  11116. })();
  11117. BABYLON.EffectFallbacks = EffectFallbacks;
  11118. var Effect = (function () {
  11119. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  11120. var _this = this;
  11121. this._isReady = false;
  11122. this._compilationError = "";
  11123. this._valueCache = [];
  11124. this._engine = engine;
  11125. this.name = baseName;
  11126. this.defines = defines;
  11127. this._uniformsNames = uniformsNames.concat(samplers);
  11128. this._samplers = samplers;
  11129. this._attributesNames = attributesNames;
  11130. this.onError = onError;
  11131. this.onCompiled = onCompiled;
  11132. var vertexSource;
  11133. var fragmentSource;
  11134. if (baseName.vertexElement) {
  11135. vertexSource = document.getElementById(baseName.vertexElement);
  11136. if (!vertexSource) {
  11137. vertexSource = baseName.vertexElement;
  11138. }
  11139. } else {
  11140. vertexSource = baseName.vertex || baseName;
  11141. }
  11142. if (baseName.fragmentElement) {
  11143. fragmentSource = document.getElementById(baseName.fragmentElement);
  11144. if (!fragmentSource) {
  11145. fragmentSource = baseName.fragmentElement;
  11146. }
  11147. } else {
  11148. fragmentSource = baseName.fragment || baseName;
  11149. }
  11150. this._loadVertexShader(vertexSource, function (vertexCode) {
  11151. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  11152. _this._prepareEffect(vertexCode, fragmentCode, attributesNames, defines, fallbacks);
  11153. });
  11154. });
  11155. }
  11156. Effect.prototype.isReady = function () {
  11157. return this._isReady;
  11158. };
  11159. Effect.prototype.getProgram = function () {
  11160. return this._program;
  11161. };
  11162. Effect.prototype.getAttributesNames = function () {
  11163. return this._attributesNames;
  11164. };
  11165. Effect.prototype.getAttributeLocation = function (index) {
  11166. return this._attributes[index];
  11167. };
  11168. Effect.prototype.getAttributeLocationByName = function (name) {
  11169. var index = this._attributesNames.indexOf(name);
  11170. return this._attributes[index];
  11171. };
  11172. Effect.prototype.getAttributesCount = function () {
  11173. return this._attributes.length;
  11174. };
  11175. Effect.prototype.getUniformIndex = function (uniformName) {
  11176. return this._uniformsNames.indexOf(uniformName);
  11177. };
  11178. Effect.prototype.getUniform = function (uniformName) {
  11179. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  11180. };
  11181. Effect.prototype.getSamplers = function () {
  11182. return this._samplers;
  11183. };
  11184. Effect.prototype.getCompilationError = function () {
  11185. return this._compilationError;
  11186. };
  11187. Effect.prototype._loadVertexShader = function (vertex, callback) {
  11188. if (vertex instanceof HTMLElement) {
  11189. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  11190. callback(vertexCode);
  11191. return;
  11192. }
  11193. if (BABYLON.Effect.ShadersStore[vertex + "VertexShader"]) {
  11194. callback(BABYLON.Effect.ShadersStore[vertex + "VertexShader"]);
  11195. return;
  11196. }
  11197. var vertexShaderUrl;
  11198. if (vertex[0] === ".") {
  11199. vertexShaderUrl = vertex;
  11200. } else {
  11201. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  11202. }
  11203. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  11204. };
  11205. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  11206. if (fragment instanceof HTMLElement) {
  11207. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  11208. callback(fragmentCode);
  11209. return;
  11210. }
  11211. if (BABYLON.Effect.ShadersStore[fragment + "PixelShader"]) {
  11212. callback(BABYLON.Effect.ShadersStore[fragment + "PixelShader"]);
  11213. return;
  11214. }
  11215. if (BABYLON.Effect.ShadersStore[fragment + "FragmentShader"]) {
  11216. callback(BABYLON.Effect.ShadersStore[fragment + "FragmentShader"]);
  11217. return;
  11218. }
  11219. var fragmentShaderUrl;
  11220. if (fragment[0] === ".") {
  11221. fragmentShaderUrl = fragment;
  11222. } else {
  11223. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  11224. }
  11225. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  11226. };
  11227. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  11228. try {
  11229. var engine = this._engine;
  11230. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  11231. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  11232. this._attributes = engine.getAttributes(this._program, attributesNames);
  11233. for (var index = 0; index < this._samplers.length; index++) {
  11234. var sampler = this.getUniform(this._samplers[index]);
  11235. if (sampler == null) {
  11236. this._samplers.splice(index, 1);
  11237. index--;
  11238. }
  11239. }
  11240. engine.bindSamplers(this);
  11241. this._isReady = true;
  11242. if (this.onCompiled) {
  11243. this.onCompiled(this);
  11244. }
  11245. } catch (e) {
  11246. if (e.message.indexOf("highp") !== -1) {
  11247. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  11248. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  11249. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  11250. return;
  11251. }
  11252. if (fallbacks && fallbacks.isMoreFallbacks) {
  11253. defines = fallbacks.reduce(defines);
  11254. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  11255. } else {
  11256. BABYLON.Tools.Error("Unable to compile effect: " + this.name);
  11257. BABYLON.Tools.Error("Defines: " + defines);
  11258. BABYLON.Tools.Error("Error: " + e.message);
  11259. this._compilationError = e.message;
  11260. if (this.onError) {
  11261. this.onError(this, this._compilationError);
  11262. }
  11263. }
  11264. }
  11265. };
  11266. Effect.prototype._bindTexture = function (channel, texture) {
  11267. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  11268. };
  11269. Effect.prototype.setTexture = function (channel, texture) {
  11270. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  11271. };
  11272. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  11273. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  11274. };
  11275. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  11276. if (!this._valueCache[uniformName]) {
  11277. this._valueCache[uniformName] = [x, y];
  11278. return;
  11279. }
  11280. this._valueCache[uniformName][0] = x;
  11281. this._valueCache[uniformName][1] = y;
  11282. };
  11283. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  11284. if (!this._valueCache[uniformName]) {
  11285. this._valueCache[uniformName] = [x, y, z];
  11286. return;
  11287. }
  11288. this._valueCache[uniformName][0] = x;
  11289. this._valueCache[uniformName][1] = y;
  11290. this._valueCache[uniformName][2] = z;
  11291. };
  11292. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  11293. if (!this._valueCache[uniformName]) {
  11294. this._valueCache[uniformName] = [x, y, z, w];
  11295. return;
  11296. }
  11297. this._valueCache[uniformName][0] = x;
  11298. this._valueCache[uniformName][1] = y;
  11299. this._valueCache[uniformName][2] = z;
  11300. this._valueCache[uniformName][3] = w;
  11301. };
  11302. Effect.prototype.setArray = function (uniformName, array) {
  11303. this._engine.setArray(this.getUniform(uniformName), array);
  11304. return this;
  11305. };
  11306. Effect.prototype.setMatrices = function (uniformName, matrices) {
  11307. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  11308. return this;
  11309. };
  11310. Effect.prototype.setMatrix = function (uniformName, matrix) {
  11311. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  11312. return this;
  11313. };
  11314. Effect.prototype.setFloat = function (uniformName, value) {
  11315. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  11316. return this;
  11317. this._valueCache[uniformName] = value;
  11318. this._engine.setFloat(this.getUniform(uniformName), value);
  11319. return this;
  11320. };
  11321. Effect.prototype.setBool = function (uniformName, bool) {
  11322. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  11323. return this;
  11324. this._valueCache[uniformName] = bool;
  11325. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  11326. return this;
  11327. };
  11328. Effect.prototype.setVector2 = function (uniformName, vector2) {
  11329. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] == vector2.x && this._valueCache[uniformName][1] == vector2.y)
  11330. return this;
  11331. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  11332. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  11333. return this;
  11334. };
  11335. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  11336. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] == x && this._valueCache[uniformName][1] == y)
  11337. return this;
  11338. this._cacheFloat2(uniformName, x, y);
  11339. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  11340. return this;
  11341. };
  11342. Effect.prototype.setVector3 = function (uniformName, vector3) {
  11343. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] == vector3.x && this._valueCache[uniformName][1] == vector3.y && this._valueCache[uniformName][2] == vector3.z)
  11344. return this;
  11345. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  11346. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  11347. return this;
  11348. };
  11349. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  11350. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] == x && this._valueCache[uniformName][1] == y && this._valueCache[uniformName][2] == z)
  11351. return this;
  11352. this._cacheFloat3(uniformName, x, y, z);
  11353. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  11354. return this;
  11355. };
  11356. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  11357. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] == x && this._valueCache[uniformName][1] == y && this._valueCache[uniformName][2] == z && this._valueCache[uniformName][3] == w)
  11358. return this;
  11359. this._cacheFloat4(uniformName, x, y, z, w);
  11360. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  11361. return this;
  11362. };
  11363. Effect.prototype.setColor3 = function (uniformName, color3) {
  11364. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] == color3.r && this._valueCache[uniformName][1] == color3.g && this._valueCache[uniformName][2] == color3.b)
  11365. return this;
  11366. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  11367. this._engine.setColor3(this.getUniform(uniformName), color3);
  11368. return this;
  11369. };
  11370. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  11371. 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)
  11372. return this;
  11373. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  11374. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  11375. return this;
  11376. };
  11377. 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}",
  11378. 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}",
  11379. 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}",
  11380. brickPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\n\nuniform float numberOfBricksHeight;\nuniform float numberOfBricksWidth;\n\nfloat rand(vec2 n) {\n return fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\n}\n\nfloat noise(vec2 n) {\n const vec2 d = vec2(0.0, 1.0);\n vec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\n return mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\n}\n\nfloat fbm(vec2 n) {\n float total = 0.0, amplitude = 1.0;\n for (int i = 0; i < 4; i++) {\n total += noise(n) * amplitude;\n n += n;\n amplitude *= 0.5;\n }\n return total;\n}\n\nfloat round(float number){\n return sign(number)*floor(abs(number) + 0.5);\n}\n\nvoid main(void)\n{\n vec3 brick = vec3(0.77, 0.47, 0.40);\n vec3 joint = vec3(0.72, 0.72, 0.72);\n\n float brickW = 1.0 / numberOfBricksWidth;\n float brickH = 1.0 / numberOfBricksHeight;\n float jointWPercentage = 0.01;\n float jointHPercentage = 0.05;\n\n vec3 color = brick;\n\n\n float yi = vUV.y / brickH;\n float nyi = round(yi);\n\n float xi = vUV.x / brickW;\n\n if (mod(floor(yi), 2.0) == 0.0){\n xi = xi - 0.5;\n }\n\n float nxi = round(xi);\n\n vec2 brickvUV = vec2((xi - floor(xi)) / brickH, (yi - floor(yi)) / brickW);\n\n\n if (yi < nyi + jointHPercentage && yi > nyi - jointHPercentage){\n color = mix(joint, vec3(0.37, 0.25, 0.25), (yi - nyi) / jointHPercentage + 0.2);\n }\n else if (xi < nxi + jointWPercentage && xi > nxi - jointWPercentage){\n color = mix(joint, vec3(0.44, 0.44, 0.44), (xi - nxi) / jointWPercentage + 0.2);\n }\n else {\n float momo = mod(floor(yi) + floor(xi), 3.0);\n\n if (momo == 0.0)\n color = mix(color, vec3(0.33, 0.33, 0.33), 0.3);\n else if (momo == 2.0)\n color = mix(color, vec3(0.11, 0.11, 0.11), 0.3);\n\n\n //color = mix(momo, vec3(0.53, 0.2, 0.0), fbm(brickvUV * 2.0));\n }\n\n\n gl_FragColor = vec4(color, 1.0);\n}",
  11381. cloudPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vUV;\n\nuniform vec3 skyColor;\nuniform vec3 cloudColor;\n\nfloat rand(vec2 n) {\n return fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\n}\n\nfloat noise(vec2 n) {\n const vec2 d = vec2(0.0, 1.0);\n vec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\n return mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\n}\n\nfloat fbm(vec2 n) {\n float total = 0.0, amplitude = 1.0;\n for (int i = 0; i < 4; i++) {\n total += noise(n) * amplitude;\n n += n;\n amplitude *= 0.5;\n }\n return total;\n}\n\nvoid main() {\n\n vec2 p = vUV * 12.0;\n vec3 c = mix(skyColor, cloudColor, fbm(p));\n gl_FragColor = vec4(c, 1);\n\n}",
  11382. colorPixelShader:"precision highp float;\n\nuniform vec4 color;\n\nvoid main(void) {\n gl_FragColor = color;\n}",
  11383. 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}",
  11384. 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}",
  11385. defaultPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n#define MAP_EXPLICIT 0.\n#define MAP_SPHERICAL 1.\n#define MAP_PLANAR 2.\n#define MAP_CUBIC 3.\n#define MAP_PROJECTION 4.\n#define MAP_SKYBOX 5.\n\n// Constants\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vDiffuseColor;\nuniform vec4 vSpecularColor;\nuniform vec3 vEmissiveColor;\n\n// Input\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n// Lights\n#ifdef LIGHT0\nuniform vec4 vLightData0;\nuniform vec4 vLightDiffuse0;\nuniform vec3 vLightSpecular0;\n#ifdef SHADOW0\nvarying vec4 vPositionFromLight0;\nuniform sampler2D shadowSampler0;\nuniform float darkness0;\n#endif\n#ifdef SPOTLIGHT0\nuniform vec4 vLightDirection0;\n#endif\n#ifdef HEMILIGHT0\nuniform vec3 vLightGround0;\n#endif\n#endif\n\n#ifdef LIGHT1\nuniform vec4 vLightData1;\nuniform vec4 vLightDiffuse1;\nuniform vec3 vLightSpecular1;\n#ifdef SHADOW1\nvarying vec4 vPositionFromLight1;\nuniform sampler2D shadowSampler1;\nuniform float darkness1;\n#endif\n#ifdef SPOTLIGHT1\nuniform vec4 vLightDirection1;\n#endif\n#ifdef HEMILIGHT1\nuniform vec3 vLightGround1;\n#endif\n#endif\n\n#ifdef LIGHT2\nuniform vec4 vLightData2;\nuniform vec4 vLightDiffuse2;\nuniform vec3 vLightSpecular2;\n#ifdef SHADOW2\nvarying vec4 vPositionFromLight2;\nuniform sampler2D shadowSampler2;\nuniform float darkness2;\n#endif\n#ifdef SPOTLIGHT2\nuniform vec4 vLightDirection2;\n#endif\n#ifdef HEMILIGHT2\nuniform vec3 vLightGround2;\n#endif\n#endif\n\n#ifdef LIGHT3\nuniform vec4 vLightData3;\nuniform vec4 vLightDiffuse3;\nuniform vec3 vLightSpecular3;\n#ifdef SHADOW3\nvarying vec4 vPositionFromLight3;\nuniform sampler2D shadowSampler3;\nuniform float darkness3;\n#endif\n#ifdef SPOTLIGHT3\nuniform vec4 vLightDirection3;\n#endif\n#ifdef HEMILIGHT3\nuniform vec3 vLightGround3;\n#endif\n#endif\n\n// Samplers\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\nuniform vec2 vDiffuseInfos;\n#endif\n\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec2 vAmbientInfos;\n#endif\n\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n\n#ifdef SPECULAR\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform sampler2D specularSampler;\n#endif\n\n// Fresnel\n#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection, vec3 worldNormal, float bias, float power)\n{\n float fresnelTerm = pow(bias + abs(dot(viewDirection, worldNormal)), power);\n return clamp(fresnelTerm, 0., 1.);\n}\n#endif\n\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n// Reflection\n#ifdef REFLECTION\nvarying vec3 vPositionUVW;\nuniform samplerCube reflectionCubeSampler;\nuniform sampler2D reflection2DSampler;\nuniform vec3 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform mat4 view;\n\nvec3 computeReflectionCoords(float mode, vec4 worldPos, vec3 worldNormal)\n{\n if (mode == MAP_SPHERICAL)\n {\n vec3 coords = vec3(view * vec4(worldNormal, 0.0));\n\n return vec3(reflectionMatrix * vec4(coords, 1.0));\n }\n else if (mode == MAP_PLANAR)\n {\n vec3 viewDir = worldPos.xyz - vEyePosition;\n vec3 coords = normalize(reflect(viewDir, worldNormal));\n\n return vec3(reflectionMatrix * vec4(coords, 1));\n }\n else if (mode == MAP_CUBIC)\n {\n vec3 viewDir = worldPos.xyz - vEyePosition;\n vec3 coords = reflect(viewDir, worldNormal);\n\n return vec3(reflectionMatrix * vec4(coords, 0));\n }\n else if (mode == MAP_PROJECTION)\n {\n return vec3(reflectionMatrix * (view * worldPos));\n }\n else if (mode == MAP_SKYBOX)\n {\n return vPositionUVW;\n }\n\n return vec3(0, 0, 0);\n}\n#endif\n\n// Shadows\n#ifdef SHADOWS\n\nfloat unpack(vec4 color)\n{\n const vec4 bitShift = vec4(1. / (255. * 255. * 255.), 1. / (255. * 255.), 1. / 255., 1.);\n return dot(color, bitShift);\n}\n\nfloat unpackHalf(vec2 color)\n{\n return color.x + (color.y / 255.0);\n}\n\nfloat computeShadow(vec4 vPositionFromLight, sampler2D shadowSampler, float darkness)\n{\n vec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\n vec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\n\n if (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n {\n return 1.0;\n }\n\n float shadow = unpack(texture2D(shadowSampler, uv));\n\n if (depth.z > shadow)\n {\n return darkness;\n }\n return 1.;\n}\n\nfloat computeShadowWithPCF(vec4 vPositionFromLight, sampler2D shadowSampler)\n{\n vec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\n vec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\n\n if (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n {\n return 1.0;\n }\n\n float visibility = 1.;\n\n vec2 poissonDisk[4];\n poissonDisk[0] = vec2(-0.94201624, -0.39906216);\n poissonDisk[1] = vec2(0.94558609, -0.76890725);\n poissonDisk[2] = vec2(-0.094184101, -0.92938870);\n poissonDisk[3] = vec2(0.34495938, 0.29387760);\n\n // Poisson Sampling\n if (unpack(texture2D(shadowSampler, uv + poissonDisk[0] / 1500.0)) < depth.z) visibility -= 0.2;\n if (unpack(texture2D(shadowSampler, uv + poissonDisk[1] / 1500.0)) < depth.z) visibility -= 0.2;\n if (unpack(texture2D(shadowSampler, uv + poissonDisk[2] / 1500.0)) < depth.z) visibility -= 0.2;\n if (unpack(texture2D(shadowSampler, uv + poissonDisk[3] / 1500.0)) < depth.z) visibility -= 0.2;\n\n return visibility;\n}\n\n// Thanks to http://devmaster.net/\nfloat ChebychevInequality(vec2 moments, float t)\n{\n if (t <= moments.x)\n {\n return 1.0;\n }\n\n float variance = moments.y - (moments.x * moments.x);\n variance = max(variance, 0.);\n\n float d = t - moments.x;\n return variance / (variance + d * d);\n}\n\nfloat computeShadowWithVSM(vec4 vPositionFromLight, sampler2D shadowSampler)\n{\n vec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\n vec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\n\n if (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n {\n return 1.0;\n }\n\n vec4 texel = texture2D(shadowSampler, uv);\n\n vec2 moments = vec2(unpackHalf(texel.xy), unpackHalf(texel.zw));\n return clamp(1.3 - ChebychevInequality(moments, depth.z), 0., 1.0);\n}\n#endif\n\n// Bump\n#ifdef BUMP\n#extension GL_OES_standard_derivatives : enable\nvarying vec2 vBumpUV;\nuniform vec2 vBumpInfos;\nuniform sampler2D bumpSampler;\n\n// Thanks to http://www.thetenthplanet.de/archives/1180\nmat3 cotangent_frame(vec3 normal, vec3 p, vec2 uv)\n{\n // get edge vectors of the pixel triangle\n vec3 dp1 = dFdx(p);\n vec3 dp2 = dFdy(p);\n vec2 duv1 = dFdx(uv);\n vec2 duv2 = dFdy(uv);\n\n // solve the linear system\n vec3 dp2perp = cross(dp2, normal);\n vec3 dp1perp = cross(normal, dp1);\n vec3 tangent = dp2perp * duv1.x + dp1perp * duv2.x;\n vec3 binormal = dp2perp * duv1.y + dp1perp * duv2.y;\n\n // construct a scale-invariant frame \n float invmax = inversesqrt(max(dot(tangent, tangent), dot(binormal, binormal)));\n return mat3(tangent * invmax, binormal * invmax, normal);\n}\n\nvec3 perturbNormal(vec3 viewDir)\n{\n vec3 map = texture2D(bumpSampler, vBumpUV).xyz * 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 baseColor.rgb *= vColor.rgb;\n#endif\n\n#ifdef DIFFUSE\n baseColor = texture2D(diffuseSampler, vDiffuseUV);\n\n#ifdef ALPHATEST\n if (baseColor.a < 0.4)\n discard;\n#endif\n\n#ifdef ALPHAFROMDIFFUSE\n alpha *= baseColor.a;\n#endif\n\n baseColor.rgb *= vDiffuseInfos.y;\n#endif\n\n // Bump\n vec3 normalW = normalize(vNormalW);\n\n#ifdef BUMP\n normalW = perturbNormal(viewDirectionW);\n#endif\n\n // Ambient color\n vec3 baseAmbientColor = vec3(1., 1., 1.);\n\n#ifdef AMBIENT\n baseAmbientColor = texture2D(ambientSampler, vAmbientUV).rgb * vAmbientInfos.y;\n#endif\n\n // Lighting\n vec3 diffuseBase = vec3(0., 0., 0.);\n vec3 specularBase = vec3(0., 0., 0.);\n float shadow = 1.;\n\n#ifdef LIGHT0\n#ifdef SPOTLIGHT0\n lightingInfo info = computeSpotLighting(viewDirectionW, normalW, vLightData0, vLightDirection0, vLightDiffuse0.rgb, vLightSpecular0, vLightDiffuse0.a);\n#endif\n#ifdef HEMILIGHT0\n lightingInfo info = computeHemisphericLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0.rgb, vLightSpecular0, vLightGround0);\n#endif\n#ifdef POINTDIRLIGHT0\n lightingInfo info = computeLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0.rgb, vLightSpecular0, vLightDiffuse0.a);\n#endif\n#ifdef SHADOW0\n#ifdef SHADOWVSM0\n shadow = computeShadowWithVSM(vPositionFromLight0, shadowSampler0);\n#else\n #ifdef SHADOWPCF0\n shadow = computeShadowWithPCF(vPositionFromLight0, shadowSampler0);\n #else\n shadow = computeShadow(vPositionFromLight0, shadowSampler0, darkness0);\n #endif\n#endif\n#else\n shadow = 1.;\n#endif\n diffuseBase += info.diffuse * shadow;\n specularBase += info.specular * shadow;\n#endif\n\n#ifdef LIGHT1\n#ifdef SPOTLIGHT1\n info = computeSpotLighting(viewDirectionW, normalW, vLightData1, vLightDirection1, vLightDiffuse1.rgb, vLightSpecular1, vLightDiffuse1.a);\n#endif\n#ifdef HEMILIGHT1\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightSpecular1, vLightGround1);\n#endif\n#ifdef POINTDIRLIGHT1\n info = computeLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightSpecular1, vLightDiffuse1.a);\n#endif\n#ifdef SHADOW1\n#ifdef SHADOWVSM1\n shadow = computeShadowWithVSM(vPositionFromLight1, shadowSampler1);\n#else\n #ifdef SHADOWPCF1\n shadow = computeShadowWithPCF(vPositionFromLight1, shadowSampler1);\n #else\n shadow = computeShadow(vPositionFromLight1, shadowSampler1, darkness1);\n #endif\n#endif\n#else\n shadow = 1.;\n#endif\n diffuseBase += info.diffuse * shadow;\n specularBase += info.specular * shadow;\n#endif\n\n#ifdef LIGHT2\n#ifdef SPOTLIGHT2\n info = computeSpotLighting(viewDirectionW, normalW, vLightData2, vLightDirection2, vLightDiffuse2.rgb, vLightSpecular2, vLightDiffuse2.a);\n#endif\n#ifdef HEMILIGHT2\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightSpecular2, vLightGround2);\n#endif\n#ifdef POINTDIRLIGHT2\n info = computeLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightSpecular2, vLightDiffuse2.a);\n#endif\n#ifdef SHADOW2\n#ifdef SHADOWVSM2\n shadow = computeShadowWithVSM(vPositionFromLight2, shadowSampler2);\n#else\n #ifdef SHADOWPCF2\n shadow = computeShadowWithPCF(vPositionFromLight2, shadowSampler2);\n #else\n shadow = computeShadow(vPositionFromLight2, shadowSampler2, darkness2);\n #endif \n#endif \n#else\n shadow = 1.;\n#endif\n diffuseBase += info.diffuse * shadow;\n specularBase += info.specular * shadow;\n#endif\n\n#ifdef LIGHT3\n#ifdef SPOTLIGHT3\n info = computeSpotLighting(viewDirectionW, normalW, vLightData3, vLightDirection3, vLightDiffuse3.rgb, vLightSpecular3, vLightDiffuse3.a);\n#endif\n#ifdef HEMILIGHT3\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightSpecular3, vLightGround3);\n#endif\n#ifdef POINTDIRLIGHT3\n info = computeLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightSpecular3, vLightDiffuse3.a);\n#endif\n#ifdef SHADOW3\n#ifdef SHADOWVSM3\n shadow = computeShadowWithVSM(vPositionFromLight3, shadowSampler3);\n#else\n #ifdef SHADOWPCF3\n shadow = computeShadowWithPCF(vPositionFromLight3, shadowSampler3);\n #else\n shadow = computeShadow(vPositionFromLight3, shadowSampler3, darkness3);\n #endif \n#endif \n#else\n shadow = 1.;\n#endif\n diffuseBase += info.diffuse * shadow;\n specularBase += info.specular * shadow;\n#endif\n\n // Reflection\n vec3 reflectionColor = vec3(0., 0., 0.);\n\n#ifdef REFLECTION\n vec3 vReflectionUVW = computeReflectionCoords(vReflectionInfos.x, vec4(vPositionW, 1.0), normalW);\n\n if (vReflectionInfos.z != 0.0)\n {\n reflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW).rgb * vReflectionInfos.y * shadow;\n }\n else\n {\n vec2 coords = vReflectionUVW.xy;\n\n if (vReflectionInfos.x == MAP_PROJECTION)\n {\n coords /= vReflectionUVW.z;\n }\n\n coords.y = 1.0 - coords.y;\n\n reflectionColor = texture2D(reflection2DSampler, coords).rgb * vReflectionInfos.y * shadow;\n }\n\n#ifdef REFLECTIONFRESNEL\n float reflectionFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, reflectionRightColor.a, reflectionLeftColor.a);\n\n reflectionColor *= reflectionLeftColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\n#endif\n#endif\n\n#ifdef OPACITY\n vec4 opacityMap = texture2D(opacitySampler, vOpacityUV);\n\n#ifdef OPACITYRGB\n opacityMap.rgb = opacityMap.rgb * vec3(0.3, 0.59, 0.11);\n alpha *= (opacityMap.x + opacityMap.y + opacityMap.z)* vOpacityInfos.y;\n#else\n alpha *= opacityMap.a * vOpacityInfos.y;\n#endif\n\n#endif\n\n#ifdef VERTEXALPHA\n alpha *= vColor.a;\n#endif\n\n#ifdef OPACITYFRESNEL\n float opacityFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, opacityParts.z, opacityParts.w);\n\n alpha += opacityParts.x * (1.0 - opacityFresnelTerm) + opacityFresnelTerm * opacityParts.y;\n#endif\n\n // Emissive\n vec3 emissiveColor = vEmissiveColor;\n#ifdef EMISSIVE\n emissiveColor += texture2D(emissiveSampler, vEmissiveUV).rgb * vEmissiveInfos.y;\n#endif\n\n#ifdef EMISSIVEFRESNEL\n float emissiveFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, emissiveRightColor.a, emissiveLeftColor.a);\n\n emissiveColor *= emissiveLeftColor.rgb * (1.0 - emissiveFresnelTerm) + emissiveFresnelTerm * emissiveRightColor.rgb;\n#endif\n\n // Specular map\n vec3 specularColor = vSpecularColor.rgb;\n#ifdef SPECULAR\n specularColor = texture2D(specularSampler, vSpecularUV).rgb * vSpecularInfos.y;\n#endif\n\n // Fresnel\n#ifdef DIFFUSEFRESNEL\n float diffuseFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, diffuseRightColor.a, diffuseLeftColor.a);\n\n diffuseBase *= diffuseLeftColor.rgb * (1.0 - diffuseFresnelTerm) + diffuseFresnelTerm * diffuseRightColor.rgb;\n#endif\n\n // Composition\n vec3 finalDiffuse = clamp(diffuseBase * diffuseColor + emissiveColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\n vec3 finalSpecular = specularBase * specularColor;\n\n#ifdef SPECULAROVERALPHA\n alpha = clamp(alpha + dot(finalSpecular, vec3(0.3, 0.59, 0.11)), 0., 1.);\n#endif\n\n vec4 color = vec4(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor, alpha);\n\n#ifdef FOG\n float fog = CalcFogFactor();\n color.rgb = fog * color.rgb + (1.0 - fog) * vFogColor;\n#endif\n\n gl_FragColor = color;\n}",
  11386. defaultVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Attributes\nattribute vec3 position;\nattribute vec3 normal;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#ifdef BONES\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#endif\n\n// Uniforms\n\n#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif\n\nuniform mat4 view;\nuniform mat4 viewProjection;\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n\n#ifdef SPECULAR\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec2 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n\n#ifdef BONES\nuniform mat4 mBones[BonesPerMesh];\n#endif\n\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\n// Output\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif\n\n#ifdef FOG\nvarying float fFogDistance;\n#endif\n\n#ifdef SHADOWS\n#ifdef LIGHT0\nuniform mat4 lightMatrix0;\nvarying vec4 vPositionFromLight0;\n#endif\n#ifdef LIGHT1\nuniform mat4 lightMatrix1;\nvarying vec4 vPositionFromLight1;\n#endif\n#ifdef LIGHT2\nuniform mat4 lightMatrix2;\nvarying vec4 vPositionFromLight2;\n#endif\n#ifdef LIGHT3\nuniform mat4 lightMatrix3;\nvarying vec4 vPositionFromLight3;\n#endif\n#endif\n\n#ifdef REFLECTION\nvarying vec3 vPositionUVW;\n#endif\n\nvoid main(void) {\n mat4 finalWorld;\n\n#ifdef REFLECTION\n vPositionUVW = position;\n#endif \n\n#ifdef 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\n // Point size\n#ifdef POINTSIZE\n gl_PointSize = pointSize;\n#endif\n}",
  11387. 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}",
  11388. emptyPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvoid main(void)\n{\n \n}",
  11389. 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}",
  11390. 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}",
  11391. 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}",
  11392. grassPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\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 vec3 herb1 = vec3(0.29, 0.38, 0.02);\n vec3 herb2 = vec3(0.36, 0.49, 0.09);\n vec3 herb3 = vec3(0.51, 0.6, 0.28);\n vec3 dirt = vec3(0.6, 0.46, 0.13);\n\n vec3 ground = vec3(1,1,1);\n \n ground = mix(ground, herb1, rand(gl_FragCoord.xy * 4.0));\n ground = mix(ground, herb2, rand(gl_FragCoord.xy * 8.0));\n ground = mix(ground, herb3, rand(gl_FragCoord.xy));\n ground = mix(ground, herb1, fbm(gl_FragCoord.xy * 16.0));\n\n gl_FragColor = vec4(ground, 1.0);\n}",
  11393. 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}",
  11394. 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}",
  11395. legacydefaultPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n#define MAP_PROJECTION 4.\n\n// Constants\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vDiffuseColor;\nuniform vec4 vSpecularColor;\nuniform vec3 vEmissiveColor;\n\n// Input\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n// Lights\n#ifdef LIGHT0\nuniform vec4 vLightData0;\nuniform vec4 vLightDiffuse0;\nuniform vec3 vLightSpecular0;\n#ifdef SHADOW0\nvarying vec4 vPositionFromLight0;\nuniform sampler2D shadowSampler0;\n#endif\n#ifdef SPOTLIGHT0\nuniform vec4 vLightDirection0;\n#endif\n#ifdef HEMILIGHT0\nuniform vec3 vLightGround0;\n#endif\n#endif\n\n#ifdef LIGHT1\nuniform vec4 vLightData1;\nuniform vec4 vLightDiffuse1;\nuniform vec3 vLightSpecular1;\n#ifdef SHADOW1\nvarying vec4 vPositionFromLight1;\nuniform sampler2D shadowSampler1;\n#endif\n#ifdef SPOTLIGHT1\nuniform vec4 vLightDirection1;\n#endif\n#ifdef HEMILIGHT1\nuniform vec3 vLightGround1;\n#endif\n#endif\n\n#ifdef LIGHT2\nuniform vec4 vLightData2;\nuniform vec4 vLightDiffuse2;\nuniform vec3 vLightSpecular2;\n#ifdef SHADOW2\nvarying vec4 vPositionFromLight2;\nuniform sampler2D shadowSampler2;\n#endif\n#ifdef SPOTLIGHT2\nuniform vec4 vLightDirection2;\n#endif\n#ifdef HEMILIGHT2\nuniform vec3 vLightGround2;\n#endif\n#endif\n\n#ifdef LIGHT3\nuniform vec4 vLightData3;\nuniform vec4 vLightDiffuse3;\nuniform vec3 vLightSpecular3;\n#ifdef SHADOW3\nvarying vec4 vPositionFromLight3;\nuniform sampler2D shadowSampler3;\n#endif\n#ifdef SPOTLIGHT3\nuniform vec4 vLightDirection3;\n#endif\n#ifdef HEMILIGHT3\nuniform vec3 vLightGround3;\n#endif\n#endif\n\n// Samplers\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\nuniform vec2 vDiffuseInfos;\n#endif\n\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec2 vAmbientInfos;\n#endif\n\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n\n#ifdef REFLECTION\nvarying vec3 vReflectionUVW;\nuniform samplerCube reflectionCubeSampler;\nuniform sampler2D reflection2DSampler;\nuniform vec3 vReflectionInfos;\n#endif\n\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n\n#ifdef SPECULAR\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform sampler2D specularSampler;\n#endif\n\n// Fresnel\n#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection, vec3 worldNormal, float bias, float power)\n{\n float fresnelTerm = pow(bias + abs(dot(viewDirection, worldNormal)), power);\n return clamp(fresnelTerm, 0., 1.);\n}\n#endif\n\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n// Shadows\n#ifdef SHADOWS\n\nfloat unpack(vec4 color)\n{\n const vec4 bitShift = vec4(1. / (255. * 255. * 255.), 1. / (255. * 255.), 1. / 255., 1.);\n return dot(color, bitShift);\n}\n\nfloat unpackHalf(vec2 color)\n{\n return color.x + (color.y / 255.0);\n}\n\nfloat computeShadow(vec4 vPositionFromLight, sampler2D shadowSampler)\n{\n vec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\n vec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\n\n if (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n {\n return 1.0;\n }\n\n float shadow = unpack(texture2D(shadowSampler, uv));\n\n if (depth.z > shadow)\n {\n return 0.;\n }\n return 1.;\n}\n\n// Thanks to http://devmaster.net/\nfloat ChebychevInequality(vec2 moments, float t)\n{\n if (t <= moments.x)\n {\n return 1.0;\n }\n\n float variance = moments.y - (moments.x * moments.x);\n variance = max(variance, 0.);\n\n float d = t - moments.x;\n return variance / (variance + d * d);\n}\n\nfloat computeShadowWithVSM(vec4 vPositionFromLight, sampler2D shadowSampler)\n{\n vec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\n vec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\n\n if (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n {\n return 1.0;\n }\n\n vec4 texel = texture2D(shadowSampler, uv);\n\n vec2 moments = vec2(unpackHalf(texel.xy), unpackHalf(texel.zw));\n return clamp(1.3 - ChebychevInequality(moments, depth.z), 0., 1.0);\n}\n#endif\n\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\n\n// Fog\n#ifdef FOG\n\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\n\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying float fFogDistance;\n\nfloat CalcFogFactor()\n{\n float fogCoeff = 1.0;\n float fogStart = vFogInfos.y;\n float fogEnd = vFogInfos.z;\n float fogDensity = vFogInfos.w;\n\n if (FOGMODE_LINEAR == vFogInfos.x)\n {\n fogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\n }\n else if (FOGMODE_EXP == vFogInfos.x)\n {\n fogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\n }\n else if (FOGMODE_EXP2 == vFogInfos.x)\n {\n fogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\n }\n\n return clamp(fogCoeff, 0.0, 1.0);\n}\n#endif\n\n// Light Computing\nmat3 computeLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 diffuseColor, vec3 specularColor) {\n mat3 result;\n\n vec3 lightVectorW;\n if (lightData.w == 0.)\n {\n lightVectorW = normalize(lightData.xyz - vPositionW);\n }\n else\n {\n lightVectorW = normalize(-lightData.xyz);\n }\n\n // diffuse\n float ndl = max(0., dot(vNormal, lightVectorW));\n\n // Specular\n vec3 angleW = normalize(viewDirectionW + lightVectorW);\n float specComp = max(0., dot(vNormal, angleW));\n specComp = max(0., pow(specComp, max(1.0, vSpecularColor.a)));\n\n result[0] = ndl * diffuseColor.rgb;\n result[1] = specComp * specularColor;\n result[2] = vec3(0.);\n\n return result;\n}\n\nmat3 computeSpotLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 lightDirection, vec4 diffuseColor, vec3 specularColor) {\n mat3 result;\n\n vec3 lightVectorW = normalize(lightData.xyz - vPositionW);\n\n // diffuse\n float cosAngle = max(0., dot(-lightDirection.xyz, lightVectorW));\n float spotAtten = 0.0;\n\n if (cosAngle >= lightDirection.w)\n {\n cosAngle = max(0., pow(cosAngle, lightData.w));\n spotAtten = max(0., (cosAngle - lightDirection.w) / (1. - cosAngle));\n\n // Diffuse\n float ndl = max(0., dot(vNormal, -lightDirection.xyz));\n\n // Specular\n vec3 angleW = normalize(viewDirectionW - lightDirection.xyz);\n float specComp = max(0., dot(vNormal, angleW));\n specComp = pow(specComp, vSpecularColor.a);\n\n result[0] = ndl * spotAtten * diffuseColor.rgb;\n result[1] = specComp * specularColor * spotAtten;\n result[2] = vec3(0.);\n\n return result;\n }\n\n result[0] = vec3(0.);\n result[1] = vec3(0.);\n result[2] = vec3(0.);\n\n return result;\n}\n\nmat3 computeHemisphericLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 diffuseColor, vec3 specularColor, vec3 groundColor) {\n mat3 result;\n\n // Diffuse\n float ndl = dot(vNormal, lightData.xyz) * 0.5 + 0.5;\n\n // Specular\n vec3 angleW = normalize(viewDirectionW + lightData.xyz);\n float specComp = max(0., dot(vNormal, angleW));\n specComp = pow(specComp, vSpecularColor.a);\n\n result[0] = mix(groundColor, diffuseColor.rgb, ndl);\n result[1] = specComp * specularColor;\n result[2] = vec3(0.);\n\n return result;\n}\n\nvoid main(void) {\n // Clip plane\n#ifdef CLIPPLANE\n if (fClipDistance > 0.0)\n discard;\n#endif\n\n vec3 viewDirectionW = normalize(vEyePosition - vPositionW);\n\n // Base color\n vec4 baseColor = vec4(1., 1., 1., 1.);\n vec3 diffuseColor = vDiffuseColor.rgb;\n\n#ifdef VERTEXCOLOR\n baseColor.rgb *= vColor.rgb;\n#endif\n\n#ifdef DIFFUSE\n baseColor = texture2D(diffuseSampler, vDiffuseUV);\n\n#ifdef ALPHATEST\n if (baseColor.a < 0.4)\n discard;\n#endif\n\n baseColor.rgb *= vDiffuseInfos.y;\n#endif\n\n // Bump\n vec3 normalW = normalize(vNormalW);\n\n // Ambient color\n vec3 baseAmbientColor = vec3(1., 1., 1.);\n\n#ifdef AMBIENT\n baseAmbientColor = texture2D(ambientSampler, vAmbientUV).rgb * vAmbientInfos.y;\n#endif\n\n // Lighting\n vec3 diffuseBase = vec3(0., 0., 0.);\n vec3 specularBase = vec3(0., 0., 0.);\n float shadow = 1.;\n\n#ifdef LIGHT0\n#ifdef SPOTLIGHT0\n mat3 info = computeSpotLighting(viewDirectionW, normalW, vLightData0, vLightDirection0, vLightDiffuse0, vLightSpecular0);\n#endif\n#ifdef HEMILIGHT0\n mat3 info = computeHemisphericLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0, vLightSpecular0, vLightGround0);\n#endif\n#ifdef POINTDIRLIGHT0\n mat3 info = computeLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0, vLightSpecular0);\n#endif\n#ifdef SHADOW0\n#ifdef SHADOWVSM0\n shadow = computeShadowWithVSM(vPositionFromLight0, shadowSampler0);\n#else\n shadow = computeShadow(vPositionFromLight0, shadowSampler0);\n#endif\n#else\n shadow = 1.;\n#endif\n diffuseBase += info[0] * shadow;\n specularBase += info[1] * shadow;\n#endif\n\n#ifdef LIGHT1\n#ifdef SPOTLIGHT1\n info = computeSpotLighting(viewDirectionW, normalW, vLightData1, vLightDirection1, vLightDiffuse1, vLightSpecular1);\n#endif\n#ifdef HEMILIGHT1\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1, vLightSpecular1, vLightGround1);\n#endif\n#ifdef POINTDIRLIGHT1\n info = computeLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1, vLightSpecular1);\n#endif\n#ifdef SHADOW1\n#ifdef SHADOWVSM1\n shadow = computeShadowWithVSM(vPositionFromLight1, shadowSampler1);\n#else\n shadow = computeShadow(vPositionFromLight1, shadowSampler1);\n#endif\n#else\n shadow = 1.;\n#endif\n diffuseBase += info[0] * shadow;\n specularBase += info[1] * shadow;\n#endif\n\n#ifdef LIGHT2\n#ifdef SPOTLIGHT2\n info = computeSpotLighting(viewDirectionW, normalW, vLightData2, vLightDirection2, vLightDiffuse2, vLightSpecular2);\n#endif\n#ifdef HEMILIGHT2\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2, vLightSpecular2, vLightGround2);\n#endif\n#ifdef POINTDIRLIGHT2\n info = computeLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2, vLightSpecular2);\n#endif\n#ifdef SHADOW2\n#ifdef SHADOWVSM2\n shadow = computeShadowWithVSM(vPositionFromLight2, shadowSampler2);\n#else\n shadow = computeShadow(vPositionFromLight2, shadowSampler2);\n#endif \n#else\n shadow = 1.;\n#endif\n diffuseBase += info[0] * shadow;\n specularBase += info[1] * shadow;\n#endif\n\n#ifdef LIGHT3\n#ifdef SPOTLIGHT3\n info = computeSpotLighting(viewDirectionW, normalW, vLightData3, vLightDirection3, vLightDiffuse3, vLightSpecular3);\n#endif\n#ifdef HEMILIGHT3\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3, vLightSpecular3, vLightGround3);\n#endif\n#ifdef POINTDIRLIGHT3\n info = computeLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3, vLightSpecular3);\n#endif\n#ifdef SHADOW3\n#ifdef SHADOWVSM3\n shadow = computeShadowWithVSM(vPositionFromLight3, shadowSampler3);\n#else\n shadow = computeShadow(vPositionFromLight3, shadowSampler3);\n#endif \n#else\n shadow = 1.;\n#endif\n diffuseBase += info[0] * shadow;\n specularBase += info[1] * shadow;\n#endif\n\n // Reflection\n vec3 reflectionColor = vec3(0., 0., 0.);\n\n#ifdef REFLECTION\n if (vReflectionInfos.z != 0.0)\n {\n reflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW).rgb * vReflectionInfos.y;\n }\n else\n {\n vec2 coords = vReflectionUVW.xy;\n\n if (vReflectionInfos.x == MAP_PROJECTION)\n {\n coords /= vReflectionUVW.z;\n }\n\n coords.y = 1.0 - coords.y;\n\n reflectionColor = texture2D(reflection2DSampler, coords).rgb * vReflectionInfos.y;\n }\n\n#ifdef REFLECTIONFRESNEL\n float reflectionFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, reflectionRightColor.a, reflectionLeftColor.a);\n\n reflectionColor *= reflectionLeftColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\n#endif\n#endif\n\n // Alpha\n float alpha = vDiffuseColor.a;\n\n#ifdef OPACITY\n vec4 opacityMap = texture2D(opacitySampler, vOpacityUV);\n#ifdef OPACITYRGB\n opacityMap.rgb = opacityMap.rgb * vec3(0.3, 0.59, 0.11);\n alpha *= (opacityMap.x + opacityMap.y + opacityMap.z)* vOpacityInfos.y;\n#else\n alpha *= opacityMap.a * vOpacityInfos.y;\n#endif\n#endif\n\n#ifdef VERTEXALPHA\n alpha *= vColor.a;\n#endif\n\n#ifdef OPACITYFRESNEL\n float opacityFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, opacityParts.z, opacityParts.w);\n\n alpha += opacityParts.x * (1.0 - opacityFresnelTerm) + opacityFresnelTerm * opacityParts.y;\n#endif\n\n // Emissive\n vec3 emissiveColor = vEmissiveColor;\n#ifdef EMISSIVE\n emissiveColor += texture2D(emissiveSampler, vEmissiveUV).rgb * vEmissiveInfos.y;\n#endif\n\n#ifdef EMISSIVEFRESNEL\n float emissiveFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, emissiveRightColor.a, emissiveLeftColor.a);\n\n emissiveColor *= emissiveLeftColor.rgb * (1.0 - emissiveFresnelTerm) + emissiveFresnelTerm * emissiveRightColor.rgb;\n#endif\n\n // Specular map\n vec3 specularColor = vSpecularColor.rgb;\n#ifdef SPECULAR\n specularColor = texture2D(specularSampler, vSpecularUV).rgb * vSpecularInfos.y;\n#endif\n\n // Fresnel\n#ifdef DIFFUSEFRESNEL\n float diffuseFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, diffuseRightColor.a, diffuseLeftColor.a);\n\n diffuseBase *= diffuseLeftColor.rgb * (1.0 - diffuseFresnelTerm) + diffuseFresnelTerm * diffuseRightColor.rgb;\n#endif\n\n // Composition\n vec3 finalDiffuse = clamp(diffuseBase * diffuseColor + emissiveColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\n vec3 finalSpecular = specularBase * specularColor;\n\n vec4 color = vec4(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor, alpha);\n\n#ifdef FOG\n float fog = CalcFogFactor();\n color.rgb = fog * color.rgb + (1.0 - fog) * vFogColor;\n#endif\n\n gl_FragColor = color;\n}",
  11396. legacydefaultVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n#define MAP_EXPLICIT 0.\n#define MAP_SPHERICAL 1.\n#define MAP_PLANAR 2.\n#define MAP_CUBIC 3.\n#define MAP_PROJECTION 4.\n#define MAP_SKYBOX 5.\n\n// Attributes\nattribute vec3 position;\nattribute vec3 normal;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#ifdef BONES\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#endif\n\n// Uniforms\nuniform mat4 world;\nuniform mat4 view;\nuniform mat4 viewProjection;\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec3 vEyePosition;\nvarying vec3 vReflectionUVW;\nuniform vec3 vReflectionInfos;\nuniform mat4 reflectionMatrix;\n#endif\n\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n\n#ifdef SPECULAR\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec2 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n\n#ifdef BONES\nuniform mat4 mBones[BonesPerMesh];\n#endif\n\n// Output\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif\n\n#ifdef FOG\nvarying float fFogDistance;\n#endif\n\n#ifdef SHADOWS\n#ifdef LIGHT0\nuniform mat4 lightMatrix0;\nvarying vec4 vPositionFromLight0;\n#endif\n#ifdef LIGHT1\nuniform mat4 lightMatrix1;\nvarying vec4 vPositionFromLight1;\n#endif\n#ifdef LIGHT2\nuniform mat4 lightMatrix2;\nvarying vec4 vPositionFromLight2;\n#endif\n#ifdef LIGHT3\nuniform mat4 lightMatrix3;\nvarying vec4 vPositionFromLight3;\n#endif\n#endif\n\n#ifdef REFLECTION\nvec3 computeReflectionCoords(float mode, vec4 worldPos, vec3 worldNormal)\n{\n if (mode == MAP_SPHERICAL)\n {\n vec3 coords = vec3(view * vec4(worldNormal, 0.0));\n\n return vec3(reflectionMatrix * vec4(coords, 1.0));\n }\n else if (mode == MAP_PLANAR)\n {\n vec3 viewDir = worldPos.xyz - vEyePosition;\n vec3 coords = normalize(reflect(viewDir, worldNormal));\n\n return vec3(reflectionMatrix * vec4(coords, 1));\n }\n else if (mode == MAP_CUBIC)\n {\n vec3 viewDir = worldPos.xyz - vEyePosition;\n vec3 coords = reflect(viewDir, worldNormal);\n\n return vec3(reflectionMatrix * vec4(coords, 0));\n }\n else if (mode == MAP_PROJECTION)\n {\n return vec3(reflectionMatrix * (view * worldPos));\n }\n else if (mode == MAP_SKYBOX)\n {\n return position;\n }\n\n return vec3(0, 0, 0);\n}\n#endif\n\nvoid main(void) {\n mat4 finalWorld;\n\n#ifdef BONES\n mat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\n mat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\n mat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\n\n#ifdef BONES4\n mat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\n finalWorld = world * (m0 + m1 + m2 + m3);\n#else\n finalWorld = world * (m0 + m1 + m2);\n#endif \n\n#else\n finalWorld = world;\n#endif\n\n gl_Position = viewProjection * finalWorld * vec4(position, 1.0);\n\n vec4 worldPos = finalWorld * vec4(position, 1.0);\n vPositionW = vec3(worldPos);\n vNormalW = normalize(vec3(finalWorld * vec4(normal, 0.0)));\n\n // Texture coordinates\n#ifndef UV1\n vec2 uv = vec2(0., 0.);\n#endif\n#ifndef UV2\n vec2 uv2 = vec2(0., 0.);\n#endif\n\n#ifdef DIFFUSE\n if (vDiffuseInfos.x == 0.)\n {\n vDiffuseUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vDiffuseUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef AMBIENT\n if (vAmbientInfos.x == 0.)\n {\n vAmbientUV = vec2(ambientMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vAmbientUV = vec2(ambientMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef OPACITY\n if (vOpacityInfos.x == 0.)\n {\n vOpacityUV = vec2(opacityMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vOpacityUV = vec2(opacityMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef REFLECTION\n vReflectionUVW = computeReflectionCoords(vReflectionInfos.x, vec4(vPositionW, 1.0), vNormalW);\n#endif\n\n#ifdef EMISSIVE\n if (vEmissiveInfos.x == 0.)\n {\n vEmissiveUV = vec2(emissiveMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vEmissiveUV = vec2(emissiveMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef SPECULAR\n if (vSpecularInfos.x == 0.)\n {\n vSpecularUV = vec2(specularMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vSpecularUV = vec2(specularMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef BUMP\n if (vBumpInfos.x == 0.)\n {\n vBumpUV = vec2(bumpMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vBumpUV = vec2(bumpMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n // Clip plane\n#ifdef CLIPPLANE\n fClipDistance = dot(worldPos, vClipPlane);\n#endif\n\n // Fog\n#ifdef FOG\n fFogDistance = (view * worldPos).z;\n#endif\n\n // Shadows\n#ifdef SHADOWS\n#ifdef LIGHT0\n vPositionFromLight0 = lightMatrix0 * worldPos;\n#endif\n#ifdef LIGHT1\n vPositionFromLight1 = lightMatrix1 * worldPos;\n#endif\n#ifdef LIGHT2\n vPositionFromLight2 = lightMatrix2 * worldPos;\n#endif\n#ifdef LIGHT3\n vPositionFromLight3 = lightMatrix3 * worldPos;\n#endif\n#endif\n\n // Vertex color\n#ifdef VERTEXCOLOR\n vColor = color;\n#endif\n}",
  11397. 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}",
  11398. 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}",
  11399. marblePixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\n\n\nuniform float numberOfBricksHeight;\nuniform float numberOfBricksWidth ;\n\nconst vec3 tileSize = vec3(1.1, 1.0, 1.1);\nconst vec3 tilePct = vec3(0.98, 1.0, 0.98);\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 turbulence(vec2 P)\n{\n float val = 0.0;\n float freq = 1.0;\n for (int i = 0; i < 4; i++)\n {\n val += abs(noise(P*freq) / freq);\n freq *= 2.07;\n }\n return val;\n}\n\nfloat round(float number){\n return sign(number)*floor(abs(number) + 0.5);\n}\n\n\nvec3 marble_color(float x)\n{\n vec3 col;\n x = 0.5*(x + 1.);\n x = sqrt(x); \n x = sqrt(x);\n x = sqrt(x);\n col = vec3(.2 + .75*x); \n col.b *= 0.95; \n return col;\n}\nvoid main()\n{\n\n vec3 brick = vec3(0.77, 0.47, 0.40);\n vec3 joint = vec3(0.72, 0.72, 0.72);\n\n float brickW = 1.0 / numberOfBricksWidth;\n float brickH = 1.0 / numberOfBricksHeight;\n float jointWPercentage = 0.01;\n float jointHPercentage = 0.01;\n\n vec3 color = brick;\n\n\n float yi = vUV.y / brickH;\n float nyi = round(yi);\n\n float xi = vUV.x / brickW;\n\n if (mod(floor(yi), 2.0) == 0.0){\n xi = xi - 0.5;\n }\n\n float nxi = round(xi);\n\n vec2 brickvUV = vec2((xi - floor(xi)) / brickH, (yi - floor(yi)) / brickW);\n\n\n if (yi < nyi + jointHPercentage && yi > nyi - jointHPercentage){\n color = mix(joint, vec3(0.37, 0.25, 0.25), (yi - nyi) / jointHPercentage + 0.2);\n }\n else if (xi < nxi + jointWPercentage && xi > nxi - jointWPercentage){\n color = mix(joint, vec3(0.44, 0.44, 0.44), (xi - nxi) / jointWPercentage + 0.2);\n }\n else {\n\n float amplitude = 9.0;\n\n float t = 6.28 * brickvUV.x / (tileSize.x + noise(vec2(vUV)*6.0));\n t += amplitude * turbulence(brickvUV.xy);\n\n t = sin(t);\n color = marble_color(t);\n\n\n }\n\n gl_FragColor = vec4(color, 0.0);\n\n \n}",
  11400. 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}",
  11401. 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}",
  11402. 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}",
  11403. 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}",
  11404. 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}",
  11405. 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}",
  11406. 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}",
  11407. 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}",
  11408. 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}",
  11409. roadPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\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(void) {\n\n\n vec3 gray = vec3(0.53, 0.53, 0.53);\n\n float ratioy = mod(gl_FragCoord.y * 100.0 , fbm(vUV * 2.0));\n \n gray = gray * ratioy;\n\n gl_FragColor = vec4(gray, 1.0);\n}",
  11410. rockPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\n\nvec3 hash(vec3 x)\n{\n x = vec3(dot(x, vec3(127.1, 311.7, 74.7)),\n dot(x, vec3(269.5, 183.3, 246.1)),\n dot(x, vec3(113.5, 271.9, 124.6)));\n\n return fract(sin(x)*43758.5453123);\n}\n\n// returns closest, second closest, and cell id\nvec3 voronoi(in vec3 x)\n{\n vec3 p = floor(x);\n vec3 f = fract(x);\n\n float id = 0.0;\n vec2 res = vec2(100.0);\n for (int k = -1; k <= 1; k++)\n for (int j = -1; j <= 1; j++)\n for (int i = -1; i <= 1; i++)\n {\n vec3 b = vec3(float(i), float(j), float(k));\n vec3 r = vec3(b) - f + hash(p + b);\n float d = dot(r, r);\n\n if (d < res.x)\n {\n id = dot(p + b, vec3(1.0, 57.0, 113.0));\n res = vec2(d, res.x);\n }\n else if (d < res.y)\n {\n res.y = d;\n }\n }\n\n return vec3(sqrt(res), abs(id));\n}\n\nconst mat3 m = mat3(0.00, 0.80, 0.60,\n -0.80, 0.36, -0.48,\n -0.60, -0.48, 0.64);\n\nvoid main(void)\n{\n vec2 p = vUV;\n\n // camera movement \n float an = 0.5*0.1;\n vec3 ro = vec3(2.5*cos(an), 1.0, 2.5*sin(an));\n vec3 ta = vec3(0.0, 1.0, 0.0);\n // camera matrix\n vec3 ww = normalize(ta - ro);\n vec3 uu = normalize(cross(ww, vec3(0.0, 1.0, 0.0)));\n vec3 vv = normalize(cross(uu, ww));\n // create view ray\n vec3 rd = normalize(p.x*uu + p.y*vv + 1.5*ww);\n\n // sphere center \n vec3 sc = vec3(0.0, 1.0, 0.0);\n\n // raytrace\n float tmin = 10000.0;\n vec3 nor = vec3(0.0);\n float occ = 1.0;\n vec3 pos = vec3(0.0);\n\n // raytrace-plane\n float h = (0.0 - ro.y) / rd.y;\n if (h>0.0)\n {\n tmin = h;\n nor = vec3(0.0, 1.0, 0.0);\n pos = ro + h*rd;\n vec3 di = sc - pos;\n float l = length(di);\n occ = 1.0 - dot(nor, di / l)*1.0*1.0 / (l*l);\n }\n\n // raytrace-sphere\n vec3 ce = ro - sc;\n float b = dot(rd, ce);\n float c = dot(ce, ce) - 1.0;\n h = b*b - c;\n if (h>0.0)\n {\n h = -b - sqrt(h);\n if (h<tmin)\n {\n tmin = h;\n nor = normalize(ro + h*rd - sc);\n occ = 0.5 + 0.5*nor.y;\n }\n }\n\n // shading/lighting \n vec3 col = vec3(0.9);\n if (tmin<100.0)\n {\n pos = ro + tmin*rd;\n\n float f = voronoi(4.0*pos).x;\n\n f *= occ;\n col = vec3(f*1.2);\n col = mix(col, vec3(0.9), 1.0 - exp(-0.003*tmin*tmin));\n }\n\n col = sqrt(col);\n\n\n gl_FragColor = vec4(col, 1.0);\n}",
  11411. 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}",
  11412. 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}",
  11413. 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}",
  11414. 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}",
  11415. woodPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\n\nuniform float ampScale;\nuniform vec3 woodColor;\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 float ratioy = mod(vUV.x * ampScale, 2.0 + fbm(vUV * 0.8));\n vec3 wood = woodColor * ratioy;\n\n gl_FragColor = vec4(wood, 1.0);\n}",
  11416. };
  11417. return Effect;
  11418. })();
  11419. BABYLON.Effect = Effect;
  11420. })(BABYLON || (BABYLON = {}));
  11421. var BABYLON;
  11422. (function (BABYLON) {
  11423. var Material = (function () {
  11424. function Material(name, scene, doNotAdd) {
  11425. this.name = name;
  11426. this.checkReadyOnEveryCall = true;
  11427. this.checkReadyOnlyOnce = false;
  11428. this.state = "";
  11429. this.alpha = 1.0;
  11430. this.backFaceCulling = true;
  11431. this._wasPreviouslyReady = false;
  11432. this._fillMode = Material.TriangleFillMode;
  11433. this.pointSize = 1.0;
  11434. this.id = name;
  11435. this._scene = scene;
  11436. if (!doNotAdd) {
  11437. scene.materials.push(this);
  11438. }
  11439. }
  11440. Object.defineProperty(Material, "TriangleFillMode", {
  11441. get: function () {
  11442. return Material._TriangleFillMode;
  11443. },
  11444. enumerable: true,
  11445. configurable: true
  11446. });
  11447. Object.defineProperty(Material, "WireFrameFillMode", {
  11448. get: function () {
  11449. return Material._WireFrameFillMode;
  11450. },
  11451. enumerable: true,
  11452. configurable: true
  11453. });
  11454. Object.defineProperty(Material, "PointFillMode", {
  11455. get: function () {
  11456. return Material._PointFillMode;
  11457. },
  11458. enumerable: true,
  11459. configurable: true
  11460. });
  11461. Object.defineProperty(Material.prototype, "wireframe", {
  11462. get: function () {
  11463. return this._fillMode === Material.WireFrameFillMode;
  11464. },
  11465. set: function (value) {
  11466. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  11467. },
  11468. enumerable: true,
  11469. configurable: true
  11470. });
  11471. Object.defineProperty(Material.prototype, "pointsCloud", {
  11472. get: function () {
  11473. return this._fillMode === Material.PointFillMode;
  11474. },
  11475. set: function (value) {
  11476. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  11477. },
  11478. enumerable: true,
  11479. configurable: true
  11480. });
  11481. Object.defineProperty(Material.prototype, "fillMode", {
  11482. get: function () {
  11483. return this._fillMode;
  11484. },
  11485. set: function (value) {
  11486. this._fillMode = value;
  11487. },
  11488. enumerable: true,
  11489. configurable: true
  11490. });
  11491. Material.prototype.isReady = function (mesh, useInstances) {
  11492. return true;
  11493. };
  11494. Material.prototype.getEffect = function () {
  11495. return this._effect;
  11496. };
  11497. Material.prototype.getScene = function () {
  11498. return this._scene;
  11499. };
  11500. Material.prototype.needAlphaBlending = function () {
  11501. return (this.alpha < 1.0);
  11502. };
  11503. Material.prototype.needAlphaTesting = function () {
  11504. return false;
  11505. };
  11506. Material.prototype.getAlphaTestTexture = function () {
  11507. return null;
  11508. };
  11509. Material.prototype.trackCreation = function (onCompiled, onError) {
  11510. };
  11511. Material.prototype._preBind = function () {
  11512. var engine = this._scene.getEngine();
  11513. engine.enableEffect(this._effect);
  11514. engine.setState(this.backFaceCulling);
  11515. };
  11516. Material.prototype.bind = function (world, mesh) {
  11517. };
  11518. Material.prototype.bindOnlyWorldMatrix = function (world) {
  11519. };
  11520. Material.prototype.unbind = function () {
  11521. };
  11522. Material.prototype.dispose = function (forceDisposeEffect) {
  11523. var index = this._scene.materials.indexOf(this);
  11524. this._scene.materials.splice(index, 1);
  11525. if (forceDisposeEffect && this._effect) {
  11526. this._scene.getEngine()._releaseEffect(this._effect);
  11527. this._effect = null;
  11528. }
  11529. if (this.onDispose) {
  11530. this.onDispose();
  11531. }
  11532. };
  11533. Material._TriangleFillMode = 0;
  11534. Material._WireFrameFillMode = 1;
  11535. Material._PointFillMode = 2;
  11536. return Material;
  11537. })();
  11538. BABYLON.Material = Material;
  11539. })(BABYLON || (BABYLON = {}));
  11540. var __extends = this.__extends || function (d, b) {
  11541. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  11542. function __() { this.constructor = d; }
  11543. __.prototype = b.prototype;
  11544. d.prototype = new __();
  11545. };
  11546. var BABYLON;
  11547. (function (BABYLON) {
  11548. var maxSimultaneousLights = 4;
  11549. var FresnelParameters = (function () {
  11550. function FresnelParameters() {
  11551. this.isEnabled = true;
  11552. this.leftColor = BABYLON.Color3.White();
  11553. this.rightColor = BABYLON.Color3.Black();
  11554. this.bias = 0;
  11555. this.power = 1;
  11556. }
  11557. return FresnelParameters;
  11558. })();
  11559. BABYLON.FresnelParameters = FresnelParameters;
  11560. var StandardMaterial = (function (_super) {
  11561. __extends(StandardMaterial, _super);
  11562. function StandardMaterial(name, scene) {
  11563. var _this = this;
  11564. _super.call(this, name, scene);
  11565. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  11566. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  11567. this.specularColor = new BABYLON.Color3(1, 1, 1);
  11568. this.specularPower = 64;
  11569. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  11570. this.useAlphaFromDiffuseTexture = false;
  11571. this.useSpecularOverAlpha = true;
  11572. this.fogEnabled = true;
  11573. this._cachedDefines = null;
  11574. this._renderTargets = new BABYLON.SmartArray(16);
  11575. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  11576. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  11577. this._scaledDiffuse = new BABYLON.Color3();
  11578. this._scaledSpecular = new BABYLON.Color3();
  11579. this.getRenderTargetTextures = function () {
  11580. _this._renderTargets.reset();
  11581. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  11582. _this._renderTargets.push(_this.reflectionTexture);
  11583. }
  11584. return _this._renderTargets;
  11585. };
  11586. }
  11587. StandardMaterial.prototype.needAlphaBlending = function () {
  11588. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  11589. };
  11590. StandardMaterial.prototype.needAlphaTesting = function () {
  11591. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && !this.diffuseTexture.getAlphaFromRGB;
  11592. };
  11593. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  11594. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  11595. };
  11596. StandardMaterial.prototype.getAlphaTestTexture = function () {
  11597. return this.diffuseTexture;
  11598. };
  11599. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  11600. if (this.checkReadyOnlyOnce) {
  11601. if (this._wasPreviouslyReady) {
  11602. return true;
  11603. }
  11604. }
  11605. var scene = this.getScene();
  11606. if (!this.checkReadyOnEveryCall) {
  11607. if (this._renderId === scene.getRenderId()) {
  11608. return true;
  11609. }
  11610. }
  11611. var engine = scene.getEngine();
  11612. var defines = [];
  11613. var fallbacks = new BABYLON.EffectFallbacks();
  11614. if (scene.texturesEnabled) {
  11615. if (this.diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  11616. if (!this.diffuseTexture.isReady()) {
  11617. return false;
  11618. } else {
  11619. defines.push("#define DIFFUSE");
  11620. }
  11621. }
  11622. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  11623. if (!this.ambientTexture.isReady()) {
  11624. return false;
  11625. } else {
  11626. defines.push("#define AMBIENT");
  11627. }
  11628. }
  11629. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  11630. if (!this.opacityTexture.isReady()) {
  11631. return false;
  11632. } else {
  11633. defines.push("#define OPACITY");
  11634. if (this.opacityTexture.getAlphaFromRGB) {
  11635. defines.push("#define OPACITYRGB");
  11636. }
  11637. }
  11638. }
  11639. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  11640. if (!this.reflectionTexture.isReady()) {
  11641. return false;
  11642. } else {
  11643. defines.push("#define REFLECTION");
  11644. fallbacks.addFallback(0, "REFLECTION");
  11645. }
  11646. }
  11647. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  11648. if (!this.emissiveTexture.isReady()) {
  11649. return false;
  11650. } else {
  11651. defines.push("#define EMISSIVE");
  11652. }
  11653. }
  11654. if (this.specularTexture && BABYLON.StandardMaterial.SpecularTextureEnabled) {
  11655. if (!this.specularTexture.isReady()) {
  11656. return false;
  11657. } else {
  11658. defines.push("#define SPECULAR");
  11659. fallbacks.addFallback(0, "SPECULAR");
  11660. }
  11661. }
  11662. }
  11663. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled) {
  11664. if (!this.bumpTexture.isReady()) {
  11665. return false;
  11666. } else {
  11667. defines.push("#define BUMP");
  11668. fallbacks.addFallback(0, "BUMP");
  11669. }
  11670. }
  11671. if (this.useSpecularOverAlpha) {
  11672. defines.push("#define SPECULAROVERALPHA");
  11673. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  11674. }
  11675. if (scene.clipPlane) {
  11676. defines.push("#define CLIPPLANE");
  11677. }
  11678. if (engine.getAlphaTesting()) {
  11679. defines.push("#define ALPHATEST");
  11680. }
  11681. if (this._shouldUseAlphaFromDiffuseTexture()) {
  11682. defines.push("#define ALPHAFROMDIFFUSE");
  11683. }
  11684. if (this.pointsCloud) {
  11685. defines.push("#define POINTSIZE");
  11686. }
  11687. if (scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  11688. defines.push("#define FOG");
  11689. fallbacks.addFallback(1, "FOG");
  11690. }
  11691. var shadowsActivated = false;
  11692. var lightIndex = 0;
  11693. if (scene.lightsEnabled) {
  11694. for (var index = 0; index < scene.lights.length; index++) {
  11695. var light = scene.lights[index];
  11696. if (!light.isEnabled()) {
  11697. continue;
  11698. }
  11699. if (light._excludedMeshesIds.length > 0) {
  11700. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  11701. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  11702. if (excludedMesh) {
  11703. light.excludedMeshes.push(excludedMesh);
  11704. }
  11705. }
  11706. light._excludedMeshesIds = [];
  11707. }
  11708. if (light._includedOnlyMeshesIds.length > 0) {
  11709. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  11710. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  11711. if (includedOnlyMesh) {
  11712. light.includedOnlyMeshes.push(includedOnlyMesh);
  11713. }
  11714. }
  11715. light._includedOnlyMeshesIds = [];
  11716. }
  11717. if (!light.canAffectMesh(mesh)) {
  11718. continue;
  11719. }
  11720. defines.push("#define LIGHT" + lightIndex);
  11721. if (lightIndex > 0) {
  11722. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  11723. }
  11724. var type;
  11725. if (light instanceof BABYLON.SpotLight) {
  11726. type = "#define SPOTLIGHT" + lightIndex;
  11727. } else if (light instanceof BABYLON.HemisphericLight) {
  11728. type = "#define HEMILIGHT" + lightIndex;
  11729. } else {
  11730. type = "#define POINTDIRLIGHT" + lightIndex;
  11731. }
  11732. defines.push(type);
  11733. if (lightIndex > 0) {
  11734. fallbacks.addFallback(lightIndex, type.replace("#define ", ""));
  11735. }
  11736. if (scene.shadowsEnabled) {
  11737. var shadowGenerator = light.getShadowGenerator();
  11738. if (mesh && mesh.receiveShadows && shadowGenerator) {
  11739. defines.push("#define SHADOW" + lightIndex);
  11740. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  11741. if (!shadowsActivated) {
  11742. defines.push("#define SHADOWS");
  11743. shadowsActivated = true;
  11744. }
  11745. if (shadowGenerator.useVarianceShadowMap) {
  11746. defines.push("#define SHADOWVSM" + lightIndex);
  11747. if (lightIndex > 0) {
  11748. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  11749. }
  11750. }
  11751. if (shadowGenerator.usePoissonSampling) {
  11752. defines.push("#define SHADOWPCF" + lightIndex);
  11753. if (lightIndex > 0) {
  11754. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  11755. }
  11756. }
  11757. }
  11758. }
  11759. lightIndex++;
  11760. if (lightIndex == maxSimultaneousLights)
  11761. break;
  11762. }
  11763. }
  11764. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled || this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled || this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  11765. var fresnelRank = 1;
  11766. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  11767. defines.push("#define DIFFUSEFRESNEL");
  11768. fallbacks.addFallback(fresnelRank, "DIFFUSEFRESNEL");
  11769. fresnelRank++;
  11770. }
  11771. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  11772. defines.push("#define OPACITYFRESNEL");
  11773. fallbacks.addFallback(fresnelRank, "OPACITYFRESNEL");
  11774. fresnelRank++;
  11775. }
  11776. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  11777. defines.push("#define REFLECTIONFRESNEL");
  11778. fallbacks.addFallback(fresnelRank, "REFLECTIONFRESNEL");
  11779. fresnelRank++;
  11780. }
  11781. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  11782. defines.push("#define EMISSIVEFRESNEL");
  11783. fallbacks.addFallback(fresnelRank, "EMISSIVEFRESNEL");
  11784. fresnelRank++;
  11785. }
  11786. defines.push("#define FRESNEL");
  11787. fallbacks.addFallback(fresnelRank - 1, "FRESNEL");
  11788. }
  11789. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  11790. if (mesh) {
  11791. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  11792. attribs.push(BABYLON.VertexBuffer.UVKind);
  11793. defines.push("#define UV1");
  11794. }
  11795. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  11796. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  11797. defines.push("#define UV2");
  11798. }
  11799. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  11800. attribs.push(BABYLON.VertexBuffer.ColorKind);
  11801. defines.push("#define VERTEXCOLOR");
  11802. if (mesh.hasVertexAlpha) {
  11803. defines.push("#define VERTEXALPHA");
  11804. }
  11805. }
  11806. if (mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  11807. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  11808. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  11809. defines.push("#define BONES");
  11810. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  11811. defines.push("#define BONES4");
  11812. fallbacks.addFallback(0, "BONES4");
  11813. }
  11814. if (useInstances) {
  11815. defines.push("#define INSTANCES");
  11816. attribs.push("world0");
  11817. attribs.push("world1");
  11818. attribs.push("world2");
  11819. attribs.push("world3");
  11820. }
  11821. }
  11822. var join = defines.join("\n");
  11823. if (this._cachedDefines != join) {
  11824. this._cachedDefines = join;
  11825. var shaderName = "default";
  11826. if (!scene.getEngine().getCaps().standardDerivatives) {
  11827. shaderName = "legacydefault";
  11828. }
  11829. this._effect = scene.getEngine().createEffect(shaderName, attribs, [
  11830. "world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  11831. "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0",
  11832. "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1",
  11833. "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2",
  11834. "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3",
  11835. "vFogInfos", "vFogColor", "pointSize",
  11836. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos",
  11837. "mBones",
  11838. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix",
  11839. "darkness0", "darkness1", "darkness2", "darkness3",
  11840. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor"
  11841. ], [
  11842. "diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler",
  11843. "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"
  11844. ], join, fallbacks, this.onCompiled, this.onError);
  11845. }
  11846. if (!this._effect.isReady()) {
  11847. return false;
  11848. }
  11849. this._renderId = scene.getRenderId();
  11850. this._wasPreviouslyReady = true;
  11851. return true;
  11852. };
  11853. StandardMaterial.prototype.unbind = function () {
  11854. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  11855. this._effect.setTexture("reflection2DSampler", null);
  11856. }
  11857. };
  11858. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  11859. this._effect.setMatrix("world", world);
  11860. };
  11861. StandardMaterial.prototype.bind = function (world, mesh) {
  11862. var scene = this.getScene();
  11863. this.bindOnlyWorldMatrix(world);
  11864. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  11865. if (mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  11866. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  11867. }
  11868. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  11869. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  11870. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  11871. }
  11872. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  11873. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  11874. }
  11875. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  11876. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  11877. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  11878. }
  11879. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  11880. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  11881. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  11882. }
  11883. if (this.diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  11884. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  11885. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  11886. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  11887. }
  11888. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  11889. this._effect.setTexture("ambientSampler", this.ambientTexture);
  11890. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  11891. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  11892. }
  11893. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  11894. this._effect.setTexture("opacitySampler", this.opacityTexture);
  11895. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  11896. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  11897. }
  11898. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  11899. if (this.reflectionTexture.isCube) {
  11900. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  11901. } else {
  11902. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  11903. }
  11904. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  11905. this._effect.setFloat3("vReflectionInfos", this.reflectionTexture.coordinatesMode, this.reflectionTexture.level, this.reflectionTexture.isCube ? 1 : 0);
  11906. }
  11907. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  11908. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  11909. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  11910. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  11911. }
  11912. if (this.specularTexture && BABYLON.StandardMaterial.SpecularTextureEnabled) {
  11913. this._effect.setTexture("specularSampler", this.specularTexture);
  11914. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  11915. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  11916. }
  11917. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled) {
  11918. this._effect.setTexture("bumpSampler", this.bumpTexture);
  11919. this._effect.setFloat2("vBumpInfos", this.bumpTexture.coordinatesIndex, this.bumpTexture.level);
  11920. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  11921. }
  11922. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  11923. this._effect.setVector3("vEyePosition", scene.activeCamera.position);
  11924. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  11925. this._effect.setColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  11926. this._effect.setColor4("vSpecularColor", this.specularColor, this.specularPower);
  11927. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  11928. if (scene.lightsEnabled) {
  11929. var lightIndex = 0;
  11930. for (var index = 0; index < scene.lights.length; index++) {
  11931. var light = scene.lights[index];
  11932. if (!light.isEnabled()) {
  11933. continue;
  11934. }
  11935. if (!light.canAffectMesh(mesh)) {
  11936. continue;
  11937. }
  11938. if (light instanceof BABYLON.PointLight) {
  11939. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  11940. } else if (light instanceof BABYLON.DirectionalLight) {
  11941. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  11942. } else if (light instanceof BABYLON.SpotLight) {
  11943. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  11944. } else if (light instanceof BABYLON.HemisphericLight) {
  11945. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  11946. }
  11947. light.diffuse.scaleToRef(light.intensity, this._scaledDiffuse);
  11948. light.specular.scaleToRef(light.intensity, this._scaledSpecular);
  11949. this._effect.setColor4("vLightDiffuse" + lightIndex, this._scaledDiffuse, light.range);
  11950. this._effect.setColor3("vLightSpecular" + lightIndex, this._scaledSpecular);
  11951. if (scene.shadowsEnabled) {
  11952. var shadowGenerator = light.getShadowGenerator();
  11953. if (mesh.receiveShadows && shadowGenerator) {
  11954. this._effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  11955. this._effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMap());
  11956. this._effect.setFloat("darkness" + lightIndex, shadowGenerator.getDarkness());
  11957. }
  11958. }
  11959. lightIndex++;
  11960. if (lightIndex == maxSimultaneousLights)
  11961. break;
  11962. }
  11963. }
  11964. if (scene.clipPlane) {
  11965. var clipPlane = scene.clipPlane;
  11966. this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  11967. }
  11968. if (scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  11969. this._effect.setMatrix("view", scene.getViewMatrix());
  11970. }
  11971. if (scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  11972. this._effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  11973. this._effect.setColor3("vFogColor", scene.fogColor);
  11974. }
  11975. if (this.pointsCloud) {
  11976. this._effect.setFloat("pointSize", this.pointSize);
  11977. }
  11978. };
  11979. StandardMaterial.prototype.getAnimatables = function () {
  11980. var results = [];
  11981. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  11982. results.push(this.diffuseTexture);
  11983. }
  11984. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  11985. results.push(this.ambientTexture);
  11986. }
  11987. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  11988. results.push(this.opacityTexture);
  11989. }
  11990. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  11991. results.push(this.reflectionTexture);
  11992. }
  11993. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  11994. results.push(this.emissiveTexture);
  11995. }
  11996. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  11997. results.push(this.specularTexture);
  11998. }
  11999. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  12000. results.push(this.bumpTexture);
  12001. }
  12002. return results;
  12003. };
  12004. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  12005. if (this.diffuseTexture) {
  12006. this.diffuseTexture.dispose();
  12007. }
  12008. if (this.ambientTexture) {
  12009. this.ambientTexture.dispose();
  12010. }
  12011. if (this.opacityTexture) {
  12012. this.opacityTexture.dispose();
  12013. }
  12014. if (this.reflectionTexture) {
  12015. this.reflectionTexture.dispose();
  12016. }
  12017. if (this.emissiveTexture) {
  12018. this.emissiveTexture.dispose();
  12019. }
  12020. if (this.specularTexture) {
  12021. this.specularTexture.dispose();
  12022. }
  12023. if (this.bumpTexture) {
  12024. this.bumpTexture.dispose();
  12025. }
  12026. _super.prototype.dispose.call(this, forceDisposeEffect);
  12027. };
  12028. StandardMaterial.prototype.clone = function (name) {
  12029. var newStandardMaterial = new BABYLON.StandardMaterial(name, this.getScene());
  12030. newStandardMaterial.checkReadyOnEveryCall = this.checkReadyOnEveryCall;
  12031. newStandardMaterial.alpha = this.alpha;
  12032. newStandardMaterial.fillMode = this.fillMode;
  12033. newStandardMaterial.backFaceCulling = this.backFaceCulling;
  12034. if (this.diffuseTexture && this.diffuseTexture.clone) {
  12035. newStandardMaterial.diffuseTexture = this.diffuseTexture.clone();
  12036. }
  12037. if (this.ambientTexture && this.ambientTexture.clone) {
  12038. newStandardMaterial.ambientTexture = this.ambientTexture.clone();
  12039. }
  12040. if (this.opacityTexture && this.opacityTexture.clone) {
  12041. newStandardMaterial.opacityTexture = this.opacityTexture.clone();
  12042. }
  12043. if (this.reflectionTexture && this.reflectionTexture.clone) {
  12044. newStandardMaterial.reflectionTexture = this.reflectionTexture.clone();
  12045. }
  12046. if (this.emissiveTexture && this.emissiveTexture.clone) {
  12047. newStandardMaterial.emissiveTexture = this.emissiveTexture.clone();
  12048. }
  12049. if (this.specularTexture && this.specularTexture.clone) {
  12050. newStandardMaterial.specularTexture = this.specularTexture.clone();
  12051. }
  12052. if (this.bumpTexture && this.bumpTexture.clone) {
  12053. newStandardMaterial.bumpTexture = this.bumpTexture.clone();
  12054. }
  12055. newStandardMaterial.ambientColor = this.ambientColor.clone();
  12056. newStandardMaterial.diffuseColor = this.diffuseColor.clone();
  12057. newStandardMaterial.specularColor = this.specularColor.clone();
  12058. newStandardMaterial.specularPower = this.specularPower;
  12059. newStandardMaterial.emissiveColor = this.emissiveColor.clone();
  12060. return newStandardMaterial;
  12061. };
  12062. StandardMaterial.DiffuseTextureEnabled = true;
  12063. StandardMaterial.AmbientTextureEnabled = true;
  12064. StandardMaterial.OpacityTextureEnabled = true;
  12065. StandardMaterial.ReflectionTextureEnabled = true;
  12066. StandardMaterial.EmissiveTextureEnabled = true;
  12067. StandardMaterial.SpecularTextureEnabled = true;
  12068. StandardMaterial.BumpTextureEnabled = true;
  12069. return StandardMaterial;
  12070. })(BABYLON.Material);
  12071. BABYLON.StandardMaterial = StandardMaterial;
  12072. })(BABYLON || (BABYLON = {}));
  12073. var __extends = this.__extends || function (d, b) {
  12074. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  12075. function __() { this.constructor = d; }
  12076. __.prototype = b.prototype;
  12077. d.prototype = new __();
  12078. };
  12079. var BABYLON;
  12080. (function (BABYLON) {
  12081. var MultiMaterial = (function (_super) {
  12082. __extends(MultiMaterial, _super);
  12083. function MultiMaterial(name, scene) {
  12084. _super.call(this, name, scene, true);
  12085. this.subMaterials = new Array();
  12086. scene.multiMaterials.push(this);
  12087. }
  12088. MultiMaterial.prototype.getSubMaterial = function (index) {
  12089. if (index < 0 || index >= this.subMaterials.length) {
  12090. return this.getScene().defaultMaterial;
  12091. }
  12092. return this.subMaterials[index];
  12093. };
  12094. MultiMaterial.prototype.isReady = function (mesh) {
  12095. for (var index = 0; index < this.subMaterials.length; index++) {
  12096. var subMaterial = this.subMaterials[index];
  12097. if (subMaterial) {
  12098. if (!this.subMaterials[index].isReady(mesh)) {
  12099. return false;
  12100. }
  12101. }
  12102. }
  12103. return true;
  12104. };
  12105. return MultiMaterial;
  12106. })(BABYLON.Material);
  12107. BABYLON.MultiMaterial = MultiMaterial;
  12108. })(BABYLON || (BABYLON = {}));
  12109. var BABYLON;
  12110. (function (BABYLON) {
  12111. var Database = (function () {
  12112. function Database(urlToScene, callbackManifestChecked) {
  12113. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  12114. this.callbackManifestChecked = callbackManifestChecked;
  12115. this.currentSceneUrl = BABYLON.Database.ReturnFullUrlLocation(urlToScene);
  12116. this.db = null;
  12117. this.enableSceneOffline = false;
  12118. this.enableTexturesOffline = false;
  12119. this.manifestVersionFound = 0;
  12120. this.mustUpdateRessources = false;
  12121. this.hasReachedQuota = false;
  12122. this.checkManifestFile();
  12123. }
  12124. Database.prototype.checkManifestFile = function () {
  12125. var _this = this;
  12126. function noManifestFile() {
  12127. BABYLON.Tools.Log("Valid manifest file not found. Scene & textures will be loaded directly from the web server.");
  12128. that.enableSceneOffline = false;
  12129. that.enableTexturesOffline = false;
  12130. that.callbackManifestChecked(false);
  12131. }
  12132. var that = this;
  12133. var manifestURL = this.currentSceneUrl + ".manifest";
  12134. var xhr = new XMLHttpRequest();
  12135. var manifestURLTimeStamped = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  12136. xhr.open("GET", manifestURLTimeStamped, true);
  12137. xhr.addEventListener("load", function () {
  12138. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  12139. try {
  12140. var manifestFile = JSON.parse(xhr.response);
  12141. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  12142. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  12143. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  12144. _this.manifestVersionFound = manifestFile.version;
  12145. }
  12146. if (_this.callbackManifestChecked) {
  12147. _this.callbackManifestChecked(true);
  12148. }
  12149. } catch (ex) {
  12150. noManifestFile();
  12151. }
  12152. } else {
  12153. noManifestFile();
  12154. }
  12155. }, false);
  12156. xhr.addEventListener("error", function (event) {
  12157. noManifestFile();
  12158. }, false);
  12159. try {
  12160. xhr.send();
  12161. } catch (ex) {
  12162. BABYLON.Tools.Error("Error on XHR send request.");
  12163. that.callbackManifestChecked(false);
  12164. }
  12165. };
  12166. Database.prototype.openAsync = function (successCallback, errorCallback) {
  12167. var _this = this;
  12168. function handleError() {
  12169. that.isSupported = false;
  12170. if (errorCallback)
  12171. errorCallback();
  12172. }
  12173. var that = this;
  12174. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  12175. this.isSupported = false;
  12176. if (errorCallback)
  12177. errorCallback();
  12178. } else {
  12179. if (!this.db) {
  12180. this.hasReachedQuota = false;
  12181. this.isSupported = true;
  12182. var request = this.idbFactory.open("babylonjs", 1);
  12183. request.onerror = function (event) {
  12184. handleError();
  12185. };
  12186. request.onblocked = function (event) {
  12187. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  12188. handleError();
  12189. };
  12190. request.onsuccess = function (event) {
  12191. _this.db = request.result;
  12192. successCallback();
  12193. };
  12194. request.onupgradeneeded = function (event) {
  12195. _this.db = (event.target).result;
  12196. try {
  12197. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  12198. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  12199. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  12200. } catch (ex) {
  12201. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  12202. handleError();
  12203. }
  12204. };
  12205. } else {
  12206. if (successCallback)
  12207. successCallback();
  12208. }
  12209. }
  12210. };
  12211. Database.prototype.loadImageFromDB = function (url, image) {
  12212. var _this = this;
  12213. var completeURL = BABYLON.Database.ReturnFullUrlLocation(url);
  12214. var saveAndLoadImage = function () {
  12215. if (!_this.hasReachedQuota && _this.db !== null) {
  12216. _this._saveImageIntoDBAsync(completeURL, image);
  12217. } else {
  12218. image.src = url;
  12219. }
  12220. };
  12221. if (!this.mustUpdateRessources) {
  12222. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  12223. } else {
  12224. saveAndLoadImage();
  12225. }
  12226. };
  12227. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  12228. if (this.isSupported && this.db !== null) {
  12229. var texture;
  12230. var transaction = this.db.transaction(["textures"]);
  12231. transaction.onabort = function (event) {
  12232. image.src = url;
  12233. };
  12234. transaction.oncomplete = function (event) {
  12235. var blobTextureURL;
  12236. if (texture) {
  12237. var URL = window.URL || window.webkitURL;
  12238. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  12239. image.onerror = function () {
  12240. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  12241. image.src = url;
  12242. };
  12243. image.src = blobTextureURL;
  12244. } else {
  12245. notInDBCallback();
  12246. }
  12247. };
  12248. var getRequest = transaction.objectStore("textures").get(url);
  12249. getRequest.onsuccess = function (event) {
  12250. texture = (event.target).result;
  12251. };
  12252. getRequest.onerror = function (event) {
  12253. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  12254. image.src = url;
  12255. };
  12256. } else {
  12257. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  12258. image.src = url;
  12259. }
  12260. };
  12261. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  12262. var _this = this;
  12263. if (this.isSupported) {
  12264. var generateBlobUrl = function () {
  12265. var blobTextureURL;
  12266. if (blob) {
  12267. var URL = window.URL || window.webkitURL;
  12268. try {
  12269. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  12270. } catch (ex) {
  12271. blobTextureURL = URL.createObjectURL(blob);
  12272. }
  12273. }
  12274. image.src = blobTextureURL;
  12275. };
  12276. if (BABYLON.Database.isUASupportingBlobStorage) {
  12277. var xhr = new XMLHttpRequest(), blob;
  12278. xhr.open("GET", url, true);
  12279. xhr.responseType = "blob";
  12280. xhr.addEventListener("load", function () {
  12281. if (xhr.status === 200) {
  12282. blob = xhr.response;
  12283. var transaction = _this.db.transaction(["textures"], "readwrite");
  12284. transaction.onabort = function (event) {
  12285. try {
  12286. if (event.srcElement.error.name === "QuotaExceededError") {
  12287. this.hasReachedQuota = true;
  12288. }
  12289. } catch (ex) {
  12290. }
  12291. generateBlobUrl();
  12292. };
  12293. transaction.oncomplete = function (event) {
  12294. generateBlobUrl();
  12295. };
  12296. var newTexture = { textureUrl: url, data: blob };
  12297. try {
  12298. var addRequest = transaction.objectStore("textures").put(newTexture);
  12299. addRequest.onsuccess = function (event) {
  12300. };
  12301. addRequest.onerror = function (event) {
  12302. generateBlobUrl();
  12303. };
  12304. } catch (ex) {
  12305. if (ex.code === 25) {
  12306. BABYLON.Database.isUASupportingBlobStorage = false;
  12307. }
  12308. image.src = url;
  12309. }
  12310. } else {
  12311. image.src = url;
  12312. }
  12313. }, false);
  12314. xhr.addEventListener("error", function (event) {
  12315. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  12316. image.src = url;
  12317. }, false);
  12318. xhr.send();
  12319. } else {
  12320. image.src = url;
  12321. }
  12322. } else {
  12323. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  12324. image.src = url;
  12325. }
  12326. };
  12327. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  12328. var _this = this;
  12329. var updateVersion = function (event) {
  12330. _this._saveVersionIntoDBAsync(url, versionLoaded);
  12331. };
  12332. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  12333. };
  12334. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  12335. var _this = this;
  12336. if (this.isSupported) {
  12337. var version;
  12338. try {
  12339. var transaction = this.db.transaction(["versions"]);
  12340. transaction.oncomplete = function (event) {
  12341. if (version) {
  12342. if (_this.manifestVersionFound > version.data) {
  12343. _this.mustUpdateRessources = true;
  12344. updateInDBCallback();
  12345. } else {
  12346. callback(version.data);
  12347. }
  12348. } else {
  12349. _this.mustUpdateRessources = true;
  12350. updateInDBCallback();
  12351. }
  12352. };
  12353. transaction.onabort = function (event) {
  12354. callback(-1);
  12355. };
  12356. var getRequest = transaction.objectStore("versions").get(url);
  12357. getRequest.onsuccess = function (event) {
  12358. version = (event.target).result;
  12359. };
  12360. getRequest.onerror = function (event) {
  12361. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  12362. callback(-1);
  12363. };
  12364. } catch (ex) {
  12365. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  12366. callback(-1);
  12367. }
  12368. } else {
  12369. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  12370. callback(-1);
  12371. }
  12372. };
  12373. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  12374. var _this = this;
  12375. if (this.isSupported && !this.hasReachedQuota) {
  12376. try {
  12377. var transaction = this.db.transaction(["versions"], "readwrite");
  12378. transaction.onabort = function (event) {
  12379. try {
  12380. if (event.srcElement.error.name === "QuotaExceededError") {
  12381. _this.hasReachedQuota = true;
  12382. }
  12383. } catch (ex) {
  12384. }
  12385. callback(-1);
  12386. };
  12387. transaction.oncomplete = function (event) {
  12388. callback(_this.manifestVersionFound);
  12389. };
  12390. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  12391. var addRequest = transaction.objectStore("versions").put(newVersion);
  12392. addRequest.onsuccess = function (event) {
  12393. };
  12394. addRequest.onerror = function (event) {
  12395. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  12396. };
  12397. } catch (ex) {
  12398. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  12399. callback(-1);
  12400. }
  12401. } else {
  12402. callback(-1);
  12403. }
  12404. };
  12405. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  12406. var _this = this;
  12407. var completeUrl = BABYLON.Database.ReturnFullUrlLocation(url);
  12408. var saveAndLoadFile = function (event) {
  12409. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  12410. };
  12411. this._checkVersionFromDB(completeUrl, function (version) {
  12412. if (version !== -1) {
  12413. if (!_this.mustUpdateRessources) {
  12414. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  12415. } else {
  12416. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  12417. }
  12418. } else {
  12419. errorCallback();
  12420. }
  12421. });
  12422. };
  12423. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  12424. if (this.isSupported) {
  12425. var targetStore;
  12426. if (url.indexOf(".babylon") !== -1) {
  12427. targetStore = "scenes";
  12428. } else {
  12429. targetStore = "textures";
  12430. }
  12431. var file;
  12432. var transaction = this.db.transaction([targetStore]);
  12433. transaction.oncomplete = function (event) {
  12434. if (file) {
  12435. callback(file.data);
  12436. } else {
  12437. notInDBCallback();
  12438. }
  12439. };
  12440. transaction.onabort = function (event) {
  12441. notInDBCallback();
  12442. };
  12443. var getRequest = transaction.objectStore(targetStore).get(url);
  12444. getRequest.onsuccess = function (event) {
  12445. file = (event.target).result;
  12446. };
  12447. getRequest.onerror = function (event) {
  12448. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  12449. notInDBCallback();
  12450. };
  12451. } else {
  12452. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  12453. callback();
  12454. }
  12455. };
  12456. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  12457. var _this = this;
  12458. if (this.isSupported) {
  12459. var targetStore;
  12460. if (url.indexOf(".babylon") !== -1) {
  12461. targetStore = "scenes";
  12462. } else {
  12463. targetStore = "textures";
  12464. }
  12465. var xhr = new XMLHttpRequest(), fileData;
  12466. xhr.open("GET", url, true);
  12467. if (useArrayBuffer) {
  12468. xhr.responseType = "arraybuffer";
  12469. }
  12470. xhr.onprogress = progressCallback;
  12471. xhr.addEventListener("load", function () {
  12472. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  12473. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  12474. if (!_this.hasReachedQuota) {
  12475. var transaction = _this.db.transaction([targetStore], "readwrite");
  12476. transaction.onabort = function (event) {
  12477. try {
  12478. if (event.srcElement.error.name === "QuotaExceededError") {
  12479. this.hasReachedQuota = true;
  12480. }
  12481. } catch (ex) {
  12482. }
  12483. callback(fileData);
  12484. };
  12485. transaction.oncomplete = function (event) {
  12486. callback(fileData);
  12487. };
  12488. var newFile;
  12489. if (targetStore === "scenes") {
  12490. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  12491. } else {
  12492. newFile = { textureUrl: url, data: fileData };
  12493. }
  12494. try {
  12495. var addRequest = transaction.objectStore(targetStore).put(newFile);
  12496. addRequest.onsuccess = function (event) {
  12497. };
  12498. addRequest.onerror = function (event) {
  12499. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  12500. };
  12501. } catch (ex) {
  12502. callback(fileData);
  12503. }
  12504. } else {
  12505. callback(fileData);
  12506. }
  12507. } else {
  12508. callback();
  12509. }
  12510. }, false);
  12511. xhr.addEventListener("error", function (event) {
  12512. BABYLON.Tools.Error("error on XHR request.");
  12513. callback();
  12514. }, false);
  12515. xhr.send();
  12516. } else {
  12517. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  12518. callback();
  12519. }
  12520. };
  12521. Database.isUASupportingBlobStorage = true;
  12522. Database.parseURL = function (url) {
  12523. var a = document.createElement('a');
  12524. a.href = url;
  12525. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  12526. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  12527. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  12528. return absLocation;
  12529. };
  12530. Database.ReturnFullUrlLocation = function (url) {
  12531. if (url.indexOf("http:/") === -1) {
  12532. return (BABYLON.Database.parseURL(window.location.href) + url);
  12533. } else {
  12534. return url;
  12535. }
  12536. };
  12537. return Database;
  12538. })();
  12539. BABYLON.Database = Database;
  12540. })(BABYLON || (BABYLON = {}));
  12541. var BABYLON;
  12542. (function (BABYLON) {
  12543. var SpriteManager = (function () {
  12544. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon) {
  12545. this.name = name;
  12546. this.cellSize = cellSize;
  12547. this.sprites = new Array();
  12548. this.renderingGroupId = 0;
  12549. this.fogEnabled = true;
  12550. this._vertexDeclaration = [3, 4, 4, 4];
  12551. this._vertexStrideSize = 15 * 4;
  12552. this._capacity = capacity;
  12553. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false);
  12554. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  12555. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  12556. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  12557. this._scene = scene;
  12558. this._scene.spriteManagers.push(this);
  12559. this._vertexDeclaration = [3, 4, 4, 4];
  12560. this._vertexStrideSize = 15 * 4;
  12561. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  12562. var indices = [];
  12563. var index = 0;
  12564. for (var count = 0; count < capacity; count++) {
  12565. indices.push(index);
  12566. indices.push(index + 1);
  12567. indices.push(index + 2);
  12568. indices.push(index);
  12569. indices.push(index + 2);
  12570. indices.push(index + 3);
  12571. index += 4;
  12572. }
  12573. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  12574. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  12575. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  12576. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  12577. }
  12578. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  12579. var arrayOffset = index * 15;
  12580. if (offsetX == 0)
  12581. offsetX = this._epsilon;
  12582. else if (offsetX == 1)
  12583. offsetX = 1 - this._epsilon;
  12584. if (offsetY == 0)
  12585. offsetY = this._epsilon;
  12586. else if (offsetY == 1)
  12587. offsetY = 1 - this._epsilon;
  12588. this._vertices[arrayOffset] = sprite.position.x;
  12589. this._vertices[arrayOffset + 1] = sprite.position.y;
  12590. this._vertices[arrayOffset + 2] = sprite.position.z;
  12591. this._vertices[arrayOffset + 3] = sprite.angle;
  12592. this._vertices[arrayOffset + 4] = sprite.size;
  12593. this._vertices[arrayOffset + 5] = offsetX;
  12594. this._vertices[arrayOffset + 6] = offsetY;
  12595. this._vertices[arrayOffset + 7] = sprite.invertU ? 1 : 0;
  12596. this._vertices[arrayOffset + 8] = sprite.invertV ? 1 : 0;
  12597. var offset = (sprite.cellIndex / rowSize) >> 0;
  12598. this._vertices[arrayOffset + 9] = sprite.cellIndex - offset * rowSize;
  12599. this._vertices[arrayOffset + 10] = offset;
  12600. this._vertices[arrayOffset + 11] = sprite.color.r;
  12601. this._vertices[arrayOffset + 12] = sprite.color.g;
  12602. this._vertices[arrayOffset + 13] = sprite.color.b;
  12603. this._vertices[arrayOffset + 14] = sprite.color.a;
  12604. };
  12605. SpriteManager.prototype.render = function () {
  12606. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  12607. return;
  12608. var engine = this._scene.getEngine();
  12609. var baseSize = this._spriteTexture.getBaseSize();
  12610. var deltaTime = BABYLON.Tools.GetDeltaTime();
  12611. var max = Math.min(this._capacity, this.sprites.length);
  12612. var rowSize = baseSize.width / this.cellSize;
  12613. var offset = 0;
  12614. for (var index = 0; index < max; index++) {
  12615. var sprite = this.sprites[index];
  12616. if (!sprite) {
  12617. continue;
  12618. }
  12619. sprite._animate(deltaTime);
  12620. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  12621. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  12622. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  12623. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  12624. }
  12625. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices, max * this._vertexStrideSize);
  12626. var effect = this._effectBase;
  12627. if (this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  12628. effect = this._effectFog;
  12629. }
  12630. engine.enableEffect(effect);
  12631. var viewMatrix = this._scene.getViewMatrix();
  12632. effect.setTexture("diffuseSampler", this._spriteTexture);
  12633. effect.setMatrix("view", viewMatrix);
  12634. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  12635. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  12636. if (this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  12637. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  12638. effect.setColor3("vFogColor", this._scene.fogColor);
  12639. }
  12640. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  12641. effect.setBool("alphaTest", true);
  12642. engine.setColorWrite(false);
  12643. engine.draw(true, 0, max * 6);
  12644. engine.setColorWrite(true);
  12645. effect.setBool("alphaTest", false);
  12646. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  12647. engine.draw(true, 0, max * 6);
  12648. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  12649. };
  12650. SpriteManager.prototype.dispose = function () {
  12651. if (this._vertexBuffer) {
  12652. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  12653. this._vertexBuffer = null;
  12654. }
  12655. if (this._indexBuffer) {
  12656. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  12657. this._indexBuffer = null;
  12658. }
  12659. if (this._spriteTexture) {
  12660. this._spriteTexture.dispose();
  12661. this._spriteTexture = null;
  12662. }
  12663. var index = this._scene.spriteManagers.indexOf(this);
  12664. this._scene.spriteManagers.splice(index, 1);
  12665. if (this.onDispose) {
  12666. this.onDispose();
  12667. }
  12668. };
  12669. return SpriteManager;
  12670. })();
  12671. BABYLON.SpriteManager = SpriteManager;
  12672. })(BABYLON || (BABYLON = {}));
  12673. var BABYLON;
  12674. (function (BABYLON) {
  12675. var Sprite = (function () {
  12676. function Sprite(name, manager) {
  12677. this.name = name;
  12678. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  12679. this.size = 1.0;
  12680. this.angle = 0;
  12681. this.cellIndex = 0;
  12682. this.invertU = 0;
  12683. this.invertV = 0;
  12684. this.animations = new Array();
  12685. this._animationStarted = false;
  12686. this._loopAnimation = false;
  12687. this._fromIndex = 0;
  12688. this._toIndex = 0;
  12689. this._delay = 0;
  12690. this._direction = 1;
  12691. this._frameCount = 0;
  12692. this._time = 0;
  12693. this._manager = manager;
  12694. this._manager.sprites.push(this);
  12695. this.position = BABYLON.Vector3.Zero();
  12696. }
  12697. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  12698. this._fromIndex = from;
  12699. this._toIndex = to;
  12700. this._loopAnimation = loop;
  12701. this._delay = delay;
  12702. this._animationStarted = true;
  12703. this._direction = from < to ? 1 : -1;
  12704. this.cellIndex = from;
  12705. this._time = 0;
  12706. };
  12707. Sprite.prototype.stopAnimation = function () {
  12708. this._animationStarted = false;
  12709. };
  12710. Sprite.prototype._animate = function (deltaTime) {
  12711. if (!this._animationStarted)
  12712. return;
  12713. this._time += deltaTime;
  12714. if (this._time > this._delay) {
  12715. this._time = this._time % this._delay;
  12716. this.cellIndex += this._direction;
  12717. if (this.cellIndex == this._toIndex) {
  12718. if (this._loopAnimation) {
  12719. this.cellIndex = this._fromIndex;
  12720. } else {
  12721. this._animationStarted = false;
  12722. if (this.disposeWhenFinishedAnimating) {
  12723. this.dispose();
  12724. }
  12725. }
  12726. }
  12727. }
  12728. };
  12729. Sprite.prototype.dispose = function () {
  12730. for (var i = 0; i < this._manager.sprites.length; i++) {
  12731. if (this._manager.sprites[i] == this) {
  12732. this._manager.sprites.splice(i, 1);
  12733. }
  12734. }
  12735. };
  12736. return Sprite;
  12737. })();
  12738. BABYLON.Sprite = Sprite;
  12739. })(BABYLON || (BABYLON = {}));
  12740. var BABYLON;
  12741. (function (BABYLON) {
  12742. var Layer = (function () {
  12743. function Layer(name, imgUrl, scene, isBackground, color) {
  12744. this.name = name;
  12745. this._vertexDeclaration = [2];
  12746. this._vertexStrideSize = 2 * 4;
  12747. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  12748. this.isBackground = isBackground === undefined ? true : isBackground;
  12749. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  12750. this._scene = scene;
  12751. this._scene.layers.push(this);
  12752. var vertices = [];
  12753. vertices.push(1, 1);
  12754. vertices.push(-1, 1);
  12755. vertices.push(-1, -1);
  12756. vertices.push(1, -1);
  12757. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  12758. var indices = [];
  12759. indices.push(0);
  12760. indices.push(1);
  12761. indices.push(2);
  12762. indices.push(0);
  12763. indices.push(2);
  12764. indices.push(3);
  12765. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  12766. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color"], ["textureSampler"], "");
  12767. }
  12768. Layer.prototype.render = function () {
  12769. if (!this._effect.isReady() || !this.texture || !this.texture.isReady())
  12770. return;
  12771. var engine = this._scene.getEngine();
  12772. engine.enableEffect(this._effect);
  12773. engine.setState(false);
  12774. this._effect.setTexture("textureSampler", this.texture);
  12775. this._effect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  12776. this._effect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  12777. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  12778. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  12779. engine.draw(true, 0, 6);
  12780. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  12781. };
  12782. Layer.prototype.dispose = function () {
  12783. if (this._vertexBuffer) {
  12784. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  12785. this._vertexBuffer = null;
  12786. }
  12787. if (this._indexBuffer) {
  12788. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  12789. this._indexBuffer = null;
  12790. }
  12791. if (this.texture) {
  12792. this.texture.dispose();
  12793. this.texture = null;
  12794. }
  12795. var index = this._scene.layers.indexOf(this);
  12796. this._scene.layers.splice(index, 1);
  12797. if (this.onDispose) {
  12798. this.onDispose();
  12799. }
  12800. };
  12801. return Layer;
  12802. })();
  12803. BABYLON.Layer = Layer;
  12804. })(BABYLON || (BABYLON = {}));
  12805. var BABYLON;
  12806. (function (BABYLON) {
  12807. var Particle = (function () {
  12808. function Particle() {
  12809. this.position = BABYLON.Vector3.Zero();
  12810. this.direction = BABYLON.Vector3.Zero();
  12811. this.color = new BABYLON.Color4(0, 0, 0, 0);
  12812. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  12813. this.lifeTime = 1.0;
  12814. this.age = 0;
  12815. this.size = 0;
  12816. this.angle = 0;
  12817. this.angularSpeed = 0;
  12818. }
  12819. return Particle;
  12820. })();
  12821. BABYLON.Particle = Particle;
  12822. })(BABYLON || (BABYLON = {}));
  12823. var BABYLON;
  12824. (function (BABYLON) {
  12825. var randomNumber = function (min, max) {
  12826. if (min == max) {
  12827. return (min);
  12828. }
  12829. var random = Math.random();
  12830. return ((random * (max - min)) + min);
  12831. };
  12832. var ParticleSystem = (function () {
  12833. function ParticleSystem(name, capacity, scene, customEffect) {
  12834. var _this = this;
  12835. this.name = name;
  12836. this.renderingGroupId = 0;
  12837. this.emitter = null;
  12838. this.emitRate = 10;
  12839. this.manualEmitCount = -1;
  12840. this.updateSpeed = 0.01;
  12841. this.targetStopDuration = 0;
  12842. this.disposeOnStop = false;
  12843. this.minEmitPower = 1;
  12844. this.maxEmitPower = 1;
  12845. this.minLifeTime = 1;
  12846. this.maxLifeTime = 1;
  12847. this.minSize = 1;
  12848. this.maxSize = 1;
  12849. this.minAngularSpeed = 0;
  12850. this.maxAngularSpeed = 0;
  12851. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  12852. this.forceDepthWrite = false;
  12853. this.gravity = BABYLON.Vector3.Zero();
  12854. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  12855. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  12856. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  12857. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  12858. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  12859. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  12860. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  12861. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  12862. this.particles = new Array();
  12863. this._vertexDeclaration = [3, 4, 4];
  12864. this._vertexStrideSize = 11 * 4;
  12865. this._stockParticles = new Array();
  12866. this._newPartsExcess = 0;
  12867. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  12868. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  12869. this._scaledDirection = BABYLON.Vector3.Zero();
  12870. this._scaledGravity = BABYLON.Vector3.Zero();
  12871. this._currentRenderId = -1;
  12872. this._started = false;
  12873. this._stopped = false;
  12874. this._actualFrame = 0;
  12875. this.id = name;
  12876. this._capacity = capacity;
  12877. this._scene = scene;
  12878. this._customEffect = customEffect;
  12879. scene.particleSystems.push(this);
  12880. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  12881. var indices = [];
  12882. var index = 0;
  12883. for (var count = 0; count < capacity; count++) {
  12884. indices.push(index);
  12885. indices.push(index + 1);
  12886. indices.push(index + 2);
  12887. indices.push(index);
  12888. indices.push(index + 2);
  12889. indices.push(index + 3);
  12890. index += 4;
  12891. }
  12892. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  12893. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  12894. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate) {
  12895. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  12896. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  12897. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  12898. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  12899. };
  12900. this.startPositionFunction = function (worldMatrix, positionToUpdate) {
  12901. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  12902. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  12903. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  12904. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  12905. };
  12906. }
  12907. ParticleSystem.prototype.getCapacity = function () {
  12908. return this._capacity;
  12909. };
  12910. ParticleSystem.prototype.isAlive = function () {
  12911. return this._alive;
  12912. };
  12913. ParticleSystem.prototype.isStarted = function () {
  12914. return this._started;
  12915. };
  12916. ParticleSystem.prototype.start = function () {
  12917. this._started = true;
  12918. this._stopped = false;
  12919. this._actualFrame = 0;
  12920. };
  12921. ParticleSystem.prototype.stop = function () {
  12922. this._stopped = true;
  12923. };
  12924. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  12925. var offset = index * 11;
  12926. this._vertices[offset] = particle.position.x;
  12927. this._vertices[offset + 1] = particle.position.y;
  12928. this._vertices[offset + 2] = particle.position.z;
  12929. this._vertices[offset + 3] = particle.color.r;
  12930. this._vertices[offset + 4] = particle.color.g;
  12931. this._vertices[offset + 5] = particle.color.b;
  12932. this._vertices[offset + 6] = particle.color.a;
  12933. this._vertices[offset + 7] = particle.angle;
  12934. this._vertices[offset + 8] = particle.size;
  12935. this._vertices[offset + 9] = offsetX;
  12936. this._vertices[offset + 10] = offsetY;
  12937. };
  12938. ParticleSystem.prototype._update = function (newParticles) {
  12939. this._alive = this.particles.length > 0;
  12940. for (var index = 0; index < this.particles.length; index++) {
  12941. var particle = this.particles[index];
  12942. particle.age += this._scaledUpdateSpeed;
  12943. if (particle.age >= particle.lifeTime) {
  12944. this._stockParticles.push(this.particles.splice(index, 1)[0]);
  12945. index--;
  12946. continue;
  12947. } else {
  12948. particle.colorStep.scaleToRef(this._scaledUpdateSpeed, this._scaledColorStep);
  12949. particle.color.addInPlace(this._scaledColorStep);
  12950. if (particle.color.a < 0)
  12951. particle.color.a = 0;
  12952. particle.angle += particle.angularSpeed * this._scaledUpdateSpeed;
  12953. particle.direction.scaleToRef(this._scaledUpdateSpeed, this._scaledDirection);
  12954. particle.position.addInPlace(this._scaledDirection);
  12955. this.gravity.scaleToRef(this._scaledUpdateSpeed, this._scaledGravity);
  12956. particle.direction.addInPlace(this._scaledGravity);
  12957. }
  12958. }
  12959. var worldMatrix;
  12960. if (this.emitter.position) {
  12961. worldMatrix = this.emitter.getWorldMatrix();
  12962. } else {
  12963. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  12964. }
  12965. for (index = 0; index < newParticles; index++) {
  12966. if (this.particles.length == this._capacity) {
  12967. break;
  12968. }
  12969. if (this._stockParticles.length !== 0) {
  12970. particle = this._stockParticles.pop();
  12971. particle.age = 0;
  12972. } else {
  12973. particle = new BABYLON.Particle();
  12974. }
  12975. this.particles.push(particle);
  12976. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  12977. this.startDirectionFunction(emitPower, worldMatrix, particle.direction);
  12978. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  12979. particle.size = randomNumber(this.minSize, this.maxSize);
  12980. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  12981. this.startPositionFunction(worldMatrix, particle.position);
  12982. var step = randomNumber(0, 1.0);
  12983. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  12984. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  12985. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  12986. }
  12987. };
  12988. ParticleSystem.prototype._getEffect = function () {
  12989. if (this._customEffect) {
  12990. return this._customEffect;
  12991. }
  12992. ;
  12993. var defines = [];
  12994. if (this._scene.clipPlane) {
  12995. defines.push("#define CLIPPLANE");
  12996. }
  12997. var join = defines.join("\n");
  12998. if (this._cachedDefines != join) {
  12999. this._cachedDefines = join;
  13000. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  13001. }
  13002. return this._effect;
  13003. };
  13004. ParticleSystem.prototype.animate = function () {
  13005. if (!this._started)
  13006. return;
  13007. var effect = this._getEffect();
  13008. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  13009. return;
  13010. if (this._currentRenderId === this._scene.getRenderId()) {
  13011. return;
  13012. }
  13013. this._currentRenderId = this._scene.getRenderId();
  13014. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  13015. var emitCout;
  13016. if (this.manualEmitCount > -1) {
  13017. emitCout = this.manualEmitCount;
  13018. this.manualEmitCount = 0;
  13019. } else {
  13020. emitCout = this.emitRate;
  13021. }
  13022. var newParticles = ((emitCout * this._scaledUpdateSpeed) >> 0);
  13023. this._newPartsExcess += emitCout * this._scaledUpdateSpeed - newParticles;
  13024. if (this._newPartsExcess > 1.0) {
  13025. newParticles += this._newPartsExcess >> 0;
  13026. this._newPartsExcess -= this._newPartsExcess >> 0;
  13027. }
  13028. this._alive = false;
  13029. if (!this._stopped) {
  13030. this._actualFrame += this._scaledUpdateSpeed;
  13031. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  13032. this.stop();
  13033. } else {
  13034. newParticles = 0;
  13035. }
  13036. this._update(newParticles);
  13037. if (this._stopped) {
  13038. if (!this._alive) {
  13039. this._started = false;
  13040. if (this.disposeOnStop) {
  13041. this._scene._toBeDisposed.push(this);
  13042. }
  13043. }
  13044. }
  13045. var offset = 0;
  13046. for (var index = 0; index < this.particles.length; index++) {
  13047. var particle = this.particles[index];
  13048. this._appendParticleVertex(offset++, particle, 0, 0);
  13049. this._appendParticleVertex(offset++, particle, 1, 0);
  13050. this._appendParticleVertex(offset++, particle, 1, 1);
  13051. this._appendParticleVertex(offset++, particle, 0, 1);
  13052. }
  13053. var engine = this._scene.getEngine();
  13054. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices, this.particles.length * this._vertexStrideSize);
  13055. };
  13056. ParticleSystem.prototype.render = function () {
  13057. var effect = this._getEffect();
  13058. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  13059. return 0;
  13060. var engine = this._scene.getEngine();
  13061. engine.enableEffect(effect);
  13062. var viewMatrix = this._scene.getViewMatrix();
  13063. effect.setTexture("diffuseSampler", this.particleTexture);
  13064. effect.setMatrix("view", viewMatrix);
  13065. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  13066. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  13067. if (this._scene.clipPlane) {
  13068. var clipPlane = this._scene.clipPlane;
  13069. var invView = viewMatrix.clone();
  13070. invView.invert();
  13071. effect.setMatrix("invView", invView);
  13072. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  13073. }
  13074. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  13075. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_ONEONE) {
  13076. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  13077. } else {
  13078. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  13079. }
  13080. if (this.forceDepthWrite) {
  13081. engine.setDepthWrite(true);
  13082. }
  13083. engine.draw(true, 0, this.particles.length * 6);
  13084. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  13085. return this.particles.length;
  13086. };
  13087. ParticleSystem.prototype.dispose = function () {
  13088. if (this._vertexBuffer) {
  13089. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  13090. this._vertexBuffer = null;
  13091. }
  13092. if (this._indexBuffer) {
  13093. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  13094. this._indexBuffer = null;
  13095. }
  13096. if (this.particleTexture) {
  13097. this.particleTexture.dispose();
  13098. this.particleTexture = null;
  13099. }
  13100. var index = this._scene.particleSystems.indexOf(this);
  13101. this._scene.particleSystems.splice(index, 1);
  13102. if (this.onDispose) {
  13103. this.onDispose();
  13104. }
  13105. };
  13106. ParticleSystem.prototype.clone = function (name, newEmitter) {
  13107. var result = new BABYLON.ParticleSystem(name, this._capacity, this._scene);
  13108. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  13109. if (newEmitter === undefined) {
  13110. newEmitter = this.emitter;
  13111. }
  13112. result.emitter = newEmitter;
  13113. if (this.particleTexture) {
  13114. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  13115. }
  13116. result.start();
  13117. return result;
  13118. };
  13119. ParticleSystem.BLENDMODE_ONEONE = 0;
  13120. ParticleSystem.BLENDMODE_STANDARD = 1;
  13121. return ParticleSystem;
  13122. })();
  13123. BABYLON.ParticleSystem = ParticleSystem;
  13124. })(BABYLON || (BABYLON = {}));
  13125. var BABYLON;
  13126. (function (BABYLON) {
  13127. var Animation = (function () {
  13128. function Animation(name, targetProperty, framePerSecond, dataType, loopMode) {
  13129. this.name = name;
  13130. this.targetProperty = targetProperty;
  13131. this.framePerSecond = framePerSecond;
  13132. this.dataType = dataType;
  13133. this.loopMode = loopMode;
  13134. this._offsetsCache = {};
  13135. this._highLimitsCache = {};
  13136. this._stopped = false;
  13137. this.targetPropertyPath = targetProperty.split(".");
  13138. this.dataType = dataType;
  13139. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  13140. }
  13141. Animation.CreateAndStartAnimation = function (name, mesh, tartgetProperty, framePerSecond, totalFrame, from, to, loopMode) {
  13142. var dataType = undefined;
  13143. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  13144. dataType = Animation.ANIMATIONTYPE_FLOAT;
  13145. } else if (from instanceof BABYLON.Quaternion) {
  13146. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  13147. } else if (from instanceof BABYLON.Vector3) {
  13148. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  13149. } else if (from instanceof BABYLON.Vector2) {
  13150. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  13151. } else if (from instanceof BABYLON.Color3) {
  13152. dataType = Animation.ANIMATIONTYPE_COLOR3;
  13153. }
  13154. if (dataType == undefined) {
  13155. return;
  13156. }
  13157. var animation = new Animation(name, tartgetProperty, framePerSecond, dataType, loopMode);
  13158. var keys = [];
  13159. keys.push({ frame: 0, value: from });
  13160. keys.push({ frame: totalFrame, value: to });
  13161. animation.setKeys(keys);
  13162. mesh.animations.push(animation);
  13163. mesh.getScene().beginAnimation(mesh, 0, totalFrame, (animation.loopMode == 1));
  13164. };
  13165. Animation.prototype.isStopped = function () {
  13166. return this._stopped;
  13167. };
  13168. Animation.prototype.getKeys = function () {
  13169. return this._keys;
  13170. };
  13171. Animation.prototype.getEasingFunction = function () {
  13172. return this._easingFunction;
  13173. };
  13174. Animation.prototype.setEasingFunction = function (easingFunction) {
  13175. this._easingFunction = easingFunction;
  13176. };
  13177. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  13178. return startValue + (endValue - startValue) * gradient;
  13179. };
  13180. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  13181. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  13182. };
  13183. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  13184. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  13185. };
  13186. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  13187. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  13188. };
  13189. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  13190. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  13191. };
  13192. Animation.prototype.clone = function () {
  13193. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  13194. clone.setKeys(this._keys);
  13195. return clone;
  13196. };
  13197. Animation.prototype.setKeys = function (values) {
  13198. this._keys = values.slice(0);
  13199. this._offsetsCache = {};
  13200. this._highLimitsCache = {};
  13201. };
  13202. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  13203. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  13204. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  13205. }
  13206. this.currentFrame = currentFrame;
  13207. for (var key = 0; key < this._keys.length; key++) {
  13208. if (this._keys[key + 1].frame >= currentFrame) {
  13209. var startValue = this._keys[key].value;
  13210. var endValue = this._keys[key + 1].value;
  13211. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  13212. if (this._easingFunction != null) {
  13213. gradient = this._easingFunction.ease(gradient);
  13214. }
  13215. switch (this.dataType) {
  13216. case Animation.ANIMATIONTYPE_FLOAT:
  13217. switch (loopMode) {
  13218. case Animation.ANIMATIONLOOPMODE_CYCLE:
  13219. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  13220. return this.floatInterpolateFunction(startValue, endValue, gradient);
  13221. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  13222. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  13223. }
  13224. break;
  13225. case Animation.ANIMATIONTYPE_QUATERNION:
  13226. var quaternion = null;
  13227. switch (loopMode) {
  13228. case Animation.ANIMATIONLOOPMODE_CYCLE:
  13229. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  13230. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  13231. break;
  13232. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  13233. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  13234. break;
  13235. }
  13236. return quaternion;
  13237. case Animation.ANIMATIONTYPE_VECTOR3:
  13238. switch (loopMode) {
  13239. case Animation.ANIMATIONLOOPMODE_CYCLE:
  13240. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  13241. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  13242. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  13243. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  13244. }
  13245. case Animation.ANIMATIONTYPE_VECTOR2:
  13246. switch (loopMode) {
  13247. case Animation.ANIMATIONLOOPMODE_CYCLE:
  13248. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  13249. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  13250. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  13251. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  13252. }
  13253. case Animation.ANIMATIONTYPE_COLOR3:
  13254. switch (loopMode) {
  13255. case Animation.ANIMATIONLOOPMODE_CYCLE:
  13256. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  13257. return this.color3InterpolateFunction(startValue, endValue, gradient);
  13258. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  13259. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  13260. }
  13261. case Animation.ANIMATIONTYPE_MATRIX:
  13262. switch (loopMode) {
  13263. case Animation.ANIMATIONLOOPMODE_CYCLE:
  13264. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  13265. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  13266. return startValue;
  13267. }
  13268. default:
  13269. break;
  13270. }
  13271. break;
  13272. }
  13273. }
  13274. return this._keys[this._keys.length - 1].value;
  13275. };
  13276. Animation.prototype.animate = function (delay, from, to, loop, speedRatio) {
  13277. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  13278. this._stopped = true;
  13279. return false;
  13280. }
  13281. var returnValue = true;
  13282. if (this._keys[0].frame != 0) {
  13283. var newKey = { frame: 0, value: this._keys[0].value };
  13284. this._keys.splice(0, 0, newKey);
  13285. }
  13286. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  13287. from = this._keys[0].frame;
  13288. }
  13289. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  13290. to = this._keys[this._keys.length - 1].frame;
  13291. }
  13292. var range = to - from;
  13293. var offsetValue;
  13294. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  13295. if (ratio > range && !loop) {
  13296. returnValue = false;
  13297. highLimitValue = this._keys[this._keys.length - 1].value;
  13298. } else {
  13299. var highLimitValue = 0;
  13300. if (this.loopMode != Animation.ANIMATIONLOOPMODE_CYCLE) {
  13301. var keyOffset = to.toString() + from.toString();
  13302. if (!this._offsetsCache[keyOffset]) {
  13303. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  13304. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  13305. switch (this.dataType) {
  13306. case Animation.ANIMATIONTYPE_FLOAT:
  13307. this._offsetsCache[keyOffset] = toValue - fromValue;
  13308. break;
  13309. case Animation.ANIMATIONTYPE_QUATERNION:
  13310. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  13311. break;
  13312. case Animation.ANIMATIONTYPE_VECTOR3:
  13313. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  13314. case Animation.ANIMATIONTYPE_VECTOR2:
  13315. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  13316. case Animation.ANIMATIONTYPE_COLOR3:
  13317. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  13318. default:
  13319. break;
  13320. }
  13321. this._highLimitsCache[keyOffset] = toValue;
  13322. }
  13323. highLimitValue = this._highLimitsCache[keyOffset];
  13324. offsetValue = this._offsetsCache[keyOffset];
  13325. }
  13326. }
  13327. if (offsetValue === undefined) {
  13328. switch (this.dataType) {
  13329. case Animation.ANIMATIONTYPE_FLOAT:
  13330. offsetValue = 0;
  13331. break;
  13332. case Animation.ANIMATIONTYPE_QUATERNION:
  13333. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  13334. break;
  13335. case Animation.ANIMATIONTYPE_VECTOR3:
  13336. offsetValue = BABYLON.Vector3.Zero();
  13337. break;
  13338. case Animation.ANIMATIONTYPE_VECTOR2:
  13339. offsetValue = BABYLON.Vector2.Zero();
  13340. break;
  13341. case Animation.ANIMATIONTYPE_COLOR3:
  13342. offsetValue = BABYLON.Color3.Black();
  13343. }
  13344. }
  13345. var repeatCount = (ratio / range) >> 0;
  13346. var currentFrame = returnValue ? from + ratio % range : to;
  13347. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  13348. if (this.targetPropertyPath.length > 1) {
  13349. var property = this._target[this.targetPropertyPath[0]];
  13350. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  13351. property = property[this.targetPropertyPath[index]];
  13352. }
  13353. property[this.targetPropertyPath[this.targetPropertyPath.length - 1]] = currentValue;
  13354. } else {
  13355. this._target[this.targetPropertyPath[0]] = currentValue;
  13356. }
  13357. if (this._target.markAsDirty) {
  13358. this._target.markAsDirty(this.targetProperty);
  13359. }
  13360. if (!returnValue) {
  13361. this._stopped = true;
  13362. }
  13363. return returnValue;
  13364. };
  13365. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  13366. get: function () {
  13367. return Animation._ANIMATIONTYPE_FLOAT;
  13368. },
  13369. enumerable: true,
  13370. configurable: true
  13371. });
  13372. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  13373. get: function () {
  13374. return Animation._ANIMATIONTYPE_VECTOR3;
  13375. },
  13376. enumerable: true,
  13377. configurable: true
  13378. });
  13379. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  13380. get: function () {
  13381. return Animation._ANIMATIONTYPE_VECTOR2;
  13382. },
  13383. enumerable: true,
  13384. configurable: true
  13385. });
  13386. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  13387. get: function () {
  13388. return Animation._ANIMATIONTYPE_QUATERNION;
  13389. },
  13390. enumerable: true,
  13391. configurable: true
  13392. });
  13393. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  13394. get: function () {
  13395. return Animation._ANIMATIONTYPE_MATRIX;
  13396. },
  13397. enumerable: true,
  13398. configurable: true
  13399. });
  13400. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  13401. get: function () {
  13402. return Animation._ANIMATIONTYPE_COLOR3;
  13403. },
  13404. enumerable: true,
  13405. configurable: true
  13406. });
  13407. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  13408. get: function () {
  13409. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  13410. },
  13411. enumerable: true,
  13412. configurable: true
  13413. });
  13414. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  13415. get: function () {
  13416. return Animation._ANIMATIONLOOPMODE_CYCLE;
  13417. },
  13418. enumerable: true,
  13419. configurable: true
  13420. });
  13421. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  13422. get: function () {
  13423. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  13424. },
  13425. enumerable: true,
  13426. configurable: true
  13427. });
  13428. Animation._ANIMATIONTYPE_FLOAT = 0;
  13429. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  13430. Animation._ANIMATIONTYPE_QUATERNION = 2;
  13431. Animation._ANIMATIONTYPE_MATRIX = 3;
  13432. Animation._ANIMATIONTYPE_COLOR3 = 4;
  13433. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  13434. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  13435. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  13436. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  13437. return Animation;
  13438. })();
  13439. BABYLON.Animation = Animation;
  13440. })(BABYLON || (BABYLON = {}));
  13441. var BABYLON;
  13442. (function (BABYLON) {
  13443. var Animatable = (function () {
  13444. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  13445. if (typeof fromFrame === "undefined") { fromFrame = 0; }
  13446. if (typeof toFrame === "undefined") { toFrame = 100; }
  13447. if (typeof loopAnimation === "undefined") { loopAnimation = false; }
  13448. if (typeof speedRatio === "undefined") { speedRatio = 1.0; }
  13449. this.target = target;
  13450. this.fromFrame = fromFrame;
  13451. this.toFrame = toFrame;
  13452. this.loopAnimation = loopAnimation;
  13453. this.speedRatio = speedRatio;
  13454. this.onAnimationEnd = onAnimationEnd;
  13455. this._animations = new Array();
  13456. this._paused = false;
  13457. this.animationStarted = false;
  13458. if (animations) {
  13459. this.appendAnimations(target, animations);
  13460. }
  13461. this._scene = scene;
  13462. scene._activeAnimatables.push(this);
  13463. }
  13464. Animatable.prototype.appendAnimations = function (target, animations) {
  13465. for (var index = 0; index < animations.length; index++) {
  13466. var animation = animations[index];
  13467. animation._target = target;
  13468. this._animations.push(animation);
  13469. }
  13470. };
  13471. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  13472. var animations = this._animations;
  13473. for (var index = 0; index < animations.length; index++) {
  13474. if (animations[index].targetProperty === property) {
  13475. return animations[index];
  13476. }
  13477. }
  13478. return null;
  13479. };
  13480. Animatable.prototype.pause = function () {
  13481. if (this._paused) {
  13482. return;
  13483. }
  13484. this._paused = true;
  13485. };
  13486. Animatable.prototype.restart = function () {
  13487. this._paused = false;
  13488. };
  13489. Animatable.prototype.stop = function () {
  13490. var index = this._scene._activeAnimatables.indexOf(this);
  13491. if (index > -1) {
  13492. this._scene._activeAnimatables.splice(index, 1);
  13493. }
  13494. if (this.onAnimationEnd) {
  13495. this.onAnimationEnd();
  13496. }
  13497. };
  13498. Animatable.prototype._animate = function (delay) {
  13499. if (this._paused) {
  13500. if (!this._pausedDelay) {
  13501. this._pausedDelay = delay;
  13502. }
  13503. return true;
  13504. }
  13505. if (!this._localDelayOffset) {
  13506. this._localDelayOffset = delay;
  13507. } else if (this._pausedDelay) {
  13508. this._localDelayOffset += delay - this._pausedDelay;
  13509. this._pausedDelay = null;
  13510. }
  13511. var running = false;
  13512. var animations = this._animations;
  13513. for (var index = 0; index < animations.length; index++) {
  13514. var animation = animations[index];
  13515. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  13516. running = running || isRunning;
  13517. }
  13518. if (!running && this.onAnimationEnd) {
  13519. this.onAnimationEnd();
  13520. }
  13521. return running;
  13522. };
  13523. return Animatable;
  13524. })();
  13525. BABYLON.Animatable = Animatable;
  13526. })(BABYLON || (BABYLON = {}));
  13527. var __extends = this.__extends || function (d, b) {
  13528. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  13529. function __() { this.constructor = d; }
  13530. __.prototype = b.prototype;
  13531. d.prototype = new __();
  13532. };
  13533. var BABYLON;
  13534. (function (BABYLON) {
  13535. var EasingFunction = (function () {
  13536. function EasingFunction() {
  13537. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  13538. }
  13539. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  13540. get: function () {
  13541. return EasingFunction._EASINGMODE_EASEIN;
  13542. },
  13543. enumerable: true,
  13544. configurable: true
  13545. });
  13546. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  13547. get: function () {
  13548. return EasingFunction._EASINGMODE_EASEOUT;
  13549. },
  13550. enumerable: true,
  13551. configurable: true
  13552. });
  13553. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  13554. get: function () {
  13555. return EasingFunction._EASINGMODE_EASEINOUT;
  13556. },
  13557. enumerable: true,
  13558. configurable: true
  13559. });
  13560. EasingFunction.prototype.setEasingMode = function (easingMode) {
  13561. var n = Math.min(Math.max(easingMode, 0), 2);
  13562. this._easingMode = n;
  13563. };
  13564. EasingFunction.prototype.getEasingMode = function () {
  13565. return this._easingMode;
  13566. };
  13567. EasingFunction.prototype.easeInCore = function (gradient) {
  13568. throw new Error('You must implement this method');
  13569. };
  13570. EasingFunction.prototype.ease = function (gradient) {
  13571. switch (this._easingMode) {
  13572. case EasingFunction.EASINGMODE_EASEIN:
  13573. return this.easeInCore(gradient);
  13574. case EasingFunction.EASINGMODE_EASEOUT:
  13575. return (1 - this.easeInCore(1 - gradient));
  13576. }
  13577. if (gradient >= 0.5) {
  13578. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  13579. }
  13580. return (this.easeInCore(gradient * 2) * 0.5);
  13581. };
  13582. EasingFunction._EASINGMODE_EASEIN = 0;
  13583. EasingFunction._EASINGMODE_EASEOUT = 1;
  13584. EasingFunction._EASINGMODE_EASEINOUT = 2;
  13585. return EasingFunction;
  13586. })();
  13587. BABYLON.EasingFunction = EasingFunction;
  13588. var CircleEase = (function (_super) {
  13589. __extends(CircleEase, _super);
  13590. function CircleEase() {
  13591. _super.apply(this, arguments);
  13592. }
  13593. CircleEase.prototype.easeInCore = function (gradient) {
  13594. gradient = Math.max(0, Math.min(1, gradient));
  13595. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  13596. };
  13597. return CircleEase;
  13598. })(EasingFunction);
  13599. BABYLON.CircleEase = CircleEase;
  13600. var BackEase = (function (_super) {
  13601. __extends(BackEase, _super);
  13602. function BackEase(amplitude) {
  13603. if (typeof amplitude === "undefined") { amplitude = 1; }
  13604. _super.call(this);
  13605. this.amplitude = amplitude;
  13606. }
  13607. BackEase.prototype.easeInCore = function (gradient) {
  13608. var num = Math.max(0, this.amplitude);
  13609. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  13610. };
  13611. return BackEase;
  13612. })(EasingFunction);
  13613. BABYLON.BackEase = BackEase;
  13614. var BounceEase = (function (_super) {
  13615. __extends(BounceEase, _super);
  13616. function BounceEase(bounces, bounciness) {
  13617. if (typeof bounces === "undefined") { bounces = 3; }
  13618. if (typeof bounciness === "undefined") { bounciness = 2; }
  13619. _super.call(this);
  13620. this.bounces = bounces;
  13621. this.bounciness = bounciness;
  13622. }
  13623. BounceEase.prototype.easeInCore = function (gradient) {
  13624. var y = Math.max(0.0, this.bounces);
  13625. var bounciness = this.bounciness;
  13626. if (bounciness <= 1.0) {
  13627. bounciness = 1.001;
  13628. }
  13629. var num9 = Math.pow(bounciness, y);
  13630. var num5 = 1.0 - bounciness;
  13631. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  13632. var num15 = gradient * num4;
  13633. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  13634. var num3 = Math.floor(num65);
  13635. var num13 = num3 + 1.0;
  13636. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  13637. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  13638. var num7 = (num8 + num12) * 0.5;
  13639. var num6 = gradient - num7;
  13640. var num2 = num7 - num8;
  13641. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  13642. };
  13643. return BounceEase;
  13644. })(EasingFunction);
  13645. BABYLON.BounceEase = BounceEase;
  13646. var CubicEase = (function (_super) {
  13647. __extends(CubicEase, _super);
  13648. function CubicEase() {
  13649. _super.apply(this, arguments);
  13650. }
  13651. CubicEase.prototype.easeInCore = function (gradient) {
  13652. return (gradient * gradient * gradient);
  13653. };
  13654. return CubicEase;
  13655. })(EasingFunction);
  13656. BABYLON.CubicEase = CubicEase;
  13657. var ElasticEase = (function (_super) {
  13658. __extends(ElasticEase, _super);
  13659. function ElasticEase(oscillations, springiness) {
  13660. if (typeof oscillations === "undefined") { oscillations = 3; }
  13661. if (typeof springiness === "undefined") { springiness = 3; }
  13662. _super.call(this);
  13663. this.oscillations = oscillations;
  13664. this.springiness = springiness;
  13665. }
  13666. ElasticEase.prototype.easeInCore = function (gradient) {
  13667. var num2;
  13668. var num3 = Math.max(0.0, this.oscillations);
  13669. var num = Math.max(0.0, this.springiness);
  13670. if (num == 0) {
  13671. num2 = gradient;
  13672. } else {
  13673. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  13674. }
  13675. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  13676. };
  13677. return ElasticEase;
  13678. })(EasingFunction);
  13679. BABYLON.ElasticEase = ElasticEase;
  13680. var ExponentialEase = (function (_super) {
  13681. __extends(ExponentialEase, _super);
  13682. function ExponentialEase(exponent) {
  13683. if (typeof exponent === "undefined") { exponent = 2; }
  13684. _super.call(this);
  13685. this.exponent = exponent;
  13686. }
  13687. ExponentialEase.prototype.easeInCore = function (gradient) {
  13688. if (this.exponent <= 0) {
  13689. return gradient;
  13690. }
  13691. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  13692. };
  13693. return ExponentialEase;
  13694. })(EasingFunction);
  13695. BABYLON.ExponentialEase = ExponentialEase;
  13696. var PowerEase = (function (_super) {
  13697. __extends(PowerEase, _super);
  13698. function PowerEase(power) {
  13699. if (typeof power === "undefined") { power = 2; }
  13700. _super.call(this);
  13701. this.power = power;
  13702. }
  13703. PowerEase.prototype.easeInCore = function (gradient) {
  13704. var y = Math.max(0.0, this.power);
  13705. return Math.pow(gradient, y);
  13706. };
  13707. return PowerEase;
  13708. })(EasingFunction);
  13709. BABYLON.PowerEase = PowerEase;
  13710. var QuadraticEase = (function (_super) {
  13711. __extends(QuadraticEase, _super);
  13712. function QuadraticEase() {
  13713. _super.apply(this, arguments);
  13714. }
  13715. QuadraticEase.prototype.easeInCore = function (gradient) {
  13716. return (gradient * gradient);
  13717. };
  13718. return QuadraticEase;
  13719. })(EasingFunction);
  13720. BABYLON.QuadraticEase = QuadraticEase;
  13721. var QuarticEase = (function (_super) {
  13722. __extends(QuarticEase, _super);
  13723. function QuarticEase() {
  13724. _super.apply(this, arguments);
  13725. }
  13726. QuarticEase.prototype.easeInCore = function (gradient) {
  13727. return (gradient * gradient * gradient * gradient);
  13728. };
  13729. return QuarticEase;
  13730. })(EasingFunction);
  13731. BABYLON.QuarticEase = QuarticEase;
  13732. var QuinticEase = (function (_super) {
  13733. __extends(QuinticEase, _super);
  13734. function QuinticEase() {
  13735. _super.apply(this, arguments);
  13736. }
  13737. QuinticEase.prototype.easeInCore = function (gradient) {
  13738. return (gradient * gradient * gradient * gradient * gradient);
  13739. };
  13740. return QuinticEase;
  13741. })(EasingFunction);
  13742. BABYLON.QuinticEase = QuinticEase;
  13743. var SineEase = (function (_super) {
  13744. __extends(SineEase, _super);
  13745. function SineEase() {
  13746. _super.apply(this, arguments);
  13747. }
  13748. SineEase.prototype.easeInCore = function (gradient) {
  13749. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  13750. };
  13751. return SineEase;
  13752. })(EasingFunction);
  13753. BABYLON.SineEase = SineEase;
  13754. var BezierCurveEase = (function (_super) {
  13755. __extends(BezierCurveEase, _super);
  13756. function BezierCurveEase(x1, y1, x2, y2) {
  13757. if (typeof x1 === "undefined") { x1 = 0; }
  13758. if (typeof y1 === "undefined") { y1 = 0; }
  13759. if (typeof x2 === "undefined") { x2 = 1; }
  13760. if (typeof y2 === "undefined") { y2 = 1; }
  13761. _super.call(this);
  13762. this.x1 = x1;
  13763. this.y1 = y1;
  13764. this.x2 = x2;
  13765. this.y2 = y2;
  13766. }
  13767. BezierCurveEase.prototype.easeInCore = function (gradient) {
  13768. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  13769. };
  13770. return BezierCurveEase;
  13771. })(EasingFunction);
  13772. BABYLON.BezierCurveEase = BezierCurveEase;
  13773. })(BABYLON || (BABYLON = {}));
  13774. var BABYLON;
  13775. (function (BABYLON) {
  13776. var Octree = (function () {
  13777. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  13778. if (typeof maxDepth === "undefined") { maxDepth = 2; }
  13779. this.maxDepth = maxDepth;
  13780. this.dynamicContent = new Array();
  13781. this._maxBlockCapacity = maxBlockCapacity || 64;
  13782. this._selectionContent = new BABYLON.SmartArray(1024);
  13783. this._creationFunc = creationFunc;
  13784. }
  13785. Octree.prototype.update = function (worldMin, worldMax, entries) {
  13786. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  13787. };
  13788. Octree.prototype.addMesh = function (entry) {
  13789. for (var index = 0; index < this.blocks.length; index++) {
  13790. var block = this.blocks[index];
  13791. block.addEntry(entry);
  13792. }
  13793. };
  13794. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  13795. this._selectionContent.reset();
  13796. for (var index = 0; index < this.blocks.length; index++) {
  13797. var block = this.blocks[index];
  13798. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  13799. }
  13800. if (allowDuplicate) {
  13801. this._selectionContent.concat(this.dynamicContent);
  13802. } else {
  13803. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  13804. }
  13805. return this._selectionContent;
  13806. };
  13807. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  13808. this._selectionContent.reset();
  13809. for (var index = 0; index < this.blocks.length; index++) {
  13810. var block = this.blocks[index];
  13811. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  13812. }
  13813. if (allowDuplicate) {
  13814. this._selectionContent.concat(this.dynamicContent);
  13815. } else {
  13816. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  13817. }
  13818. return this._selectionContent;
  13819. };
  13820. Octree.prototype.intersectsRay = function (ray) {
  13821. this._selectionContent.reset();
  13822. for (var index = 0; index < this.blocks.length; index++) {
  13823. var block = this.blocks[index];
  13824. block.intersectsRay(ray, this._selectionContent);
  13825. }
  13826. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  13827. return this._selectionContent;
  13828. };
  13829. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  13830. target.blocks = new Array();
  13831. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  13832. for (var x = 0; x < 2; x++) {
  13833. for (var y = 0; y < 2; y++) {
  13834. for (var z = 0; z < 2; z++) {
  13835. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  13836. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  13837. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  13838. block.addEntries(entries);
  13839. target.blocks.push(block);
  13840. }
  13841. }
  13842. }
  13843. };
  13844. Octree.CreationFuncForMeshes = function (entry, block) {
  13845. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  13846. block.entries.push(entry);
  13847. }
  13848. };
  13849. Octree.CreationFuncForSubMeshes = function (entry, block) {
  13850. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  13851. block.entries.push(entry);
  13852. }
  13853. };
  13854. return Octree;
  13855. })();
  13856. BABYLON.Octree = Octree;
  13857. })(BABYLON || (BABYLON = {}));
  13858. var BABYLON;
  13859. (function (BABYLON) {
  13860. var OctreeBlock = (function () {
  13861. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  13862. this.entries = new Array();
  13863. this._boundingVectors = new Array();
  13864. this._capacity = capacity;
  13865. this._depth = depth;
  13866. this._maxDepth = maxDepth;
  13867. this._creationFunc = creationFunc;
  13868. this._minPoint = minPoint;
  13869. this._maxPoint = maxPoint;
  13870. this._boundingVectors.push(minPoint.clone());
  13871. this._boundingVectors.push(maxPoint.clone());
  13872. this._boundingVectors.push(minPoint.clone());
  13873. this._boundingVectors[2].x = maxPoint.x;
  13874. this._boundingVectors.push(minPoint.clone());
  13875. this._boundingVectors[3].y = maxPoint.y;
  13876. this._boundingVectors.push(minPoint.clone());
  13877. this._boundingVectors[4].z = maxPoint.z;
  13878. this._boundingVectors.push(maxPoint.clone());
  13879. this._boundingVectors[5].z = minPoint.z;
  13880. this._boundingVectors.push(maxPoint.clone());
  13881. this._boundingVectors[6].x = minPoint.x;
  13882. this._boundingVectors.push(maxPoint.clone());
  13883. this._boundingVectors[7].y = minPoint.y;
  13884. }
  13885. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  13886. get: function () {
  13887. return this._capacity;
  13888. },
  13889. enumerable: true,
  13890. configurable: true
  13891. });
  13892. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  13893. get: function () {
  13894. return this._minPoint;
  13895. },
  13896. enumerable: true,
  13897. configurable: true
  13898. });
  13899. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  13900. get: function () {
  13901. return this._maxPoint;
  13902. },
  13903. enumerable: true,
  13904. configurable: true
  13905. });
  13906. OctreeBlock.prototype.addEntry = function (entry) {
  13907. if (this.blocks) {
  13908. for (var index = 0; index < this.blocks.length; index++) {
  13909. var block = this.blocks[index];
  13910. block.addEntry(entry);
  13911. }
  13912. return;
  13913. }
  13914. this._creationFunc(entry, this);
  13915. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  13916. this.createInnerBlocks();
  13917. }
  13918. };
  13919. OctreeBlock.prototype.addEntries = function (entries) {
  13920. for (var index = 0; index < entries.length; index++) {
  13921. var mesh = entries[index];
  13922. this.addEntry(mesh);
  13923. }
  13924. };
  13925. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  13926. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  13927. if (this.blocks) {
  13928. for (var index = 0; index < this.blocks.length; index++) {
  13929. var block = this.blocks[index];
  13930. block.select(frustumPlanes, selection, allowDuplicate);
  13931. }
  13932. return;
  13933. }
  13934. if (allowDuplicate) {
  13935. selection.concat(this.entries);
  13936. } else {
  13937. selection.concatWithNoDuplicate(this.entries);
  13938. }
  13939. }
  13940. };
  13941. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  13942. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  13943. if (this.blocks) {
  13944. for (var index = 0; index < this.blocks.length; index++) {
  13945. var block = this.blocks[index];
  13946. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  13947. }
  13948. return;
  13949. }
  13950. if (allowDuplicate) {
  13951. selection.concat(this.entries);
  13952. } else {
  13953. selection.concatWithNoDuplicate(this.entries);
  13954. }
  13955. }
  13956. };
  13957. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  13958. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  13959. if (this.blocks) {
  13960. for (var index = 0; index < this.blocks.length; index++) {
  13961. var block = this.blocks[index];
  13962. block.intersectsRay(ray, selection);
  13963. }
  13964. return;
  13965. }
  13966. selection.concatWithNoDuplicate(this.entries);
  13967. }
  13968. };
  13969. OctreeBlock.prototype.createInnerBlocks = function () {
  13970. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  13971. };
  13972. return OctreeBlock;
  13973. })();
  13974. BABYLON.OctreeBlock = OctreeBlock;
  13975. })(BABYLON || (BABYLON = {}));
  13976. var BABYLON;
  13977. (function (BABYLON) {
  13978. var Bone = (function () {
  13979. function Bone(name, skeleton, parentBone, matrix) {
  13980. this.name = name;
  13981. this.children = new Array();
  13982. this.animations = new Array();
  13983. this._worldTransform = new BABYLON.Matrix();
  13984. this._absoluteTransform = new BABYLON.Matrix();
  13985. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  13986. this._skeleton = skeleton;
  13987. this._matrix = matrix;
  13988. this._baseMatrix = matrix;
  13989. skeleton.bones.push(this);
  13990. if (parentBone) {
  13991. this._parent = parentBone;
  13992. parentBone.children.push(this);
  13993. } else {
  13994. this._parent = null;
  13995. }
  13996. this._updateDifferenceMatrix();
  13997. }
  13998. Bone.prototype.getParent = function () {
  13999. return this._parent;
  14000. };
  14001. Bone.prototype.getLocalMatrix = function () {
  14002. return this._matrix;
  14003. };
  14004. Bone.prototype.getBaseMatrix = function () {
  14005. return this._baseMatrix;
  14006. };
  14007. Bone.prototype.getWorldMatrix = function () {
  14008. return this._worldTransform;
  14009. };
  14010. Bone.prototype.getInvertedAbsoluteTransform = function () {
  14011. return this._invertedAbsoluteTransform;
  14012. };
  14013. Bone.prototype.getAbsoluteMatrix = function () {
  14014. var matrix = this._matrix.clone();
  14015. var parent = this._parent;
  14016. while (parent) {
  14017. matrix = matrix.multiply(parent.getLocalMatrix());
  14018. parent = parent.getParent();
  14019. }
  14020. return matrix;
  14021. };
  14022. Bone.prototype.updateMatrix = function (matrix) {
  14023. this._matrix = matrix;
  14024. this._skeleton._markAsDirty();
  14025. this._updateDifferenceMatrix();
  14026. };
  14027. Bone.prototype._updateDifferenceMatrix = function () {
  14028. if (this._parent) {
  14029. this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  14030. } else {
  14031. this._absoluteTransform.copyFrom(this._matrix);
  14032. }
  14033. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  14034. for (var index = 0; index < this.children.length; index++) {
  14035. this.children[index]._updateDifferenceMatrix();
  14036. }
  14037. };
  14038. Bone.prototype.markAsDirty = function () {
  14039. this._skeleton._markAsDirty();
  14040. };
  14041. return Bone;
  14042. })();
  14043. BABYLON.Bone = Bone;
  14044. })(BABYLON || (BABYLON = {}));
  14045. var BABYLON;
  14046. (function (BABYLON) {
  14047. var Skeleton = (function () {
  14048. function Skeleton(name, id, scene) {
  14049. this.name = name;
  14050. this.id = id;
  14051. this.bones = new Array();
  14052. this._isDirty = true;
  14053. this._identity = BABYLON.Matrix.Identity();
  14054. this.bones = [];
  14055. this._scene = scene;
  14056. scene.skeletons.push(this);
  14057. }
  14058. Skeleton.prototype.getTransformMatrices = function () {
  14059. return this._transformMatrices;
  14060. };
  14061. Skeleton.prototype._markAsDirty = function () {
  14062. this._isDirty = true;
  14063. };
  14064. Skeleton.prototype.prepare = function () {
  14065. if (!this._isDirty) {
  14066. return;
  14067. }
  14068. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  14069. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  14070. }
  14071. for (var index = 0; index < this.bones.length; index++) {
  14072. var bone = this.bones[index];
  14073. var parentBone = bone.getParent();
  14074. if (parentBone) {
  14075. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  14076. } else {
  14077. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  14078. }
  14079. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), this._transformMatrices, index * 16);
  14080. }
  14081. this._identity.copyToArray(this._transformMatrices, this.bones.length * 16);
  14082. this._isDirty = false;
  14083. };
  14084. Skeleton.prototype.getAnimatables = function () {
  14085. if (!this._animatables || this._animatables.length != this.bones.length) {
  14086. this._animatables = [];
  14087. for (var index = 0; index < this.bones.length; index++) {
  14088. this._animatables.push(this.bones[index]);
  14089. }
  14090. }
  14091. return this._animatables;
  14092. };
  14093. Skeleton.prototype.clone = function (name, id) {
  14094. var result = new BABYLON.Skeleton(name, id || name, this._scene);
  14095. for (var index = 0; index < this.bones.length; index++) {
  14096. var source = this.bones[index];
  14097. var parentBone = null;
  14098. if (source.getParent()) {
  14099. var parentIndex = this.bones.indexOf(source.getParent());
  14100. parentBone = result.bones[parentIndex];
  14101. }
  14102. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix());
  14103. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  14104. }
  14105. return result;
  14106. };
  14107. return Skeleton;
  14108. })();
  14109. BABYLON.Skeleton = Skeleton;
  14110. })(BABYLON || (BABYLON = {}));
  14111. var BABYLON;
  14112. (function (BABYLON) {
  14113. var PostProcess = (function () {
  14114. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable) {
  14115. this.name = name;
  14116. this.width = -1;
  14117. this.height = -1;
  14118. this._reusable = false;
  14119. this._textures = new BABYLON.SmartArray(2);
  14120. this._currentRenderTextureInd = 0;
  14121. if (camera != null) {
  14122. this._camera = camera;
  14123. this._scene = camera.getScene();
  14124. camera.attachPostProcess(this);
  14125. this._engine = this._scene.getEngine();
  14126. } else {
  14127. this._engine = engine;
  14128. }
  14129. this._renderRatio = ratio;
  14130. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  14131. this._reusable = reusable || false;
  14132. samplers = samplers || [];
  14133. samplers.push("textureSampler");
  14134. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: fragmentUrl }, ["position"], parameters || [], samplers, "");
  14135. }
  14136. PostProcess.prototype.isReusable = function () {
  14137. return this._reusable;
  14138. };
  14139. PostProcess.prototype.activate = function (camera, sourceTexture) {
  14140. camera = camera || this._camera;
  14141. var scene = camera.getScene();
  14142. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  14143. var desiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  14144. var desiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  14145. desiredWidth = BABYLON.Tools.GetExponantOfTwo(desiredWidth, maxSize);
  14146. desiredHeight = BABYLON.Tools.GetExponantOfTwo(desiredHeight, maxSize);
  14147. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  14148. if (this._textures.length > 0) {
  14149. for (var i = 0; i < this._textures.length; i++) {
  14150. this._engine._releaseTexture(this._textures.data[i]);
  14151. }
  14152. this._textures.reset();
  14153. }
  14154. this.width = desiredWidth;
  14155. this.height = desiredHeight;
  14156. 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 }));
  14157. if (this._reusable) {
  14158. 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 }));
  14159. }
  14160. if (this.onSizeChanged) {
  14161. this.onSizeChanged();
  14162. }
  14163. }
  14164. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  14165. if (this.onActivate) {
  14166. this.onActivate(camera);
  14167. }
  14168. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  14169. if (this._reusable) {
  14170. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  14171. }
  14172. };
  14173. PostProcess.prototype.apply = function () {
  14174. if (!this._effect.isReady())
  14175. return null;
  14176. this._engine.enableEffect(this._effect);
  14177. this._engine.setState(false);
  14178. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  14179. this._engine.setDepthBuffer(false);
  14180. this._engine.setDepthWrite(false);
  14181. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  14182. if (this.onApply) {
  14183. this.onApply(this._effect);
  14184. }
  14185. return this._effect;
  14186. };
  14187. PostProcess.prototype.dispose = function (camera) {
  14188. camera = camera || this._camera;
  14189. if (this._textures.length > 0) {
  14190. for (var i = 0; i < this._textures.length; i++) {
  14191. this._engine._releaseTexture(this._textures.data[i]);
  14192. }
  14193. this._textures.reset();
  14194. }
  14195. camera.detachPostProcess(this);
  14196. var index = camera._postProcesses.indexOf(this);
  14197. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  14198. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1;
  14199. }
  14200. };
  14201. return PostProcess;
  14202. })();
  14203. BABYLON.PostProcess = PostProcess;
  14204. })(BABYLON || (BABYLON = {}));
  14205. var BABYLON;
  14206. (function (BABYLON) {
  14207. var PostProcessManager = (function () {
  14208. function PostProcessManager(scene) {
  14209. this._vertexDeclaration = [2];
  14210. this._vertexStrideSize = 2 * 4;
  14211. this._scene = scene;
  14212. var vertices = [];
  14213. vertices.push(1, 1);
  14214. vertices.push(-1, 1);
  14215. vertices.push(-1, -1);
  14216. vertices.push(1, -1);
  14217. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  14218. var indices = [];
  14219. indices.push(0);
  14220. indices.push(1);
  14221. indices.push(2);
  14222. indices.push(0);
  14223. indices.push(2);
  14224. indices.push(3);
  14225. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  14226. }
  14227. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  14228. var postProcesses = this._scene.activeCamera._postProcesses;
  14229. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  14230. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  14231. return false;
  14232. }
  14233. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  14234. return true;
  14235. };
  14236. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture) {
  14237. var postProcesses = this._scene.activeCamera._postProcesses;
  14238. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  14239. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  14240. return;
  14241. }
  14242. var engine = this._scene.getEngine();
  14243. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  14244. if (index < postProcessesTakenIndices.length - 1) {
  14245. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera);
  14246. } else {
  14247. if (targetTexture) {
  14248. engine.bindFramebuffer(targetTexture);
  14249. } else {
  14250. engine.restoreDefaultFramebuffer();
  14251. }
  14252. }
  14253. if (doNotPresent) {
  14254. break;
  14255. }
  14256. var pp = postProcesses[postProcessesTakenIndices[index]];
  14257. var effect = pp.apply();
  14258. if (effect) {
  14259. if (pp.onBeforeRender) {
  14260. pp.onBeforeRender(effect);
  14261. }
  14262. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  14263. engine.draw(true, 0, 6);
  14264. }
  14265. }
  14266. engine.setDepthBuffer(true);
  14267. engine.setDepthWrite(true);
  14268. };
  14269. PostProcessManager.prototype.dispose = function () {
  14270. if (this._vertexBuffer) {
  14271. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  14272. this._vertexBuffer = null;
  14273. }
  14274. if (this._indexBuffer) {
  14275. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  14276. this._indexBuffer = null;
  14277. }
  14278. };
  14279. return PostProcessManager;
  14280. })();
  14281. BABYLON.PostProcessManager = PostProcessManager;
  14282. })(BABYLON || (BABYLON = {}));
  14283. var __extends = this.__extends || function (d, b) {
  14284. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  14285. function __() { this.constructor = d; }
  14286. __.prototype = b.prototype;
  14287. d.prototype = new __();
  14288. };
  14289. var BABYLON;
  14290. (function (BABYLON) {
  14291. var PassPostProcess = (function (_super) {
  14292. __extends(PassPostProcess, _super);
  14293. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  14294. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  14295. }
  14296. return PassPostProcess;
  14297. })(BABYLON.PostProcess);
  14298. BABYLON.PassPostProcess = PassPostProcess;
  14299. })(BABYLON || (BABYLON = {}));
  14300. var __extends = this.__extends || function (d, b) {
  14301. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  14302. function __() { this.constructor = d; }
  14303. __.prototype = b.prototype;
  14304. d.prototype = new __();
  14305. };
  14306. var BABYLON;
  14307. (function (BABYLON) {
  14308. var BlurPostProcess = (function (_super) {
  14309. __extends(BlurPostProcess, _super);
  14310. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  14311. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  14312. var _this = this;
  14313. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  14314. this.direction = direction;
  14315. this.blurWidth = blurWidth;
  14316. this.onApply = function (effect) {
  14317. effect.setFloat2("screenSize", _this.width, _this.height);
  14318. effect.setVector2("direction", _this.direction);
  14319. effect.setFloat("blurWidth", _this.blurWidth);
  14320. };
  14321. }
  14322. return BlurPostProcess;
  14323. })(BABYLON.PostProcess);
  14324. BABYLON.BlurPostProcess = BlurPostProcess;
  14325. })(BABYLON || (BABYLON = {}));
  14326. var __extends = this.__extends || function (d, b) {
  14327. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  14328. function __() { this.constructor = d; }
  14329. __.prototype = b.prototype;
  14330. d.prototype = new __();
  14331. };
  14332. var BABYLON;
  14333. (function (BABYLON) {
  14334. var FilterPostProcess = (function (_super) {
  14335. __extends(FilterPostProcess, _super);
  14336. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  14337. var _this = this;
  14338. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  14339. this.kernelMatrix = kernelMatrix;
  14340. this.onApply = function (effect) {
  14341. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  14342. };
  14343. }
  14344. return FilterPostProcess;
  14345. })(BABYLON.PostProcess);
  14346. BABYLON.FilterPostProcess = FilterPostProcess;
  14347. })(BABYLON || (BABYLON = {}));
  14348. var __extends = this.__extends || function (d, b) {
  14349. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  14350. function __() { this.constructor = d; }
  14351. __.prototype = b.prototype;
  14352. d.prototype = new __();
  14353. };
  14354. var BABYLON;
  14355. (function (BABYLON) {
  14356. var RefractionPostProcess = (function (_super) {
  14357. __extends(RefractionPostProcess, _super);
  14358. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  14359. var _this = this;
  14360. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  14361. this.color = color;
  14362. this.depth = depth;
  14363. this.colorLevel = colorLevel;
  14364. this.onActivate = function (cam) {
  14365. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  14366. };
  14367. this.onApply = function (effect) {
  14368. effect.setColor3("baseColor", _this.color);
  14369. effect.setFloat("depth", _this.depth);
  14370. effect.setFloat("colorLevel", _this.colorLevel);
  14371. effect.setTexture("refractionSampler", _this._refRexture);
  14372. };
  14373. }
  14374. RefractionPostProcess.prototype.dispose = function (camera) {
  14375. if (this._refRexture) {
  14376. this._refRexture.dispose();
  14377. }
  14378. _super.prototype.dispose.call(this, camera);
  14379. };
  14380. return RefractionPostProcess;
  14381. })(BABYLON.PostProcess);
  14382. BABYLON.RefractionPostProcess = RefractionPostProcess;
  14383. })(BABYLON || (BABYLON = {}));
  14384. var __extends = this.__extends || function (d, b) {
  14385. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  14386. function __() { this.constructor = d; }
  14387. __.prototype = b.prototype;
  14388. d.prototype = new __();
  14389. };
  14390. var BABYLON;
  14391. (function (BABYLON) {
  14392. var BlackAndWhitePostProcess = (function (_super) {
  14393. __extends(BlackAndWhitePostProcess, _super);
  14394. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  14395. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  14396. }
  14397. return BlackAndWhitePostProcess;
  14398. })(BABYLON.PostProcess);
  14399. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  14400. })(BABYLON || (BABYLON = {}));
  14401. var __extends = this.__extends || function (d, b) {
  14402. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  14403. function __() { this.constructor = d; }
  14404. __.prototype = b.prototype;
  14405. d.prototype = new __();
  14406. };
  14407. var BABYLON;
  14408. (function (BABYLON) {
  14409. var ConvolutionPostProcess = (function (_super) {
  14410. __extends(ConvolutionPostProcess, _super);
  14411. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  14412. var _this = this;
  14413. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  14414. this.kernel = kernel;
  14415. this.onApply = function (effect) {
  14416. effect.setFloat2("screenSize", _this.width, _this.height);
  14417. effect.setArray("kernel", _this.kernel);
  14418. };
  14419. }
  14420. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  14421. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  14422. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  14423. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  14424. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  14425. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  14426. return ConvolutionPostProcess;
  14427. })(BABYLON.PostProcess);
  14428. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  14429. })(BABYLON || (BABYLON = {}));
  14430. var __extends = this.__extends || function (d, b) {
  14431. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  14432. function __() { this.constructor = d; }
  14433. __.prototype = b.prototype;
  14434. d.prototype = new __();
  14435. };
  14436. var BABYLON;
  14437. (function (BABYLON) {
  14438. var FxaaPostProcess = (function (_super) {
  14439. __extends(FxaaPostProcess, _super);
  14440. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  14441. var _this = this;
  14442. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  14443. this.onSizeChanged = function () {
  14444. _this.texelWidth = 1.0 / _this.width;
  14445. _this.texelHeight = 1.0 / _this.height;
  14446. };
  14447. this.onApply = function (effect) {
  14448. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  14449. };
  14450. }
  14451. return FxaaPostProcess;
  14452. })(BABYLON.PostProcess);
  14453. BABYLON.FxaaPostProcess = FxaaPostProcess;
  14454. })(BABYLON || (BABYLON = {}));
  14455. var BABYLON;
  14456. (function (BABYLON) {
  14457. var LensFlare = (function () {
  14458. function LensFlare(size, position, color, imgUrl, system) {
  14459. this.size = size;
  14460. this.position = position;
  14461. this.dispose = function () {
  14462. if (this.texture) {
  14463. this.texture.dispose();
  14464. }
  14465. var index = this._system.lensFlares.indexOf(this);
  14466. this._system.lensFlares.splice(index, 1);
  14467. };
  14468. this.color = color || new BABYLON.Color3(1, 1, 1);
  14469. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  14470. this._system = system;
  14471. system.lensFlares.push(this);
  14472. }
  14473. return LensFlare;
  14474. })();
  14475. BABYLON.LensFlare = LensFlare;
  14476. })(BABYLON || (BABYLON = {}));
  14477. var BABYLON;
  14478. (function (BABYLON) {
  14479. var LensFlareSystem = (function () {
  14480. function LensFlareSystem(name, emitter, scene) {
  14481. this.name = name;
  14482. this.lensFlares = new Array();
  14483. this.borderLimit = 300;
  14484. this._vertexDeclaration = [2];
  14485. this._vertexStrideSize = 2 * 4;
  14486. this._isEnabled = true;
  14487. this._scene = scene;
  14488. this._emitter = emitter;
  14489. scene.lensFlareSystems.push(this);
  14490. this.meshesSelectionPredicate = function (m) {
  14491. return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0);
  14492. };
  14493. var vertices = [];
  14494. vertices.push(1, 1);
  14495. vertices.push(-1, 1);
  14496. vertices.push(-1, -1);
  14497. vertices.push(1, -1);
  14498. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  14499. var indices = [];
  14500. indices.push(0);
  14501. indices.push(1);
  14502. indices.push(2);
  14503. indices.push(0);
  14504. indices.push(2);
  14505. indices.push(3);
  14506. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  14507. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  14508. }
  14509. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  14510. get: function () {
  14511. return this._isEnabled;
  14512. },
  14513. set: function (value) {
  14514. this._isEnabled = value;
  14515. },
  14516. enumerable: true,
  14517. configurable: true
  14518. });
  14519. LensFlareSystem.prototype.getScene = function () {
  14520. return this._scene;
  14521. };
  14522. LensFlareSystem.prototype.getEmitter = function () {
  14523. return this._emitter;
  14524. };
  14525. LensFlareSystem.prototype.getEmitterPosition = function () {
  14526. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  14527. };
  14528. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  14529. var position = this.getEmitterPosition();
  14530. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  14531. this._positionX = position.x;
  14532. this._positionY = position.y;
  14533. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  14534. if (position.z > 0) {
  14535. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  14536. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  14537. return true;
  14538. }
  14539. }
  14540. return false;
  14541. };
  14542. LensFlareSystem.prototype._isVisible = function () {
  14543. if (!this._isEnabled) {
  14544. return false;
  14545. }
  14546. var emitterPosition = this.getEmitterPosition();
  14547. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  14548. var distance = direction.length();
  14549. direction.normalize();
  14550. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  14551. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  14552. return !pickInfo.hit || pickInfo.distance > distance;
  14553. };
  14554. LensFlareSystem.prototype.render = function () {
  14555. if (!this._effect.isReady())
  14556. return false;
  14557. var engine = this._scene.getEngine();
  14558. var viewport = this._scene.activeCamera.viewport;
  14559. var globalViewport = viewport.toGlobal(engine);
  14560. if (!this.computeEffectivePosition(globalViewport)) {
  14561. return false;
  14562. }
  14563. if (!this._isVisible()) {
  14564. return false;
  14565. }
  14566. var awayX;
  14567. var awayY;
  14568. if (this._positionX < this.borderLimit + globalViewport.x) {
  14569. awayX = this.borderLimit + globalViewport.x - this._positionX;
  14570. } else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  14571. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  14572. } else {
  14573. awayX = 0;
  14574. }
  14575. if (this._positionY < this.borderLimit + globalViewport.y) {
  14576. awayY = this.borderLimit + globalViewport.y - this._positionY;
  14577. } else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  14578. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  14579. } else {
  14580. awayY = 0;
  14581. }
  14582. var away = (awayX > awayY) ? awayX : awayY;
  14583. if (away > this.borderLimit) {
  14584. away = this.borderLimit;
  14585. }
  14586. var intensity = 1.0 - (away / this.borderLimit);
  14587. if (intensity < 0) {
  14588. return false;
  14589. }
  14590. if (intensity > 1.0) {
  14591. intensity = 1.0;
  14592. }
  14593. var centerX = globalViewport.x + globalViewport.width / 2;
  14594. var centerY = globalViewport.y + globalViewport.height / 2;
  14595. var distX = centerX - this._positionX;
  14596. var distY = centerY - this._positionY;
  14597. engine.enableEffect(this._effect);
  14598. engine.setState(false);
  14599. engine.setDepthBuffer(false);
  14600. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  14601. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  14602. for (var index = 0; index < this.lensFlares.length; index++) {
  14603. var flare = this.lensFlares[index];
  14604. var x = centerX - (distX * flare.position);
  14605. var y = centerY - (distY * flare.position);
  14606. var cw = flare.size;
  14607. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera);
  14608. var cx = 2 * (x / globalViewport.width) - 1.0;
  14609. var cy = 1.0 - 2 * (y / globalViewport.height);
  14610. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  14611. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  14612. this._effect.setTexture("textureSampler", flare.texture);
  14613. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  14614. engine.draw(true, 0, 6);
  14615. }
  14616. engine.setDepthBuffer(true);
  14617. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  14618. return true;
  14619. };
  14620. LensFlareSystem.prototype.dispose = function () {
  14621. if (this._vertexBuffer) {
  14622. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  14623. this._vertexBuffer = null;
  14624. }
  14625. if (this._indexBuffer) {
  14626. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  14627. this._indexBuffer = null;
  14628. }
  14629. while (this.lensFlares.length) {
  14630. this.lensFlares[0].dispose();
  14631. }
  14632. var index = this._scene.lensFlareSystems.indexOf(this);
  14633. this._scene.lensFlareSystems.splice(index, 1);
  14634. };
  14635. return LensFlareSystem;
  14636. })();
  14637. BABYLON.LensFlareSystem = LensFlareSystem;
  14638. })(BABYLON || (BABYLON = {}));
  14639. var BABYLON;
  14640. (function (BABYLON) {
  14641. var IntersectionInfo = (function () {
  14642. function IntersectionInfo(bu, bv, distance) {
  14643. this.bu = bu;
  14644. this.bv = bv;
  14645. this.distance = distance;
  14646. this.faceId = 0;
  14647. }
  14648. return IntersectionInfo;
  14649. })();
  14650. BABYLON.IntersectionInfo = IntersectionInfo;
  14651. var PickingInfo = (function () {
  14652. function PickingInfo() {
  14653. this.hit = false;
  14654. this.distance = 0;
  14655. this.pickedPoint = null;
  14656. this.pickedMesh = null;
  14657. this.bu = 0;
  14658. this.bv = 0;
  14659. this.faceId = -1;
  14660. }
  14661. PickingInfo.prototype.getNormal = function () {
  14662. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  14663. return null;
  14664. }
  14665. var indices = this.pickedMesh.getIndices();
  14666. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14667. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  14668. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  14669. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  14670. normal0 = normal0.scale(this.bu);
  14671. normal1 = normal1.scale(this.bv);
  14672. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  14673. return new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  14674. };
  14675. PickingInfo.prototype.getTextureCoordinates = function () {
  14676. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  14677. return null;
  14678. }
  14679. var indices = this.pickedMesh.getIndices();
  14680. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  14681. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  14682. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  14683. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  14684. uv0 = uv0.scale(this.bu);
  14685. uv1 = uv1.scale(this.bv);
  14686. uv2 = uv2.scale(1.0 - this.bu - this.bv);
  14687. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  14688. };
  14689. return PickingInfo;
  14690. })();
  14691. BABYLON.PickingInfo = PickingInfo;
  14692. })(BABYLON || (BABYLON = {}));
  14693. var BABYLON;
  14694. (function (BABYLON) {
  14695. var FilesInput = (function () {
  14696. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  14697. this.engine = p_engine;
  14698. this.canvas = p_canvas;
  14699. this.currentScene = p_scene;
  14700. this.sceneLoadedCallback = p_sceneLoadedCallback;
  14701. this.progressCallback = p_progressCallback;
  14702. this.additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  14703. this.textureLoadingCallback = p_textureLoadingCallback;
  14704. this.startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  14705. }
  14706. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  14707. var _this = this;
  14708. if (p_elementToMonitor) {
  14709. this.elementToMonitor = p_elementToMonitor;
  14710. this.elementToMonitor.addEventListener("dragenter", function (e) {
  14711. _this.drag(e);
  14712. }, false);
  14713. this.elementToMonitor.addEventListener("dragover", function (e) {
  14714. _this.drag(e);
  14715. }, false);
  14716. this.elementToMonitor.addEventListener("drop", function (e) {
  14717. _this.drop(e);
  14718. }, false);
  14719. }
  14720. };
  14721. FilesInput.prototype.renderFunction = function () {
  14722. if (this.additionnalRenderLoopLogicCallback) {
  14723. this.additionnalRenderLoopLogicCallback();
  14724. }
  14725. if (this.currentScene) {
  14726. if (this.textureLoadingCallback) {
  14727. var remaining = this.currentScene.getWaitingItemsCount();
  14728. if (remaining > 0) {
  14729. this.textureLoadingCallback(remaining);
  14730. }
  14731. }
  14732. this.currentScene.render();
  14733. }
  14734. };
  14735. FilesInput.prototype.drag = function (e) {
  14736. e.stopPropagation();
  14737. e.preventDefault();
  14738. };
  14739. FilesInput.prototype.drop = function (eventDrop) {
  14740. eventDrop.stopPropagation();
  14741. eventDrop.preventDefault();
  14742. this.loadFiles(eventDrop);
  14743. };
  14744. FilesInput.prototype.loadFiles = function (event) {
  14745. var _this = this;
  14746. var that = this;
  14747. if (this.startingProcessingFilesCallback)
  14748. this.startingProcessingFilesCallback();
  14749. var sceneFileToLoad;
  14750. var filesToLoad;
  14751. if (event && event.dataTransfer && event.dataTransfer.files) {
  14752. filesToLoad = event.dataTransfer.files;
  14753. }
  14754. if (event && event.target && event.target.files) {
  14755. filesToLoad = event.target.files;
  14756. }
  14757. if (filesToLoad && filesToLoad.length > 0) {
  14758. for (var i = 0; i < filesToLoad.length; i++) {
  14759. switch (filesToLoad[i].type) {
  14760. case "image/jpeg":
  14761. case "image/png":
  14762. BABYLON.FilesInput.FilesTextures[filesToLoad[i].name] = filesToLoad[i];
  14763. break;
  14764. case "image/targa":
  14765. case "image/vnd.ms-dds":
  14766. BABYLON.FilesInput.FilesToLoad[filesToLoad[i].name] = filesToLoad[i];
  14767. break;
  14768. default:
  14769. 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) {
  14770. sceneFileToLoad = filesToLoad[i];
  14771. }
  14772. break;
  14773. }
  14774. }
  14775. if (sceneFileToLoad) {
  14776. if (this.currentScene) {
  14777. this.engine.stopRenderLoop();
  14778. this.currentScene.dispose();
  14779. }
  14780. BABYLON.SceneLoader.Load("file:", sceneFileToLoad, this.engine, function (newScene) {
  14781. that.currentScene = newScene;
  14782. that.currentScene.executeWhenReady(function () {
  14783. if (that.currentScene.activeCamera) {
  14784. that.currentScene.activeCamera.attachControl(that.canvas);
  14785. }
  14786. if (that.sceneLoadedCallback) {
  14787. that.sceneLoadedCallback(sceneFileToLoad, that.currentScene);
  14788. }
  14789. that.engine.runRenderLoop(function () {
  14790. that.renderFunction();
  14791. });
  14792. });
  14793. }, function (progress) {
  14794. if (_this.progressCallback) {
  14795. _this.progressCallback(progress);
  14796. }
  14797. });
  14798. } else {
  14799. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  14800. }
  14801. }
  14802. };
  14803. FilesInput.FilesTextures = new Array();
  14804. FilesInput.FilesToLoad = new Array();
  14805. return FilesInput;
  14806. })();
  14807. BABYLON.FilesInput = FilesInput;
  14808. })(BABYLON || (BABYLON = {}));
  14809. var BABYLON;
  14810. (function (BABYLON) {
  14811. var OimoJSPlugin = (function () {
  14812. function OimoJSPlugin() {
  14813. this._registeredMeshes = [];
  14814. /**
  14815. * Update the body position according to the mesh position
  14816. * @param mesh
  14817. */
  14818. this.updateBodyPosition = function (mesh) {
  14819. for (var index = 0; index < this._registeredMeshes.length; index++) {
  14820. var registeredMesh = this._registeredMeshes[index];
  14821. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  14822. var body = registeredMesh.body.body;
  14823. mesh.computeWorldMatrix(true);
  14824. var center = mesh.getBoundingInfo().boundingBox.center;
  14825. body.setPosition(center.x, center.y, center.z);
  14826. body.setOrientation(mesh.rotation.x, mesh.rotation.y, mesh.rotation.z);
  14827. return;
  14828. }
  14829. if (registeredMesh.mesh.parent === mesh) {
  14830. mesh.computeWorldMatrix(true);
  14831. registeredMesh.mesh.computeWorldMatrix(true);
  14832. var absolutePosition = registeredMesh.mesh.getAbsolutePosition();
  14833. var absoluteRotation = mesh.rotation;
  14834. body = registeredMesh.body.body;
  14835. body.setPosition(absolutePosition.x, absolutePosition.y, absolutePosition.z);
  14836. body.setOrientation(absoluteRotation.x, absoluteRotation.y, absoluteRotation.z);
  14837. return;
  14838. }
  14839. }
  14840. };
  14841. }
  14842. OimoJSPlugin.prototype._checkWithEpsilon = function (value) {
  14843. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  14844. };
  14845. OimoJSPlugin.prototype.initialize = function (iterations) {
  14846. this._world = new OIMO.World();
  14847. this._world.clear();
  14848. };
  14849. OimoJSPlugin.prototype.setGravity = function (gravity) {
  14850. this._world.gravity = gravity;
  14851. };
  14852. OimoJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  14853. var body = null;
  14854. this.unregisterMesh(mesh);
  14855. mesh.computeWorldMatrix(true);
  14856. switch (impostor) {
  14857. case BABYLON.PhysicsEngine.SphereImpostor:
  14858. var bbox = mesh.getBoundingInfo().boundingBox;
  14859. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  14860. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  14861. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  14862. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  14863. var deltaPosition = mesh.position.subtract(bbox.center);
  14864. body = new OIMO.Body({
  14865. type: 'sphere',
  14866. size: [size],
  14867. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  14868. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  14869. move: options.mass != 0,
  14870. config: [options.mass, options.friction, options.restitution],
  14871. world: this._world
  14872. });
  14873. this._registeredMeshes.push({
  14874. mesh: mesh,
  14875. body: body,
  14876. delta: deltaPosition
  14877. });
  14878. break;
  14879. case BABYLON.PhysicsEngine.PlaneImpostor:
  14880. case BABYLON.PhysicsEngine.BoxImpostor:
  14881. bbox = mesh.getBoundingInfo().boundingBox;
  14882. var min = bbox.minimumWorld;
  14883. var max = bbox.maximumWorld;
  14884. var box = max.subtract(min);
  14885. var sizeX = this._checkWithEpsilon(box.x);
  14886. var sizeY = this._checkWithEpsilon(box.y);
  14887. var sizeZ = this._checkWithEpsilon(box.z);
  14888. var deltaPosition = mesh.position.subtract(bbox.center);
  14889. body = new OIMO.Body({
  14890. type: 'box',
  14891. size: [sizeX, sizeY, sizeZ],
  14892. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  14893. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  14894. move: options.mass != 0,
  14895. config: [options.mass, options.friction, options.restitution],
  14896. world: this._world
  14897. });
  14898. this._registeredMeshes.push({
  14899. mesh: mesh,
  14900. body: body,
  14901. delta: deltaPosition
  14902. });
  14903. break;
  14904. }
  14905. return body;
  14906. };
  14907. OimoJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  14908. var types = [], sizes = [], positions = [], rotations = [];
  14909. var initialMesh = parts[0].mesh;
  14910. for (var index = 0; index < parts.length; index++) {
  14911. var part = parts[index];
  14912. var bodyParameters = this._createBodyAsCompound(part, options, initialMesh);
  14913. types.push(bodyParameters.type);
  14914. sizes.push.apply(sizes, bodyParameters.size);
  14915. positions.push.apply(positions, bodyParameters.pos);
  14916. rotations.push.apply(rotations, bodyParameters.rot);
  14917. }
  14918. var body = new OIMO.Body({
  14919. type: types,
  14920. size: sizes,
  14921. pos: positions,
  14922. rot: rotations,
  14923. move: options.mass != 0,
  14924. config: [options.mass, options.friction, options.restitution],
  14925. world: this._world
  14926. });
  14927. this._registeredMeshes.push({
  14928. mesh: initialMesh,
  14929. body: body
  14930. });
  14931. return body;
  14932. };
  14933. OimoJSPlugin.prototype._createBodyAsCompound = function (part, options, initialMesh) {
  14934. var bodyParameters = null;
  14935. var mesh = part.mesh;
  14936. switch (part.impostor) {
  14937. case BABYLON.PhysicsEngine.SphereImpostor:
  14938. var bbox = mesh.getBoundingInfo().boundingBox;
  14939. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  14940. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  14941. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  14942. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  14943. bodyParameters = {
  14944. type: 'sphere',
  14945. /* bug with oimo : sphere needs 3 sizes in this case */
  14946. size: [size, -1, -1],
  14947. pos: [mesh.position.x, mesh.position.y, mesh.position.z],
  14948. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  14949. };
  14950. break;
  14951. case BABYLON.PhysicsEngine.PlaneImpostor:
  14952. case BABYLON.PhysicsEngine.BoxImpostor:
  14953. bbox = mesh.getBoundingInfo().boundingBox;
  14954. var min = bbox.minimumWorld;
  14955. var max = bbox.maximumWorld;
  14956. var box = max.subtract(min);
  14957. var sizeX = this._checkWithEpsilon(box.x);
  14958. var sizeY = this._checkWithEpsilon(box.y);
  14959. var sizeZ = this._checkWithEpsilon(box.z);
  14960. var relativePosition = mesh.position;
  14961. bodyParameters = {
  14962. type: 'box',
  14963. size: [sizeX, sizeY, sizeZ],
  14964. pos: [relativePosition.x, relativePosition.y, relativePosition.z],
  14965. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  14966. };
  14967. break;
  14968. }
  14969. return bodyParameters;
  14970. };
  14971. OimoJSPlugin.prototype.unregisterMesh = function (mesh) {
  14972. for (var index = 0; index < this._registeredMeshes.length; index++) {
  14973. var registeredMesh = this._registeredMeshes[index];
  14974. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  14975. if (registeredMesh.body) {
  14976. this._world.removeRigidBody(registeredMesh.body.body);
  14977. this._unbindBody(registeredMesh.body);
  14978. }
  14979. this._registeredMeshes.splice(index, 1);
  14980. return;
  14981. }
  14982. }
  14983. };
  14984. OimoJSPlugin.prototype._unbindBody = function (body) {
  14985. for (var index = 0; index < this._registeredMeshes.length; index++) {
  14986. var registeredMesh = this._registeredMeshes[index];
  14987. if (registeredMesh.body === body) {
  14988. registeredMesh.body = null;
  14989. }
  14990. }
  14991. };
  14992. OimoJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  14993. for (var index = 0; index < this._registeredMeshes.length; index++) {
  14994. var registeredMesh = this._registeredMeshes[index];
  14995. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  14996. var mass = registeredMesh.body.body.massInfo.mass;
  14997. registeredMesh.body.body.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  14998. return;
  14999. }
  15000. }
  15001. };
  15002. OimoJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  15003. var body1 = null, body2 = null;
  15004. for (var index = 0; index < this._registeredMeshes.length; index++) {
  15005. var registeredMesh = this._registeredMeshes[index];
  15006. if (registeredMesh.mesh === mesh1) {
  15007. body1 = registeredMesh.body.body;
  15008. } else if (registeredMesh.mesh === mesh2) {
  15009. body2 = registeredMesh.body.body;
  15010. }
  15011. }
  15012. if (!body1 || !body2) {
  15013. return false;
  15014. }
  15015. if (!options) {
  15016. options = {};
  15017. }
  15018. new OIMO.Link({
  15019. type: options.type,
  15020. body1: body1,
  15021. body2: body2,
  15022. min: options.min,
  15023. max: options.max,
  15024. axe1: options.axe1,
  15025. axe2: options.axe2,
  15026. pos1: [pivot1.x, pivot1.y, pivot1.z],
  15027. pos2: [pivot2.x, pivot2.y, pivot2.z],
  15028. collision: options.collision,
  15029. spring: options.spring,
  15030. world: this._world
  15031. });
  15032. return true;
  15033. };
  15034. OimoJSPlugin.prototype.dispose = function () {
  15035. this._world.clear();
  15036. while (this._registeredMeshes.length) {
  15037. this.unregisterMesh(this._registeredMeshes[0].mesh);
  15038. }
  15039. };
  15040. OimoJSPlugin.prototype.isSupported = function () {
  15041. return OIMO !== undefined;
  15042. };
  15043. OimoJSPlugin.prototype._getLastShape = function (body) {
  15044. var lastShape = body.shapes;
  15045. while (lastShape.next) {
  15046. lastShape = lastShape.next;
  15047. }
  15048. return lastShape;
  15049. };
  15050. OimoJSPlugin.prototype.runOneStep = function (time) {
  15051. this._world.step();
  15052. var i = this._registeredMeshes.length;
  15053. var m;
  15054. while (i--) {
  15055. var body = this._registeredMeshes[i].body.body;
  15056. var mesh = this._registeredMeshes[i].mesh;
  15057. var delta = this._registeredMeshes[i].delta;
  15058. if (!body.sleeping) {
  15059. if (body.shapes.next) {
  15060. var parentShape = this._getLastShape(body);
  15061. mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  15062. mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  15063. mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  15064. var mtx = BABYLON.Matrix.FromArray(body.getMatrix());
  15065. if (!mesh.rotationQuaternion) {
  15066. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  15067. }
  15068. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  15069. mesh.computeWorldMatrix();
  15070. } else {
  15071. m = body.getMatrix();
  15072. mtx = BABYLON.Matrix.FromArray(m);
  15073. var bodyX = mtx.m[12], bodyY = mtx.m[13], bodyZ = mtx.m[14];
  15074. if (!delta) {
  15075. mesh.position.x = bodyX;
  15076. mesh.position.y = bodyY;
  15077. mesh.position.z = bodyZ;
  15078. } else {
  15079. mesh.position.x = bodyX + delta.x;
  15080. mesh.position.y = bodyY + delta.y;
  15081. mesh.position.z = bodyZ + delta.z;
  15082. }
  15083. if (!mesh.rotationQuaternion) {
  15084. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  15085. }
  15086. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  15087. mesh.computeWorldMatrix();
  15088. }
  15089. }
  15090. }
  15091. };
  15092. return OimoJSPlugin;
  15093. })();
  15094. BABYLON.OimoJSPlugin = OimoJSPlugin;
  15095. })(BABYLON || (BABYLON = {}));
  15096. var BABYLON;
  15097. (function (BABYLON) {
  15098. var PhysicsEngine = (function () {
  15099. function PhysicsEngine(plugin) {
  15100. this._currentPlugin = plugin || new BABYLON.OimoJSPlugin();
  15101. }
  15102. PhysicsEngine.prototype._initialize = function (gravity) {
  15103. this._currentPlugin.initialize();
  15104. this._setGravity(gravity);
  15105. };
  15106. PhysicsEngine.prototype._runOneStep = function (delta) {
  15107. if (delta > 0.1) {
  15108. delta = 0.1;
  15109. } else if (delta <= 0) {
  15110. delta = 1.0 / 60.0;
  15111. }
  15112. this._currentPlugin.runOneStep(delta);
  15113. };
  15114. PhysicsEngine.prototype._setGravity = function (gravity) {
  15115. this.gravity = gravity || new BABYLON.Vector3(0, -9.82, 0);
  15116. this._currentPlugin.setGravity(this.gravity);
  15117. };
  15118. PhysicsEngine.prototype._registerMesh = function (mesh, impostor, options) {
  15119. return this._currentPlugin.registerMesh(mesh, impostor, options);
  15120. };
  15121. PhysicsEngine.prototype._registerMeshesAsCompound = function (parts, options) {
  15122. return this._currentPlugin.registerMeshesAsCompound(parts, options);
  15123. };
  15124. PhysicsEngine.prototype._unregisterMesh = function (mesh) {
  15125. this._currentPlugin.unregisterMesh(mesh);
  15126. };
  15127. PhysicsEngine.prototype._applyImpulse = function (mesh, force, contactPoint) {
  15128. this._currentPlugin.applyImpulse(mesh, force, contactPoint);
  15129. };
  15130. PhysicsEngine.prototype._createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  15131. return this._currentPlugin.createLink(mesh1, mesh2, pivot1, pivot2, options);
  15132. };
  15133. PhysicsEngine.prototype._updateBodyPosition = function (mesh) {
  15134. this._currentPlugin.updateBodyPosition(mesh);
  15135. };
  15136. PhysicsEngine.prototype.dispose = function () {
  15137. this._currentPlugin.dispose();
  15138. };
  15139. PhysicsEngine.prototype.isSupported = function () {
  15140. return this._currentPlugin.isSupported();
  15141. };
  15142. PhysicsEngine.NoImpostor = 0;
  15143. PhysicsEngine.SphereImpostor = 1;
  15144. PhysicsEngine.BoxImpostor = 2;
  15145. PhysicsEngine.PlaneImpostor = 3;
  15146. PhysicsEngine.MeshImpostor = 4;
  15147. PhysicsEngine.CapsuleImpostor = 5;
  15148. PhysicsEngine.ConeImpostor = 6;
  15149. PhysicsEngine.CylinderImpostor = 7;
  15150. PhysicsEngine.ConvexHullImpostor = 8;
  15151. PhysicsEngine.Epsilon = 0.001;
  15152. return PhysicsEngine;
  15153. })();
  15154. BABYLON.PhysicsEngine = PhysicsEngine;
  15155. })(BABYLON || (BABYLON = {}));
  15156. var BABYLON;
  15157. (function (BABYLON) {
  15158. var serializeLight = function (light) {
  15159. var serializationObject = {};
  15160. serializationObject.name = light.name;
  15161. serializationObject.id = light.id;
  15162. serializationObject.tags = BABYLON.Tags.GetTags(light);
  15163. if (light instanceof BABYLON.PointLight) {
  15164. serializationObject.type = 0;
  15165. serializationObject.position = light.position.asArray();
  15166. } else if (light instanceof BABYLON.DirectionalLight) {
  15167. serializationObject.type = 1;
  15168. var directionalLight = light;
  15169. serializationObject.position = directionalLight.position.asArray();
  15170. serializationObject.direction = directionalLight.direction.asArray();
  15171. } else if (light instanceof BABYLON.SpotLight) {
  15172. serializationObject.type = 2;
  15173. var spotLight = light;
  15174. serializationObject.position = spotLight.position.asArray();
  15175. serializationObject.direction = spotLight.position.asArray();
  15176. serializationObject.angle = spotLight.angle;
  15177. serializationObject.exponent = spotLight.exponent;
  15178. } else if (light instanceof BABYLON.HemisphericLight) {
  15179. serializationObject.type = 3;
  15180. var hemisphericLight = light;
  15181. serializationObject.direction = hemisphericLight.direction.asArray();
  15182. serializationObject.groundColor = hemisphericLight.groundColor.asArray();
  15183. }
  15184. if (light.intensity) {
  15185. serializationObject.intensity = light.intensity;
  15186. }
  15187. serializationObject.range = light.range;
  15188. serializationObject.diffuse = light.diffuse.asArray();
  15189. serializationObject.specular = light.specular.asArray();
  15190. return serializationObject;
  15191. };
  15192. var serializeFresnelParameter = function (fresnelParameter) {
  15193. var serializationObject = {};
  15194. serializationObject.isEnabled = fresnelParameter.isEnabled;
  15195. serializationObject.leftColor = fresnelParameter.leftColor;
  15196. serializationObject.rightColor = fresnelParameter.rightColor;
  15197. serializationObject.bias = fresnelParameter.bias;
  15198. serializationObject.power = fresnelParameter.power;
  15199. return serializationObject;
  15200. };
  15201. var serializeCamera = function (camera) {
  15202. var serializationObject = {};
  15203. serializationObject.name = camera.name;
  15204. serializationObject.tags = BABYLON.Tags.GetTags(camera);
  15205. serializationObject.id = camera.id;
  15206. serializationObject.position = camera.position.asArray();
  15207. if (camera.parent) {
  15208. serializationObject.parentId = camera.parent.id;
  15209. }
  15210. serializationObject.rotation = camera.rotation.asArray();
  15211. if (camera.lockedTarget && camera.lockedTarget.id) {
  15212. serializationObject.lockedTargetId = camera.lockedTarget.id;
  15213. }
  15214. serializationObject.fov = camera.fov;
  15215. serializationObject.minZ = camera.minZ;
  15216. serializationObject.maxZ = camera.maxZ;
  15217. serializationObject.speed = camera.speed;
  15218. serializationObject.inertia = camera.inertia;
  15219. serializationObject.checkCollisions = camera.checkCollisions;
  15220. serializationObject.applyGravity = camera.applyGravity;
  15221. if (camera.ellipsoid) {
  15222. serializationObject.ellipsoid = camera.ellipsoid.asArray();
  15223. }
  15224. appendAnimations(camera, serializationObject);
  15225. serializationObject.layerMask = camera.layerMask;
  15226. return serializationObject;
  15227. };
  15228. var appendAnimations = function (source, destination) {
  15229. if (source.animations) {
  15230. destination.animations = [];
  15231. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  15232. var animation = source.animations[animationIndex];
  15233. destination.animations.push(serializeAnimation(animation));
  15234. }
  15235. }
  15236. };
  15237. var serializeAnimation = function (animation) {
  15238. var serializationObject = {};
  15239. serializationObject.name = animation.name;
  15240. serializationObject.property = animation.targetProperty;
  15241. serializationObject.framePerSecond = animation.framePerSecond;
  15242. serializationObject.dataType = animation.dataType;
  15243. serializationObject.loopBehavior = animation.loopMode;
  15244. var dataType = animation.dataType;
  15245. serializationObject.keys = [];
  15246. var keys = animation.getKeys();
  15247. for (var index = 0; index < keys.length; index++) {
  15248. var animationKey = keys[index];
  15249. var key = {};
  15250. key.frame = animationKey.frame;
  15251. switch (dataType) {
  15252. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  15253. key.values = [animationKey.value];
  15254. break;
  15255. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  15256. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  15257. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  15258. key.values = animationKey.value.asArray();
  15259. break;
  15260. }
  15261. serializationObject.keys.push(key);
  15262. }
  15263. return serializationObject;
  15264. };
  15265. var serializeMultiMaterial = function (material) {
  15266. var serializationObject = {};
  15267. serializationObject.name = material.name;
  15268. serializationObject.id = material.id;
  15269. serializationObject.tags = BABYLON.Tags.GetTags(material);
  15270. serializationObject.materials = [];
  15271. for (var matIndex = 0; matIndex < material.subMaterials.length; matIndex++) {
  15272. var subMat = material.subMaterials[matIndex];
  15273. if (subMat) {
  15274. serializationObject.materials.push(subMat.id);
  15275. } else {
  15276. serializationObject.materials.push(null);
  15277. }
  15278. }
  15279. return serializationObject;
  15280. };
  15281. var serializeMaterial = function (material) {
  15282. var serializationObject = {};
  15283. serializationObject.name = material.name;
  15284. serializationObject.ambient = material.ambientColor.asArray();
  15285. serializationObject.diffuse = material.diffuseColor.asArray();
  15286. serializationObject.specular = material.specularColor.asArray();
  15287. serializationObject.specularPower = material.specularPower;
  15288. serializationObject.emissive = material.emissiveColor.asArray();
  15289. serializationObject.alpha = material.alpha;
  15290. serializationObject.id = material.id;
  15291. serializationObject.tags = BABYLON.Tags.GetTags(material);
  15292. serializationObject.backFaceCulling = material.backFaceCulling;
  15293. if (material.diffuseTexture) {
  15294. serializationObject.diffuseTexture = serializeTexture(material.diffuseTexture);
  15295. }
  15296. if (material.diffuseFresnelParameters) {
  15297. serializationObject.diffuseFresnelParameters = serializeFresnelParameter(material.diffuseFresnelParameters);
  15298. }
  15299. if (material.ambientTexture) {
  15300. serializationObject.ambientTexture = serializeTexture(material.ambientTexture);
  15301. }
  15302. if (material.opacityTexture) {
  15303. serializationObject.opacityTexture = serializeTexture(material.opacityTexture);
  15304. }
  15305. if (material.opacityFresnelParameters) {
  15306. serializationObject.opacityFresnelParameters = serializeFresnelParameter(material.opacityFresnelParameters);
  15307. }
  15308. if (material.reflectionTexture) {
  15309. serializationObject.reflectionTexture = serializeTexture(material.reflectionTexture);
  15310. }
  15311. if (material.reflectionFresnelParameters) {
  15312. serializationObject.reflectionFresnelParameters = serializeFresnelParameter(material.reflectionFresnelParameters);
  15313. }
  15314. if (material.emissiveTexture) {
  15315. serializationObject.emissiveTexture = serializeTexture(material.emissiveTexture);
  15316. }
  15317. if (material.emissiveFresnelParameters) {
  15318. serializationObject.emissiveFresnelParameters = serializeFresnelParameter(material.emissiveFresnelParameters);
  15319. }
  15320. if (material.specularTexture) {
  15321. serializationObject.specularTexture = serializeTexture(material.specularTexture);
  15322. }
  15323. if (material.bumpTexture) {
  15324. serializationObject.bumpTexture = serializeTexture(material.bumpTexture);
  15325. }
  15326. return serializationObject;
  15327. };
  15328. var serializeTexture = function (texture) {
  15329. var serializationObject = {};
  15330. if (!texture.name) {
  15331. return null;
  15332. }
  15333. if (texture instanceof BABYLON.CubeTexture) {
  15334. serializationObject.name = texture.name;
  15335. serializationObject.hasAlpha = texture.hasAlpha;
  15336. serializationObject.level = texture.level;
  15337. serializationObject.coordinatesMode = texture.coordinatesMode;
  15338. return serializationObject;
  15339. }
  15340. if (texture instanceof BABYLON.MirrorTexture) {
  15341. var mirrorTexture = texture;
  15342. serializationObject.renderTargetSize = mirrorTexture.getRenderSize();
  15343. serializationObject.renderList = [];
  15344. for (var index = 0; index < mirrorTexture.renderList.length; index++) {
  15345. serializationObject.renderList.push(mirrorTexture.renderList[index].id);
  15346. }
  15347. serializationObject.mirrorPlane = mirrorTexture.mirrorPlane.asArray();
  15348. } else if (texture instanceof BABYLON.RenderTargetTexture) {
  15349. var renderTargetTexture = texture;
  15350. serializationObject.renderTargetSize = renderTargetTexture.getRenderSize();
  15351. serializationObject.renderList = [];
  15352. for (index = 0; index < renderTargetTexture.renderList.length; index++) {
  15353. serializationObject.renderList.push(renderTargetTexture.renderList[index].id);
  15354. }
  15355. }
  15356. var regularTexture = texture;
  15357. serializationObject.name = texture.name;
  15358. serializationObject.hasAlpha = texture.hasAlpha;
  15359. serializationObject.level = texture.level;
  15360. serializationObject.coordinatesIndex = texture.coordinatesIndex;
  15361. serializationObject.coordinatesMode = texture.coordinatesMode;
  15362. serializationObject.uOffset = regularTexture.uOffset;
  15363. serializationObject.vOffset = regularTexture.vOffset;
  15364. serializationObject.uScale = regularTexture.uScale;
  15365. serializationObject.vScale = regularTexture.vScale;
  15366. serializationObject.uAng = regularTexture.uAng;
  15367. serializationObject.vAng = regularTexture.vAng;
  15368. serializationObject.wAng = regularTexture.wAng;
  15369. serializationObject.wrapU = texture.wrapU;
  15370. serializationObject.wrapV = texture.wrapV;
  15371. appendAnimations(texture, serializationObject);
  15372. return serializationObject;
  15373. };
  15374. var serializeSkeleton = function (skeleton) {
  15375. var serializationObject = {};
  15376. serializationObject.name = skeleton.name;
  15377. serializationObject.id = skeleton.id;
  15378. serializationObject.bones = [];
  15379. for (var index = 0; index < skeleton.bones.length; index++) {
  15380. var bone = skeleton.bones[index];
  15381. var serializedBone = {
  15382. parentBoneIndex: bone.getParent() ? skeleton.bones.indexOf(bone.getParent()) : -1,
  15383. name: bone.name,
  15384. matrix: bone.getLocalMatrix().toArray()
  15385. };
  15386. serializationObject.bones.push(serializedBone);
  15387. if (bone.animations && bone.animations.length > 0) {
  15388. serializedBone.animation = serializeAnimation(bone.animations[0]);
  15389. }
  15390. }
  15391. return serializationObject;
  15392. };
  15393. var serializeParticleSystem = function (particleSystem) {
  15394. var serializationObject = {};
  15395. serializationObject.emitterId = particleSystem.emitter.id;
  15396. serializationObject.capacity = particleSystem.getCapacity();
  15397. if (particleSystem.particleTexture) {
  15398. serializationObject.textureName = particleSystem.particleTexture.name;
  15399. }
  15400. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  15401. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  15402. serializationObject.minSize = particleSystem.minSize;
  15403. serializationObject.maxSize = particleSystem.maxSize;
  15404. serializationObject.minLifeTime = particleSystem.minLifeTime;
  15405. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  15406. serializationObject.emitRate = particleSystem.emitRate;
  15407. serializationObject.minEmitBox = particleSystem.minEmitBox.asArray();
  15408. serializationObject.maxEmitBox = particleSystem.maxEmitBox.asArray();
  15409. serializationObject.gravity = particleSystem.gravity.asArray();
  15410. serializationObject.direction1 = particleSystem.direction1.asArray();
  15411. serializationObject.direction2 = particleSystem.direction2.asArray();
  15412. serializationObject.color1 = particleSystem.color1.asArray();
  15413. serializationObject.color2 = particleSystem.color2.asArray();
  15414. serializationObject.colorDead = particleSystem.colorDead.asArray();
  15415. serializationObject.updateSpeed = particleSystem.updateSpeed;
  15416. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  15417. serializationObject.textureMask = particleSystem.textureMask.asArray();
  15418. serializationObject.blendMode = particleSystem.blendMode;
  15419. return serializationObject;
  15420. };
  15421. var serializeLensFlareSystem = function (lensFlareSystem) {
  15422. var serializationObject = {};
  15423. serializationObject.emitterId = lensFlareSystem.getEmitter().id;
  15424. serializationObject.borderLimit = lensFlareSystem.borderLimit;
  15425. serializationObject.flares = [];
  15426. for (var index = 0; index < lensFlareSystem.lensFlares.length; index++) {
  15427. var flare = lensFlareSystem.lensFlares[index];
  15428. serializationObject.flares.push({
  15429. size: flare.size,
  15430. position: flare.position,
  15431. color: flare.color.asArray(),
  15432. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  15433. });
  15434. }
  15435. return serializationObject;
  15436. };
  15437. var serializeShadowGenerator = function (light) {
  15438. var serializationObject = {};
  15439. var shadowGenerator = light.getShadowGenerator();
  15440. serializationObject.lightId = light.id;
  15441. serializationObject.mapSize = shadowGenerator.getShadowMap().getRenderSize();
  15442. serializationObject.useVarianceShadowMap = shadowGenerator.useVarianceShadowMap;
  15443. serializationObject.usePoissonSampling = shadowGenerator.usePoissonSampling;
  15444. serializationObject.renderList = [];
  15445. for (var meshIndex = 0; meshIndex < shadowGenerator.getShadowMap().renderList.length; meshIndex++) {
  15446. var mesh = shadowGenerator.getShadowMap().renderList[meshIndex];
  15447. serializationObject.renderList.push(mesh.id);
  15448. }
  15449. return serializationObject;
  15450. };
  15451. var serializedGeometries = [];
  15452. var serializeGeometry = function (geometry, serializationGeometries) {
  15453. if (serializedGeometries[geometry.id]) {
  15454. return;
  15455. }
  15456. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  15457. serializationGeometries.boxes.push(serializeBox(geometry));
  15458. } else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  15459. serializationGeometries.spheres.push(serializeSphere(geometry));
  15460. } else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  15461. serializationGeometries.cylinders.push(serializeCylinder(geometry));
  15462. } else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  15463. serializationGeometries.toruses.push(serializeTorus(geometry));
  15464. } else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  15465. serializationGeometries.grounds.push(serializeGround(geometry));
  15466. } else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  15467. serializationGeometries.planes.push(serializePlane(geometry));
  15468. } else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  15469. serializationGeometries.torusKnots.push(serializeTorusKnot(geometry));
  15470. } else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  15471. throw new Error("Unknow primitive type");
  15472. } else {
  15473. serializationGeometries.vertexData.push(serializeVertexData(geometry));
  15474. }
  15475. serializedGeometries[geometry.id] = true;
  15476. };
  15477. var serializeGeometryBase = function (geometry) {
  15478. var serializationObject = {};
  15479. serializationObject.id = geometry.id;
  15480. if (BABYLON.Tags.HasTags(geometry)) {
  15481. serializationObject.tags = BABYLON.Tags.GetTags(geometry);
  15482. }
  15483. return serializationObject;
  15484. };
  15485. var serializeVertexData = function (vertexData) {
  15486. var serializationObject = serializeGeometryBase(vertexData);
  15487. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  15488. serializationObject.positions = vertexData.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15489. }
  15490. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  15491. serializationObject.normals = vertexData.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15492. }
  15493. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  15494. serializationObject.uvs = vertexData.getVerticesData(BABYLON.VertexBuffer.UVKind);
  15495. }
  15496. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  15497. serializationObject.uvs2 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  15498. }
  15499. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  15500. serializationObject.colors = vertexData.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  15501. }
  15502. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  15503. serializationObject.matricesIndices = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  15504. serializationObject.matricesIndices._isExpanded = true;
  15505. }
  15506. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  15507. serializationObject.matricesWeights = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  15508. }
  15509. serializationObject.indices = vertexData.getIndices();
  15510. return serializationObject;
  15511. };
  15512. var serializePrimitive = function (primitive) {
  15513. var serializationObject = serializeGeometryBase(primitive);
  15514. serializationObject.canBeRegenerated = primitive.canBeRegenerated();
  15515. return serializationObject;
  15516. };
  15517. var serializeBox = function (box) {
  15518. var serializationObject = serializePrimitive(box);
  15519. serializationObject.size = box.size;
  15520. return serializationObject;
  15521. };
  15522. var serializeSphere = function (sphere) {
  15523. var serializationObject = serializePrimitive(sphere);
  15524. serializationObject.segments = sphere.segments;
  15525. serializationObject.diameter = sphere.diameter;
  15526. return serializationObject;
  15527. };
  15528. var serializeCylinder = function (cylinder) {
  15529. var serializationObject = serializePrimitive(cylinder);
  15530. serializationObject.height = cylinder.height;
  15531. serializationObject.diameterTop = cylinder.diameterTop;
  15532. serializationObject.diameterBottom = cylinder.diameterBottom;
  15533. serializationObject.tessellation = cylinder.tessellation;
  15534. return serializationObject;
  15535. };
  15536. var serializeTorus = function (torus) {
  15537. var serializationObject = serializePrimitive(torus);
  15538. serializationObject.diameter = torus.diameter;
  15539. serializationObject.thickness = torus.thickness;
  15540. serializationObject.tessellation = torus.tessellation;
  15541. return serializationObject;
  15542. };
  15543. var serializeGround = function (ground) {
  15544. var serializationObject = serializePrimitive(ground);
  15545. serializationObject.width = ground.width;
  15546. serializationObject.height = ground.height;
  15547. serializationObject.subdivisions = ground.subdivisions;
  15548. return serializationObject;
  15549. };
  15550. var serializePlane = function (plane) {
  15551. var serializationObject = serializePrimitive(plane);
  15552. serializationObject.size = plane.size;
  15553. return serializationObject;
  15554. };
  15555. var serializeTorusKnot = function (torusKnot) {
  15556. var serializationObject = serializePrimitive(torusKnot);
  15557. serializationObject.radius = torusKnot.radius;
  15558. serializationObject.tube = torusKnot.tube;
  15559. serializationObject.radialSegments = torusKnot.radialSegments;
  15560. serializationObject.tubularSegments = torusKnot.tubularSegments;
  15561. serializationObject.p = torusKnot.p;
  15562. serializationObject.q = torusKnot.q;
  15563. return serializationObject;
  15564. };
  15565. var serializeMesh = function (mesh, serializationScene) {
  15566. var serializationObject = {};
  15567. serializationObject.name = mesh.name;
  15568. serializationObject.id = mesh.id;
  15569. if (BABYLON.Tags.HasTags(mesh)) {
  15570. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  15571. }
  15572. serializationObject.position = mesh.position.asArray();
  15573. if (mesh.rotationQuaternion) {
  15574. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  15575. } else if (mesh.rotation) {
  15576. serializationObject.rotation = mesh.rotation.asArray();
  15577. }
  15578. serializationObject.scaling = mesh.scaling.asArray();
  15579. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  15580. serializationObject.isEnabled = mesh.isEnabled();
  15581. serializationObject.isVisible = mesh.isVisible;
  15582. serializationObject.infiniteDistance = mesh.infiniteDistance;
  15583. serializationObject.pickable = mesh.isPickable;
  15584. serializationObject.receiveShadows = mesh.receiveShadows;
  15585. serializationObject.billboardMode = mesh.billboardMode;
  15586. serializationObject.visibility = mesh.visibility;
  15587. serializationObject.checkCollisions = mesh.checkCollisions;
  15588. if (mesh.parent) {
  15589. serializationObject.parentId = mesh.parent.id;
  15590. }
  15591. var geometry = mesh._geometry;
  15592. if (geometry) {
  15593. var geometryId = geometry.id;
  15594. serializationObject.geometryId = geometryId;
  15595. if (!mesh.getScene().getGeometryByID(geometryId)) {
  15596. serializeGeometry(geometry, serializationScene.geometries);
  15597. }
  15598. serializationObject.subMeshes = [];
  15599. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  15600. var subMesh = mesh.subMeshes[subIndex];
  15601. serializationObject.subMeshes.push({
  15602. materialIndex: subMesh.materialIndex,
  15603. verticesStart: subMesh.verticesStart,
  15604. verticesCount: subMesh.verticesCount,
  15605. indexStart: subMesh.indexStart,
  15606. indexCount: subMesh.indexCount
  15607. });
  15608. }
  15609. }
  15610. if (mesh.material) {
  15611. serializationObject.materialId = mesh.material.id;
  15612. } else {
  15613. mesh.material = null;
  15614. }
  15615. if (mesh.skeleton) {
  15616. serializationObject.skeletonId = mesh.skeleton.id;
  15617. }
  15618. if (mesh.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  15619. serializationObject.physicsMass = mesh.getPhysicsMass();
  15620. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  15621. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  15622. switch (mesh.getPhysicsImpostor()) {
  15623. case BABYLON.PhysicsEngine.BoxImpostor:
  15624. serializationObject.physicsImpostor = 1;
  15625. break;
  15626. case BABYLON.PhysicsEngine.SphereImpostor:
  15627. serializationObject.physicsImpostor = 2;
  15628. break;
  15629. }
  15630. }
  15631. serializationObject.instances = [];
  15632. for (var index = 0; index < mesh.instances.length; index++) {
  15633. var instance = mesh.instances[index];
  15634. var serializationInstance = {
  15635. name: instance.name,
  15636. position: instance.position,
  15637. rotation: instance.rotation,
  15638. rotationQuaternion: instance.rotationQuaternion,
  15639. scaling: instance.scaling
  15640. };
  15641. serializationObject.instances.push(serializationInstance);
  15642. appendAnimations(instance, serializationInstance);
  15643. }
  15644. appendAnimations(mesh, serializationObject);
  15645. serializationObject.layerMask = mesh.layerMask;
  15646. return serializationObject;
  15647. };
  15648. var SceneSerializer = (function () {
  15649. function SceneSerializer() {
  15650. }
  15651. SceneSerializer.Serialize = function (scene) {
  15652. var serializationObject = {};
  15653. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  15654. serializationObject.autoClear = scene.autoClear;
  15655. serializationObject.clearColor = scene.clearColor.asArray();
  15656. serializationObject.ambientColor = scene.ambientColor.asArray();
  15657. serializationObject.gravity = scene.gravity.asArray();
  15658. if (scene.fogMode && scene.fogMode !== 0) {
  15659. serializationObject.fogMode = scene.fogMode;
  15660. serializationObject.fogColor = scene.fogColor.asArray();
  15661. serializationObject.fogStart = scene.fogStart;
  15662. serializationObject.fogEnd = scene.fogEnd;
  15663. serializationObject.fogDensity = scene.fogDensity;
  15664. }
  15665. serializationObject.lights = [];
  15666. for (var index = 0; index < scene.lights.length; index++) {
  15667. var light = scene.lights[index];
  15668. serializationObject.lights.push(serializeLight(light));
  15669. }
  15670. serializationObject.cameras = [];
  15671. for (index = 0; index < scene.cameras.length; index++) {
  15672. var camera = scene.cameras[index];
  15673. if (camera instanceof BABYLON.FreeCamera) {
  15674. serializationObject.cameras.push(serializeCamera(camera));
  15675. }
  15676. }
  15677. if (scene.activeCamera) {
  15678. serializationObject.activeCameraID = scene.activeCamera.id;
  15679. }
  15680. serializationObject.materials = [];
  15681. serializationObject.multiMaterials = [];
  15682. for (index = 0; index < scene.materials.length; index++) {
  15683. var material = scene.materials[index];
  15684. if (material instanceof BABYLON.StandardMaterial) {
  15685. serializationObject.materials.push(serializeMaterial(material));
  15686. } else if (material instanceof BABYLON.MultiMaterial) {
  15687. serializationObject.multiMaterials.push(serializeMultiMaterial(material));
  15688. }
  15689. }
  15690. serializationObject.skeletons = [];
  15691. for (index = 0; index < scene.skeletons.length; index++) {
  15692. serializationObject.skeletons.push(serializeSkeleton(scene.skeletons[index]));
  15693. }
  15694. serializationObject.geometries = {};
  15695. serializationObject.geometries.boxes = [];
  15696. serializationObject.geometries.spheres = [];
  15697. serializationObject.geometries.cylinders = [];
  15698. serializationObject.geometries.toruses = [];
  15699. serializationObject.geometries.grounds = [];
  15700. serializationObject.geometries.planes = [];
  15701. serializationObject.geometries.torusKnots = [];
  15702. serializationObject.geometries.vertexData = [];
  15703. serializedGeometries = [];
  15704. var geometries = scene.getGeometries();
  15705. for (var index = 0; index < geometries.length; index++) {
  15706. var geometry = geometries[index];
  15707. if (geometry.isReady()) {
  15708. serializeGeometry(geometry, serializationObject.geometries);
  15709. }
  15710. }
  15711. serializationObject.meshes = [];
  15712. for (index = 0; index < scene.meshes.length; index++) {
  15713. var abstractMesh = scene.meshes[index];
  15714. if (abstractMesh instanceof BABYLON.Mesh) {
  15715. var mesh = abstractMesh;
  15716. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  15717. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  15718. }
  15719. }
  15720. }
  15721. serializationObject.particleSystems = [];
  15722. for (index = 0; index < scene.particleSystems.length; index++) {
  15723. serializationObject.particleSystems.push(serializeParticleSystem(scene.particleSystems[index]));
  15724. }
  15725. serializationObject.lensFlareSystems = [];
  15726. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  15727. serializationObject.lensFlareSystems.push(serializeLensFlareSystem(scene.lensFlareSystems[index]));
  15728. }
  15729. serializationObject.shadowGenerators = [];
  15730. for (index = 0; index < scene.lights.length; index++) {
  15731. light = scene.lights[index];
  15732. if (light.getShadowGenerator()) {
  15733. serializationObject.shadowGenerators.push(serializeShadowGenerator(light));
  15734. }
  15735. }
  15736. return serializationObject;
  15737. };
  15738. return SceneSerializer;
  15739. })();
  15740. BABYLON.SceneSerializer = SceneSerializer;
  15741. })(BABYLON || (BABYLON = {}));
  15742. var BABYLON;
  15743. (function (BABYLON) {
  15744. var SceneLoader = (function () {
  15745. function SceneLoader() {
  15746. }
  15747. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  15748. get: function () {
  15749. return SceneLoader._ForceFullSceneLoadingForIncremental;
  15750. },
  15751. set: function (value) {
  15752. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  15753. },
  15754. enumerable: true,
  15755. configurable: true
  15756. });
  15757. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  15758. get: function () {
  15759. return SceneLoader._ShowLoadingScreen;
  15760. },
  15761. set: function (value) {
  15762. SceneLoader._ShowLoadingScreen = value;
  15763. },
  15764. enumerable: true,
  15765. configurable: true
  15766. });
  15767. SceneLoader._getPluginForFilename = function (sceneFilename) {
  15768. var dotPosition = sceneFilename.lastIndexOf(".");
  15769. var queryStringPosition = sceneFilename.indexOf("?");
  15770. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  15771. for (var index = 0; index < this._registeredPlugins.length; index++) {
  15772. var plugin = this._registeredPlugins[index];
  15773. if (plugin.extensions.indexOf(extension) !== -1) {
  15774. return plugin;
  15775. }
  15776. }
  15777. return this._registeredPlugins[this._registeredPlugins.length - 1];
  15778. };
  15779. SceneLoader.RegisterPlugin = function (plugin) {
  15780. plugin.extensions = plugin.extensions.toLowerCase();
  15781. SceneLoader._registeredPlugins.push(plugin);
  15782. };
  15783. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  15784. var manifestChecked = function (success) {
  15785. scene.database = database;
  15786. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  15787. var importMeshFromData = function (data) {
  15788. var meshes = [];
  15789. var particleSystems = [];
  15790. var skeletons = [];
  15791. try {
  15792. if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  15793. if (onerror) {
  15794. onerror(scene, 'unable to load the scene');
  15795. }
  15796. return;
  15797. }
  15798. } catch (e) {
  15799. if (onerror) {
  15800. onerror(scene, e);
  15801. }
  15802. return;
  15803. }
  15804. if (onsuccess) {
  15805. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  15806. onsuccess(meshes, particleSystems, skeletons);
  15807. }
  15808. };
  15809. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  15810. importMeshFromData(sceneFilename.substr(5));
  15811. return;
  15812. }
  15813. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  15814. importMeshFromData(data);
  15815. }, progressCallBack, database);
  15816. };
  15817. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  15818. };
  15819. /**
  15820. * Load a scene
  15821. * @param rootUrl a string that defines the root url for scene and resources
  15822. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  15823. * @param engine is the instance of BABYLON.Engine to use to create the scene
  15824. */
  15825. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  15826. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  15827. };
  15828. /**
  15829. * Append a scene
  15830. * @param rootUrl a string that defines the root url for scene and resources
  15831. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  15832. * @param scene is the instance of BABYLON.Scene to append to
  15833. */
  15834. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  15835. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  15836. var database;
  15837. if (SceneLoader.ShowLoadingScreen) {
  15838. scene.getEngine().displayLoadingUI();
  15839. }
  15840. var loadSceneFromData = function (data) {
  15841. scene.database = database;
  15842. if (!plugin.load(scene, data, rootUrl)) {
  15843. if (onerror) {
  15844. onerror(scene);
  15845. }
  15846. scene.getEngine().hideLoadingUI();
  15847. return;
  15848. }
  15849. if (onsuccess) {
  15850. onsuccess(scene);
  15851. }
  15852. if (SceneLoader.ShowLoadingScreen) {
  15853. scene.executeWhenReady(function () {
  15854. scene.getEngine().hideLoadingUI();
  15855. });
  15856. }
  15857. };
  15858. var manifestChecked = function (success) {
  15859. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  15860. };
  15861. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  15862. loadSceneFromData(sceneFilename.substr(5));
  15863. return;
  15864. }
  15865. if (rootUrl.indexOf("file:") === -1) {
  15866. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  15867. } else {
  15868. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  15869. }
  15870. };
  15871. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  15872. SceneLoader._ShowLoadingScreen = true;
  15873. SceneLoader._registeredPlugins = new Array();
  15874. return SceneLoader;
  15875. })();
  15876. BABYLON.SceneLoader = SceneLoader;
  15877. ;
  15878. })(BABYLON || (BABYLON = {}));
  15879. var BABYLON;
  15880. (function (BABYLON) {
  15881. (function (Internals) {
  15882. var checkColors4 = function (colors, count) {
  15883. if (colors.length === count * 3) {
  15884. var colors4 = [];
  15885. for (var index = 0; index < colors.length; index += 3) {
  15886. var newIndex = (index / 3) * 4;
  15887. colors4[newIndex] = colors[index];
  15888. colors4[newIndex + 1] = colors[index + 1];
  15889. colors4[newIndex + 2] = colors[index + 2];
  15890. colors4[newIndex + 3] = 1.0;
  15891. }
  15892. return colors4;
  15893. }
  15894. return colors;
  15895. };
  15896. var loadCubeTexture = function (rootUrl, parsedTexture, scene) {
  15897. var texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene);
  15898. texture.name = parsedTexture.name;
  15899. texture.hasAlpha = parsedTexture.hasAlpha;
  15900. texture.level = parsedTexture.level;
  15901. texture.coordinatesMode = parsedTexture.coordinatesMode;
  15902. return texture;
  15903. };
  15904. var loadTexture = function (rootUrl, parsedTexture, scene) {
  15905. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  15906. return null;
  15907. }
  15908. if (parsedTexture.isCube) {
  15909. return loadCubeTexture(rootUrl, parsedTexture, scene);
  15910. }
  15911. var texture;
  15912. if (parsedTexture.mirrorPlane) {
  15913. texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  15914. texture._waitingRenderList = parsedTexture.renderList;
  15915. texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  15916. } else if (parsedTexture.isRenderTarget) {
  15917. texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  15918. texture._waitingRenderList = parsedTexture.renderList;
  15919. } else {
  15920. texture = new BABYLON.Texture(rootUrl + parsedTexture.name, scene);
  15921. }
  15922. texture.name = parsedTexture.name;
  15923. texture.hasAlpha = parsedTexture.hasAlpha;
  15924. texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
  15925. texture.level = parsedTexture.level;
  15926. texture.coordinatesIndex = parsedTexture.coordinatesIndex;
  15927. texture.coordinatesMode = parsedTexture.coordinatesMode;
  15928. texture.uOffset = parsedTexture.uOffset;
  15929. texture.vOffset = parsedTexture.vOffset;
  15930. texture.uScale = parsedTexture.uScale;
  15931. texture.vScale = parsedTexture.vScale;
  15932. texture.uAng = parsedTexture.uAng;
  15933. texture.vAng = parsedTexture.vAng;
  15934. texture.wAng = parsedTexture.wAng;
  15935. texture.wrapU = parsedTexture.wrapU;
  15936. texture.wrapV = parsedTexture.wrapV;
  15937. if (parsedTexture.animations) {
  15938. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  15939. var parsedAnimation = parsedTexture.animations[animationIndex];
  15940. texture.animations.push(parseAnimation(parsedAnimation));
  15941. }
  15942. }
  15943. return texture;
  15944. };
  15945. var parseSkeleton = function (parsedSkeleton, scene) {
  15946. var skeleton = new BABYLON.Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  15947. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  15948. var parsedBone = parsedSkeleton.bones[index];
  15949. var parentBone = null;
  15950. if (parsedBone.parentBoneIndex > -1) {
  15951. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  15952. }
  15953. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix));
  15954. if (parsedBone.animation) {
  15955. bone.animations.push(parseAnimation(parsedBone.animation));
  15956. }
  15957. }
  15958. return skeleton;
  15959. };
  15960. var parseFresnelParameters = function (parsedFresnelParameters) {
  15961. var fresnelParameters = new BABYLON.FresnelParameters();
  15962. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  15963. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  15964. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  15965. fresnelParameters.bias = parsedFresnelParameters.bias;
  15966. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  15967. return fresnelParameters;
  15968. };
  15969. var parseMaterial = function (parsedMaterial, scene, rootUrl) {
  15970. var material;
  15971. material = new BABYLON.StandardMaterial(parsedMaterial.name, scene);
  15972. material.ambientColor = BABYLON.Color3.FromArray(parsedMaterial.ambient);
  15973. material.diffuseColor = BABYLON.Color3.FromArray(parsedMaterial.diffuse);
  15974. material.specularColor = BABYLON.Color3.FromArray(parsedMaterial.specular);
  15975. material.specularPower = parsedMaterial.specularPower;
  15976. material.emissiveColor = BABYLON.Color3.FromArray(parsedMaterial.emissive);
  15977. material.alpha = parsedMaterial.alpha;
  15978. material.id = parsedMaterial.id;
  15979. BABYLON.Tags.AddTagsTo(material, parsedMaterial.tags);
  15980. material.backFaceCulling = parsedMaterial.backFaceCulling;
  15981. material.wireframe = parsedMaterial.wireframe;
  15982. if (parsedMaterial.diffuseTexture) {
  15983. material.diffuseTexture = loadTexture(rootUrl, parsedMaterial.diffuseTexture, scene);
  15984. }
  15985. if (parsedMaterial.diffuseFresnelParameters) {
  15986. material.diffuseFresnelParameters = parseFresnelParameters(parsedMaterial.diffuseFresnelParameters);
  15987. }
  15988. if (parsedMaterial.ambientTexture) {
  15989. material.ambientTexture = loadTexture(rootUrl, parsedMaterial.ambientTexture, scene);
  15990. }
  15991. if (parsedMaterial.opacityTexture) {
  15992. material.opacityTexture = loadTexture(rootUrl, parsedMaterial.opacityTexture, scene);
  15993. }
  15994. if (parsedMaterial.opacityFresnelParameters) {
  15995. material.opacityFresnelParameters = parseFresnelParameters(parsedMaterial.opacityFresnelParameters);
  15996. }
  15997. if (parsedMaterial.reflectionTexture) {
  15998. material.reflectionTexture = loadTexture(rootUrl, parsedMaterial.reflectionTexture, scene);
  15999. }
  16000. if (parsedMaterial.reflectionFresnelParameters) {
  16001. material.reflectionFresnelParameters = parseFresnelParameters(parsedMaterial.reflectionFresnelParameters);
  16002. }
  16003. if (parsedMaterial.emissiveTexture) {
  16004. material.emissiveTexture = loadTexture(rootUrl, parsedMaterial.emissiveTexture, scene);
  16005. }
  16006. if (parsedMaterial.emissiveFresnelParameters) {
  16007. material.emissiveFresnelParameters = parseFresnelParameters(parsedMaterial.emissiveFresnelParameters);
  16008. }
  16009. if (parsedMaterial.specularTexture) {
  16010. material.specularTexture = loadTexture(rootUrl, parsedMaterial.specularTexture, scene);
  16011. }
  16012. if (parsedMaterial.bumpTexture) {
  16013. material.bumpTexture = loadTexture(rootUrl, parsedMaterial.bumpTexture, scene);
  16014. }
  16015. return material;
  16016. };
  16017. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  16018. for (var index = 0; index < parsedData.materials.length; index++) {
  16019. var parsedMaterial = parsedData.materials[index];
  16020. if (parsedMaterial.id === id) {
  16021. return parseMaterial(parsedMaterial, scene, rootUrl);
  16022. }
  16023. }
  16024. return null;
  16025. };
  16026. var parseMultiMaterial = function (parsedMultiMaterial, scene) {
  16027. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  16028. multiMaterial.id = parsedMultiMaterial.id;
  16029. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  16030. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  16031. var subMatId = parsedMultiMaterial.materials[matIndex];
  16032. if (subMatId) {
  16033. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  16034. } else {
  16035. multiMaterial.subMaterials.push(null);
  16036. }
  16037. }
  16038. return multiMaterial;
  16039. };
  16040. var parseLensFlareSystem = function (parsedLensFlareSystem, scene, rootUrl) {
  16041. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  16042. var lensFlareSystem = new BABYLON.LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  16043. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  16044. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  16045. var parsedFlare = parsedLensFlareSystem.flares[index];
  16046. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  16047. }
  16048. return lensFlareSystem;
  16049. };
  16050. var parseParticleSystem = function (parsedParticleSystem, scene, rootUrl) {
  16051. var emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  16052. var particleSystem = new BABYLON.ParticleSystem("particles#" + emitter.name, parsedParticleSystem.capacity, scene);
  16053. if (parsedParticleSystem.textureName) {
  16054. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  16055. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  16056. }
  16057. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  16058. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  16059. particleSystem.minSize = parsedParticleSystem.minSize;
  16060. particleSystem.maxSize = parsedParticleSystem.maxSize;
  16061. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  16062. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  16063. particleSystem.emitter = emitter;
  16064. particleSystem.emitRate = parsedParticleSystem.emitRate;
  16065. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  16066. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  16067. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  16068. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  16069. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  16070. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  16071. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  16072. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  16073. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  16074. particleSystem.targetStopDuration = parsedParticleSystem.targetStopFrame;
  16075. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  16076. particleSystem.blendMode = parsedParticleSystem.blendMode;
  16077. particleSystem.start();
  16078. return particleSystem;
  16079. };
  16080. var parseShadowGenerator = function (parsedShadowGenerator, scene) {
  16081. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  16082. var shadowGenerator = new BABYLON.ShadowGenerator(parsedShadowGenerator.mapSize, light);
  16083. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  16084. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  16085. shadowGenerator.getShadowMap().renderList.push(mesh);
  16086. }
  16087. if (parsedShadowGenerator.usePoissonSampling) {
  16088. shadowGenerator.usePoissonSampling = true;
  16089. } else {
  16090. shadowGenerator.useVarianceShadowMap = parsedShadowGenerator.useVarianceShadowMap;
  16091. }
  16092. return shadowGenerator;
  16093. };
  16094. var parseAnimation = function (parsedAnimation) {
  16095. var animation = new BABYLON.Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  16096. var dataType = parsedAnimation.dataType;
  16097. var keys = [];
  16098. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  16099. var key = parsedAnimation.keys[index];
  16100. var data;
  16101. switch (dataType) {
  16102. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  16103. data = key.values[0];
  16104. break;
  16105. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  16106. data = BABYLON.Quaternion.FromArray(key.values);
  16107. break;
  16108. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  16109. data = BABYLON.Matrix.FromArray(key.values);
  16110. break;
  16111. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  16112. default:
  16113. data = BABYLON.Vector3.FromArray(key.values);
  16114. break;
  16115. }
  16116. keys.push({
  16117. frame: key.frame,
  16118. value: data
  16119. });
  16120. }
  16121. animation.setKeys(keys);
  16122. return animation;
  16123. };
  16124. var parseLight = function (parsedLight, scene) {
  16125. var light;
  16126. switch (parsedLight.type) {
  16127. case 0:
  16128. light = new BABYLON.PointLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), scene);
  16129. break;
  16130. case 1:
  16131. light = new BABYLON.DirectionalLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  16132. light.position = BABYLON.Vector3.FromArray(parsedLight.position);
  16133. break;
  16134. case 2:
  16135. light = new BABYLON.SpotLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), BABYLON.Vector3.FromArray(parsedLight.direction), parsedLight.angle, parsedLight.exponent, scene);
  16136. break;
  16137. case 3:
  16138. light = new BABYLON.HemisphericLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  16139. light.groundColor = BABYLON.Color3.FromArray(parsedLight.groundColor);
  16140. break;
  16141. }
  16142. light.id = parsedLight.id;
  16143. BABYLON.Tags.AddTagsTo(light, parsedLight.tags);
  16144. if (parsedLight.intensity !== undefined) {
  16145. light.intensity = parsedLight.intensity;
  16146. }
  16147. if (parsedLight.range) {
  16148. light.range = parsedLight.range;
  16149. }
  16150. light.diffuse = BABYLON.Color3.FromArray(parsedLight.diffuse);
  16151. light.specular = BABYLON.Color3.FromArray(parsedLight.specular);
  16152. if (parsedLight.excludedMeshesIds) {
  16153. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  16154. }
  16155. if (parsedLight.parentId) {
  16156. light._waitingParentId = parsedLight.parentId;
  16157. }
  16158. if (parsedLight.includedOnlyMeshesIds) {
  16159. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  16160. }
  16161. if (parsedLight.animations) {
  16162. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  16163. var parsedAnimation = parsedLight.animations[animationIndex];
  16164. light.animations.push(parseAnimation(parsedAnimation));
  16165. }
  16166. }
  16167. if (parsedLight.autoAnimate) {
  16168. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, 1.0);
  16169. }
  16170. };
  16171. var parseCamera = function (parsedCamera, scene) {
  16172. var camera;
  16173. var position = BABYLON.Vector3.FromArray(parsedCamera.position);
  16174. var lockedTargetMesh = (parsedCamera.lockedTargetId) ? scene.getLastMeshByID(parsedCamera.lockedTargetId) : null;
  16175. if (parsedCamera.type === "AnaglyphArcRotateCamera" || parsedCamera.type === "ArcRotateCamera") {
  16176. var alpha = parsedCamera.alpha;
  16177. var beta = parsedCamera.beta;
  16178. var radius = parsedCamera.radius;
  16179. if (parsedCamera.type === "AnaglyphArcRotateCamera") {
  16180. var eye_space = parsedCamera.eye_space;
  16181. camera = new BABYLON.AnaglyphArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, eye_space, scene);
  16182. } else {
  16183. camera = new BABYLON.ArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, scene);
  16184. }
  16185. } else if (parsedCamera.type === "AnaglyphFreeCamera") {
  16186. var eye_space = parsedCamera.eye_space;
  16187. camera = new BABYLON.AnaglyphFreeCamera(parsedCamera.name, position, eye_space, scene);
  16188. } else if (parsedCamera.type === "DeviceOrientationCamera") {
  16189. camera = new BABYLON.DeviceOrientationCamera(parsedCamera.name, position, scene);
  16190. } else if (parsedCamera.type === "FollowCamera") {
  16191. camera = new BABYLON.FollowCamera(parsedCamera.name, position, scene);
  16192. camera.heightOffset = parsedCamera.heightOffset;
  16193. camera.radius = parsedCamera.radius;
  16194. camera.rotationOffset = parsedCamera.rotationOffset;
  16195. if (lockedTargetMesh)
  16196. camera.target = lockedTargetMesh;
  16197. } else if (parsedCamera.type === "GamepadCamera") {
  16198. camera = new BABYLON.GamepadCamera(parsedCamera.name, position, scene);
  16199. } else if (parsedCamera.type === "OculusCamera") {
  16200. camera = new BABYLON.OculusCamera(parsedCamera.name, position, scene);
  16201. } else if (parsedCamera.type === "TouchCamera") {
  16202. camera = new BABYLON.TouchCamera(parsedCamera.name, position, scene);
  16203. } else if (parsedCamera.type === "VirtualJoysticksCamera") {
  16204. camera = new BABYLON.VirtualJoysticksCamera(parsedCamera.name, position, scene);
  16205. } else if (parsedCamera.type === "WebVRCamera") {
  16206. camera = new BABYLON.WebVRCamera(parsedCamera.name, position, scene);
  16207. } else if (parsedCamera.type === "VRDeviceOrientationCamera") {
  16208. camera = new BABYLON.VRDeviceOrientationCamera(parsedCamera.name, position, scene);
  16209. } else {
  16210. camera = new BABYLON.FreeCamera(parsedCamera.name, position, scene);
  16211. }
  16212. if (lockedTargetMesh && camera instanceof BABYLON.FreeCamera) {
  16213. camera.lockedTarget = lockedTargetMesh;
  16214. }
  16215. camera.id = parsedCamera.id;
  16216. BABYLON.Tags.AddTagsTo(camera, parsedCamera.tags);
  16217. if (parsedCamera.parentId) {
  16218. camera._waitingParentId = parsedCamera.parentId;
  16219. }
  16220. if (parsedCamera.target) {
  16221. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  16222. } else {
  16223. camera.rotation = BABYLON.Vector3.FromArray(parsedCamera.rotation);
  16224. }
  16225. camera.fov = parsedCamera.fov;
  16226. camera.minZ = parsedCamera.minZ;
  16227. camera.maxZ = parsedCamera.maxZ;
  16228. camera.speed = parsedCamera.speed;
  16229. camera.inertia = parsedCamera.inertia;
  16230. camera.checkCollisions = parsedCamera.checkCollisions;
  16231. camera.applyGravity = parsedCamera.applyGravity;
  16232. if (parsedCamera.ellipsoid) {
  16233. camera.ellipsoid = BABYLON.Vector3.FromArray(parsedCamera.ellipsoid);
  16234. }
  16235. if (parsedCamera.animations) {
  16236. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  16237. var parsedAnimation = parsedCamera.animations[animationIndex];
  16238. camera.animations.push(parseAnimation(parsedAnimation));
  16239. }
  16240. }
  16241. if (parsedCamera.autoAnimate) {
  16242. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, 1.0);
  16243. }
  16244. if (parsedCamera.layerMask && (!isNaN(parsedCamera.layerMask))) {
  16245. camera.layerMask = Math.abs(parseInt(parsedCamera.layerMask));
  16246. } else {
  16247. camera.layerMask = 0xFFFFFFFF;
  16248. }
  16249. return camera;
  16250. };
  16251. var parseGeometry = function (parsedGeometry, scene) {
  16252. var id = parsedGeometry.id;
  16253. return scene.getGeometryByID(id);
  16254. };
  16255. var parseBox = function (parsedBox, scene) {
  16256. if (parseGeometry(parsedBox, scene)) {
  16257. return null;
  16258. }
  16259. var box = new BABYLON.Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  16260. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  16261. scene.pushGeometry(box, true);
  16262. return box;
  16263. };
  16264. var parseSphere = function (parsedSphere, scene) {
  16265. if (parseGeometry(parsedSphere, scene)) {
  16266. return null;
  16267. }
  16268. var sphere = new BABYLON.Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  16269. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  16270. scene.pushGeometry(sphere, true);
  16271. return sphere;
  16272. };
  16273. var parseCylinder = function (parsedCylinder, scene) {
  16274. if (parseGeometry(parsedCylinder, scene)) {
  16275. return null;
  16276. }
  16277. var cylinder = new BABYLON.Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  16278. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  16279. scene.pushGeometry(cylinder, true);
  16280. return cylinder;
  16281. };
  16282. var parseTorus = function (parsedTorus, scene) {
  16283. if (parseGeometry(parsedTorus, scene)) {
  16284. return null;
  16285. }
  16286. var torus = new BABYLON.Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  16287. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  16288. scene.pushGeometry(torus, true);
  16289. return torus;
  16290. };
  16291. var parseGround = function (parsedGround, scene) {
  16292. if (parseGeometry(parsedGround, scene)) {
  16293. return null;
  16294. }
  16295. var ground = new BABYLON.Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  16296. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  16297. scene.pushGeometry(ground, true);
  16298. return ground;
  16299. };
  16300. var parsePlane = function (parsedPlane, scene) {
  16301. if (parseGeometry(parsedPlane, scene)) {
  16302. return null;
  16303. }
  16304. var plane = new BABYLON.Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  16305. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  16306. scene.pushGeometry(plane, true);
  16307. return plane;
  16308. };
  16309. var parseTorusKnot = function (parsedTorusKnot, scene) {
  16310. if (parseGeometry(parsedTorusKnot, scene)) {
  16311. return null;
  16312. }
  16313. 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);
  16314. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  16315. scene.pushGeometry(torusKnot, true);
  16316. return torusKnot;
  16317. };
  16318. var parseVertexData = function (parsedVertexData, scene, rootUrl) {
  16319. if (parseGeometry(parsedVertexData, scene)) {
  16320. return null;
  16321. }
  16322. var geometry = new BABYLON.Geometry(parsedVertexData.id, scene);
  16323. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  16324. if (parsedVertexData.delayLoadingFile) {
  16325. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  16326. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  16327. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  16328. geometry._delayInfo = [];
  16329. if (parsedVertexData.hasUVs) {
  16330. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  16331. }
  16332. if (parsedVertexData.hasUVs2) {
  16333. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  16334. }
  16335. if (parsedVertexData.hasColors) {
  16336. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  16337. }
  16338. if (parsedVertexData.hasMatricesIndices) {
  16339. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  16340. }
  16341. if (parsedVertexData.hasMatricesWeights) {
  16342. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  16343. }
  16344. geometry._delayLoadingFunction = importVertexData;
  16345. } else {
  16346. importVertexData(parsedVertexData, geometry);
  16347. }
  16348. scene.pushGeometry(geometry, true);
  16349. return geometry;
  16350. };
  16351. var parseMesh = function (parsedMesh, scene, rootUrl) {
  16352. var mesh = new BABYLON.Mesh(parsedMesh.name, scene);
  16353. mesh.id = parsedMesh.id;
  16354. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  16355. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  16356. if (parsedMesh.rotationQuaternion) {
  16357. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  16358. } else if (parsedMesh.rotation) {
  16359. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  16360. }
  16361. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  16362. if (parsedMesh.localMatrix) {
  16363. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  16364. } else if (parsedMesh.pivotMatrix) {
  16365. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  16366. }
  16367. mesh.setEnabled(parsedMesh.isEnabled);
  16368. mesh.isVisible = parsedMesh.isVisible;
  16369. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  16370. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  16371. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  16372. if (parsedMesh.pickable !== undefined) {
  16373. mesh.isPickable = parsedMesh.pickable;
  16374. }
  16375. mesh.receiveShadows = parsedMesh.receiveShadows;
  16376. mesh.billboardMode = parsedMesh.billboardMode;
  16377. if (parsedMesh.visibility !== undefined) {
  16378. mesh.visibility = parsedMesh.visibility;
  16379. }
  16380. mesh.checkCollisions = parsedMesh.checkCollisions;
  16381. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  16382. if (parsedMesh.parentId) {
  16383. mesh._waitingParentId = parsedMesh.parentId;
  16384. }
  16385. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  16386. if (parsedMesh.delayLoadingFile) {
  16387. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  16388. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  16389. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  16390. if (parsedMesh._binaryInfo) {
  16391. mesh._binaryInfo = parsedMesh._binaryInfo;
  16392. }
  16393. mesh._delayInfo = [];
  16394. if (parsedMesh.hasUVs) {
  16395. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  16396. }
  16397. if (parsedMesh.hasUVs2) {
  16398. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  16399. }
  16400. if (parsedMesh.hasColors) {
  16401. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  16402. }
  16403. if (parsedMesh.hasMatricesIndices) {
  16404. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  16405. }
  16406. if (parsedMesh.hasMatricesWeights) {
  16407. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  16408. }
  16409. mesh._delayLoadingFunction = importGeometry;
  16410. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  16411. mesh._checkDelayState();
  16412. }
  16413. } else {
  16414. importGeometry(parsedMesh, mesh);
  16415. }
  16416. if (parsedMesh.materialId) {
  16417. mesh.setMaterialByID(parsedMesh.materialId);
  16418. } else {
  16419. mesh.material = null;
  16420. }
  16421. if (parsedMesh.skeletonId > -1) {
  16422. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  16423. }
  16424. if (parsedMesh.physicsImpostor) {
  16425. if (!scene.isPhysicsEnabled()) {
  16426. scene.enablePhysics();
  16427. }
  16428. mesh.setPhysicsState({ impostor: parsedMesh.physicsImpostor, mass: parsedMesh.physicsMass, friction: parsedMesh.physicsFriction, restitution: parsedMesh.physicsRestitution });
  16429. }
  16430. if (parsedMesh.animations) {
  16431. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  16432. var parsedAnimation = parsedMesh.animations[animationIndex];
  16433. mesh.animations.push(parseAnimation(parsedAnimation));
  16434. }
  16435. }
  16436. if (parsedMesh.autoAnimate) {
  16437. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, 1.0);
  16438. }
  16439. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  16440. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  16441. } else {
  16442. mesh.layerMask = 0xFFFFFFFF;
  16443. }
  16444. if (parsedMesh.instances) {
  16445. for (var index = 0; index < parsedMesh.instances.length; index++) {
  16446. var parsedInstance = parsedMesh.instances[index];
  16447. var instance = mesh.createInstance(parsedInstance.name);
  16448. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  16449. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  16450. if (parsedInstance.rotationQuaternion) {
  16451. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  16452. } else if (parsedInstance.rotation) {
  16453. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  16454. }
  16455. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  16456. instance.checkCollisions = mesh.checkCollisions;
  16457. if (parsedMesh.animations) {
  16458. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  16459. parsedAnimation = parsedMesh.animations[animationIndex];
  16460. instance.animations.push(parseAnimation(parsedAnimation));
  16461. }
  16462. }
  16463. }
  16464. }
  16465. return mesh;
  16466. };
  16467. var isDescendantOf = function (mesh, names, hierarchyIds) {
  16468. names = (names instanceof Array) ? names : [names];
  16469. for (var i in names) {
  16470. if (mesh.name === names[i]) {
  16471. hierarchyIds.push(mesh.id);
  16472. return true;
  16473. }
  16474. }
  16475. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  16476. hierarchyIds.push(mesh.id);
  16477. return true;
  16478. }
  16479. return false;
  16480. };
  16481. var importVertexData = function (parsedVertexData, geometry) {
  16482. var vertexData = new BABYLON.VertexData();
  16483. var positions = parsedVertexData.positions;
  16484. if (positions) {
  16485. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  16486. }
  16487. var normals = parsedVertexData.normals;
  16488. if (normals) {
  16489. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  16490. }
  16491. var uvs = parsedVertexData.uvs;
  16492. if (uvs) {
  16493. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  16494. }
  16495. var uv2s = parsedVertexData.uv2s;
  16496. if (uv2s) {
  16497. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  16498. }
  16499. var colors = parsedVertexData.colors;
  16500. if (colors) {
  16501. vertexData.set(checkColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  16502. }
  16503. var matricesIndices = parsedVertexData.matricesIndices;
  16504. if (matricesIndices) {
  16505. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  16506. }
  16507. var matricesWeights = parsedVertexData.matricesWeights;
  16508. if (matricesWeights) {
  16509. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  16510. }
  16511. var indices = parsedVertexData.indices;
  16512. if (indices) {
  16513. vertexData.indices = indices;
  16514. }
  16515. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  16516. };
  16517. var importGeometry = function (parsedGeometry, mesh) {
  16518. var scene = mesh.getScene();
  16519. var geometryId = parsedGeometry.geometryId;
  16520. if (geometryId) {
  16521. var geometry = scene.getGeometryByID(geometryId);
  16522. if (geometry) {
  16523. geometry.applyToMesh(mesh);
  16524. }
  16525. } else if (parsedGeometry instanceof ArrayBuffer) {
  16526. var binaryInfo = mesh._binaryInfo;
  16527. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  16528. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  16529. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  16530. }
  16531. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  16532. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  16533. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  16534. }
  16535. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  16536. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  16537. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  16538. }
  16539. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  16540. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  16541. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  16542. }
  16543. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  16544. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  16545. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false);
  16546. }
  16547. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  16548. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  16549. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  16550. }
  16551. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  16552. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  16553. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  16554. }
  16555. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  16556. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  16557. mesh.setIndices(indicesData);
  16558. }
  16559. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  16560. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  16561. mesh.subMeshes = [];
  16562. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  16563. var materialIndex = subMeshesData[(i * 5) + 0];
  16564. var verticesStart = subMeshesData[(i * 5) + 1];
  16565. var verticesCount = subMeshesData[(i * 5) + 2];
  16566. var indexStart = subMeshesData[(i * 5) + 3];
  16567. var indexCount = subMeshesData[(i * 5) + 4];
  16568. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  16569. }
  16570. }
  16571. } else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  16572. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  16573. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  16574. if (parsedGeometry.uvs) {
  16575. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  16576. }
  16577. if (parsedGeometry.uvs2) {
  16578. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  16579. }
  16580. if (parsedGeometry.colors) {
  16581. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, checkColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  16582. }
  16583. if (parsedGeometry.matricesIndices) {
  16584. if (!parsedGeometry.matricesIndices._isExpanded) {
  16585. var floatIndices = [];
  16586. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  16587. var matricesIndex = parsedGeometry.matricesIndices[i];
  16588. floatIndices.push(matricesIndex & 0x000000FF);
  16589. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  16590. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  16591. floatIndices.push(matricesIndex >> 24);
  16592. }
  16593. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  16594. } else {
  16595. delete parsedGeometry.matricesIndices._isExpanded;
  16596. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  16597. }
  16598. }
  16599. if (parsedGeometry.matricesWeights) {
  16600. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  16601. }
  16602. mesh.setIndices(parsedGeometry.indices);
  16603. if (parsedGeometry.subMeshes) {
  16604. mesh.subMeshes = [];
  16605. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  16606. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  16607. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  16608. }
  16609. }
  16610. }
  16611. if (mesh._shouldGenerateFlatShading) {
  16612. mesh.convertToFlatShadedMesh();
  16613. delete mesh._shouldGenerateFlatShading;
  16614. }
  16615. mesh.computeWorldMatrix(true);
  16616. if (scene._selectionOctree) {
  16617. scene._selectionOctree.addMesh(mesh);
  16618. }
  16619. };
  16620. BABYLON.SceneLoader.RegisterPlugin({
  16621. extensions: ".babylon",
  16622. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  16623. var parsedData = JSON.parse(data);
  16624. var loadedSkeletonsIds = [];
  16625. var loadedMaterialsIds = [];
  16626. var hierarchyIds = [];
  16627. for (var index = 0; index < parsedData.meshes.length; index++) {
  16628. var parsedMesh = parsedData.meshes[index];
  16629. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  16630. if (meshesNames instanceof Array) {
  16631. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  16632. }
  16633. if (parsedMesh.materialId) {
  16634. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  16635. if (!materialFound) {
  16636. for (var multimatIndex = 0; multimatIndex < parsedData.multiMaterials.length; multimatIndex++) {
  16637. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  16638. if (parsedMultiMaterial.id == parsedMesh.materialId) {
  16639. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  16640. var subMatId = parsedMultiMaterial.materials[matIndex];
  16641. loadedMaterialsIds.push(subMatId);
  16642. parseMaterialById(subMatId, parsedData, scene, rootUrl);
  16643. }
  16644. loadedMaterialsIds.push(parsedMultiMaterial.id);
  16645. parseMultiMaterial(parsedMultiMaterial, scene);
  16646. materialFound = true;
  16647. break;
  16648. }
  16649. }
  16650. }
  16651. if (!materialFound) {
  16652. loadedMaterialsIds.push(parsedMesh.materialId);
  16653. parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  16654. }
  16655. }
  16656. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  16657. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  16658. if (!skeletonAlreadyLoaded) {
  16659. for (var skeletonIndex = 0; skeletonIndex < parsedData.skeletons.length; skeletonIndex++) {
  16660. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  16661. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  16662. skeletons.push(parseSkeleton(parsedSkeleton, scene));
  16663. loadedSkeletonsIds.push(parsedSkeleton.id);
  16664. }
  16665. }
  16666. }
  16667. }
  16668. var mesh = parseMesh(parsedMesh, scene, rootUrl);
  16669. meshes.push(mesh);
  16670. }
  16671. }
  16672. for (index = 0; index < scene.meshes.length; index++) {
  16673. var currentMesh = scene.meshes[index];
  16674. if (currentMesh._waitingParentId) {
  16675. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  16676. currentMesh._waitingParentId = undefined;
  16677. }
  16678. }
  16679. if (parsedData.particleSystems) {
  16680. for (index = 0; index < parsedData.particleSystems.length; index++) {
  16681. var parsedParticleSystem = parsedData.particleSystems[index];
  16682. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  16683. particleSystems.push(parseParticleSystem(parsedParticleSystem, scene, rootUrl));
  16684. }
  16685. }
  16686. }
  16687. return true;
  16688. },
  16689. load: function (scene, data, rootUrl) {
  16690. var parsedData = JSON.parse(data);
  16691. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  16692. scene.autoClear = parsedData.autoClear;
  16693. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  16694. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  16695. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  16696. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  16697. scene.fogMode = parsedData.fogMode;
  16698. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  16699. scene.fogStart = parsedData.fogStart;
  16700. scene.fogEnd = parsedData.fogEnd;
  16701. scene.fogDensity = parsedData.fogDensity;
  16702. }
  16703. for (var index = 0; index < parsedData.lights.length; index++) {
  16704. var parsedLight = parsedData.lights[index];
  16705. parseLight(parsedLight, scene);
  16706. }
  16707. if (parsedData.materials) {
  16708. for (index = 0; index < parsedData.materials.length; index++) {
  16709. var parsedMaterial = parsedData.materials[index];
  16710. parseMaterial(parsedMaterial, scene, rootUrl);
  16711. }
  16712. }
  16713. if (parsedData.multiMaterials) {
  16714. for (index = 0; index < parsedData.multiMaterials.length; index++) {
  16715. var parsedMultiMaterial = parsedData.multiMaterials[index];
  16716. parseMultiMaterial(parsedMultiMaterial, scene);
  16717. }
  16718. }
  16719. if (parsedData.skeletons) {
  16720. for (index = 0; index < parsedData.skeletons.length; index++) {
  16721. var parsedSkeleton = parsedData.skeletons[index];
  16722. parseSkeleton(parsedSkeleton, scene);
  16723. }
  16724. }
  16725. var geometries = parsedData.geometries;
  16726. if (geometries) {
  16727. var boxes = geometries.boxes;
  16728. if (boxes) {
  16729. for (index = 0; index < boxes.length; index++) {
  16730. var parsedBox = boxes[index];
  16731. parseBox(parsedBox, scene);
  16732. }
  16733. }
  16734. var spheres = geometries.spheres;
  16735. if (spheres) {
  16736. for (index = 0; index < spheres.length; index++) {
  16737. var parsedSphere = spheres[index];
  16738. parseSphere(parsedSphere, scene);
  16739. }
  16740. }
  16741. var cylinders = geometries.cylinders;
  16742. if (cylinders) {
  16743. for (index = 0; index < cylinders.length; index++) {
  16744. var parsedCylinder = cylinders[index];
  16745. parseCylinder(parsedCylinder, scene);
  16746. }
  16747. }
  16748. var toruses = geometries.toruses;
  16749. if (toruses) {
  16750. for (index = 0; index < toruses.length; index++) {
  16751. var parsedTorus = toruses[index];
  16752. parseTorus(parsedTorus, scene);
  16753. }
  16754. }
  16755. var grounds = geometries.grounds;
  16756. if (grounds) {
  16757. for (index = 0; index < grounds.length; index++) {
  16758. var parsedGround = grounds[index];
  16759. parseGround(parsedGround, scene);
  16760. }
  16761. }
  16762. var planes = geometries.planes;
  16763. if (planes) {
  16764. for (index = 0; index < planes.length; index++) {
  16765. var parsedPlane = planes[index];
  16766. parsePlane(parsedPlane, scene);
  16767. }
  16768. }
  16769. var torusKnots = geometries.torusKnots;
  16770. if (torusKnots) {
  16771. for (index = 0; index < torusKnots.length; index++) {
  16772. var parsedTorusKnot = torusKnots[index];
  16773. parseTorusKnot(parsedTorusKnot, scene);
  16774. }
  16775. }
  16776. var vertexData = geometries.vertexData;
  16777. if (vertexData) {
  16778. for (index = 0; index < vertexData.length; index++) {
  16779. var parsedVertexData = vertexData[index];
  16780. parseVertexData(parsedVertexData, scene, rootUrl);
  16781. }
  16782. }
  16783. }
  16784. for (index = 0; index < parsedData.meshes.length; index++) {
  16785. var parsedMesh = parsedData.meshes[index];
  16786. parseMesh(parsedMesh, scene, rootUrl);
  16787. }
  16788. for (index = 0; index < parsedData.cameras.length; index++) {
  16789. var parsedCamera = parsedData.cameras[index];
  16790. parseCamera(parsedCamera, scene);
  16791. }
  16792. if (parsedData.activeCameraID) {
  16793. scene.setActiveCameraByID(parsedData.activeCameraID);
  16794. }
  16795. for (index = 0; index < scene.cameras.length; index++) {
  16796. var camera = scene.cameras[index];
  16797. if (camera._waitingParentId) {
  16798. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  16799. camera._waitingParentId = undefined;
  16800. }
  16801. }
  16802. for (index = 0; index < scene.lights.length; index++) {
  16803. var light = scene.lights[index];
  16804. if (light._waitingParentId) {
  16805. light.parent = scene.getLastEntryByID(light._waitingParentId);
  16806. light._waitingParentId = undefined;
  16807. }
  16808. }
  16809. for (index = 0; index < scene.meshes.length; index++) {
  16810. var mesh = scene.meshes[index];
  16811. if (mesh._waitingParentId) {
  16812. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  16813. mesh._waitingParentId = undefined;
  16814. }
  16815. }
  16816. if (parsedData.particleSystems) {
  16817. for (index = 0; index < parsedData.particleSystems.length; index++) {
  16818. var parsedParticleSystem = parsedData.particleSystems[index];
  16819. parseParticleSystem(parsedParticleSystem, scene, rootUrl);
  16820. }
  16821. }
  16822. if (parsedData.lensFlareSystems) {
  16823. for (index = 0; index < parsedData.lensFlareSystems.length; index++) {
  16824. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  16825. parseLensFlareSystem(parsedLensFlareSystem, scene, rootUrl);
  16826. }
  16827. }
  16828. if (parsedData.shadowGenerators) {
  16829. for (index = 0; index < parsedData.shadowGenerators.length; index++) {
  16830. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  16831. parseShadowGenerator(parsedShadowGenerator, scene);
  16832. }
  16833. }
  16834. return true;
  16835. }
  16836. });
  16837. })(BABYLON.Internals || (BABYLON.Internals = {}));
  16838. var Internals = BABYLON.Internals;
  16839. })(BABYLON || (BABYLON = {}));
  16840. var BABYLON;
  16841. (function (BABYLON) {
  16842. var currentCSGMeshId = 0;
  16843. var Vertex = (function () {
  16844. function Vertex(pos, normal, uv) {
  16845. this.pos = pos;
  16846. this.normal = normal;
  16847. this.uv = uv;
  16848. }
  16849. Vertex.prototype.clone = function () {
  16850. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  16851. };
  16852. Vertex.prototype.flip = function () {
  16853. this.normal = this.normal.scale(-1);
  16854. };
  16855. Vertex.prototype.interpolate = function (other, t) {
  16856. 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));
  16857. };
  16858. return Vertex;
  16859. })();
  16860. var Plane = (function () {
  16861. function Plane(normal, w) {
  16862. this.normal = normal;
  16863. this.w = w;
  16864. }
  16865. Plane.FromPoints = function (a, b, c) {
  16866. var v0 = c.subtract(a);
  16867. var v1 = b.subtract(a);
  16868. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  16869. return null;
  16870. }
  16871. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  16872. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  16873. };
  16874. Plane.prototype.clone = function () {
  16875. return new Plane(this.normal.clone(), this.w);
  16876. };
  16877. Plane.prototype.flip = function () {
  16878. this.normal.scaleInPlace(-1);
  16879. this.w = -this.w;
  16880. };
  16881. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  16882. var COPLANAR = 0;
  16883. var FRONT = 1;
  16884. var BACK = 2;
  16885. var SPANNING = 3;
  16886. var polygonType = 0;
  16887. var types = [];
  16888. for (var i = 0; i < polygon.vertices.length; i++) {
  16889. var t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  16890. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  16891. polygonType |= type;
  16892. types.push(type);
  16893. }
  16894. switch (polygonType) {
  16895. case COPLANAR:
  16896. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  16897. break;
  16898. case FRONT:
  16899. front.push(polygon);
  16900. break;
  16901. case BACK:
  16902. back.push(polygon);
  16903. break;
  16904. case SPANNING:
  16905. var f = [], b = [];
  16906. for (i = 0; i < polygon.vertices.length; i++) {
  16907. var j = (i + 1) % polygon.vertices.length;
  16908. var ti = types[i], tj = types[j];
  16909. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  16910. if (ti != BACK)
  16911. f.push(vi);
  16912. if (ti != FRONT)
  16913. b.push(ti != BACK ? vi.clone() : vi);
  16914. if ((ti | tj) == SPANNING) {
  16915. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  16916. var v = vi.interpolate(vj, t);
  16917. f.push(v);
  16918. b.push(v.clone());
  16919. }
  16920. }
  16921. if (f.length >= 3) {
  16922. var poly = new Polygon(f, polygon.shared);
  16923. if (poly.plane)
  16924. front.push(poly);
  16925. }
  16926. if (b.length >= 3) {
  16927. poly = new Polygon(b, polygon.shared);
  16928. if (poly.plane)
  16929. back.push(poly);
  16930. }
  16931. break;
  16932. }
  16933. };
  16934. Plane.EPSILON = 1e-5;
  16935. return Plane;
  16936. })();
  16937. var Polygon = (function () {
  16938. function Polygon(vertices, shared) {
  16939. this.vertices = vertices;
  16940. this.shared = shared;
  16941. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  16942. }
  16943. Polygon.prototype.clone = function () {
  16944. var vertices = this.vertices.map(function (v) {
  16945. return v.clone();
  16946. });
  16947. return new Polygon(vertices, this.shared);
  16948. };
  16949. Polygon.prototype.flip = function () {
  16950. this.vertices.reverse().map(function (v) {
  16951. v.flip();
  16952. });
  16953. this.plane.flip();
  16954. };
  16955. return Polygon;
  16956. })();
  16957. var Node = (function () {
  16958. function Node(polygons) {
  16959. this.plane = null;
  16960. this.front = null;
  16961. this.back = null;
  16962. this.polygons = [];
  16963. if (polygons) {
  16964. this.build(polygons);
  16965. }
  16966. }
  16967. Node.prototype.clone = function () {
  16968. var node = new Node();
  16969. node.plane = this.plane && this.plane.clone();
  16970. node.front = this.front && this.front.clone();
  16971. node.back = this.back && this.back.clone();
  16972. node.polygons = this.polygons.map(function (p) {
  16973. return p.clone();
  16974. });
  16975. return node;
  16976. };
  16977. Node.prototype.invert = function () {
  16978. for (var i = 0; i < this.polygons.length; i++) {
  16979. this.polygons[i].flip();
  16980. }
  16981. if (this.plane) {
  16982. this.plane.flip();
  16983. }
  16984. if (this.front) {
  16985. this.front.invert();
  16986. }
  16987. if (this.back) {
  16988. this.back.invert();
  16989. }
  16990. var temp = this.front;
  16991. this.front = this.back;
  16992. this.back = temp;
  16993. };
  16994. Node.prototype.clipPolygons = function (polygons) {
  16995. if (!this.plane)
  16996. return polygons.slice();
  16997. var front = [], back = [];
  16998. for (var i = 0; i < polygons.length; i++) {
  16999. this.plane.splitPolygon(polygons[i], front, back, front, back);
  17000. }
  17001. if (this.front) {
  17002. front = this.front.clipPolygons(front);
  17003. }
  17004. if (this.back) {
  17005. back = this.back.clipPolygons(back);
  17006. } else {
  17007. back = [];
  17008. }
  17009. return front.concat(back);
  17010. };
  17011. Node.prototype.clipTo = function (bsp) {
  17012. this.polygons = bsp.clipPolygons(this.polygons);
  17013. if (this.front)
  17014. this.front.clipTo(bsp);
  17015. if (this.back)
  17016. this.back.clipTo(bsp);
  17017. };
  17018. Node.prototype.allPolygons = function () {
  17019. var polygons = this.polygons.slice();
  17020. if (this.front)
  17021. polygons = polygons.concat(this.front.allPolygons());
  17022. if (this.back)
  17023. polygons = polygons.concat(this.back.allPolygons());
  17024. return polygons;
  17025. };
  17026. Node.prototype.build = function (polygons) {
  17027. if (!polygons.length)
  17028. return;
  17029. if (!this.plane)
  17030. this.plane = polygons[0].plane.clone();
  17031. var front = [], back = [];
  17032. for (var i = 0; i < polygons.length; i++) {
  17033. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  17034. }
  17035. if (front.length) {
  17036. if (!this.front)
  17037. this.front = new Node();
  17038. this.front.build(front);
  17039. }
  17040. if (back.length) {
  17041. if (!this.back)
  17042. this.back = new Node();
  17043. this.back.build(back);
  17044. }
  17045. };
  17046. return Node;
  17047. })();
  17048. var CSG = (function () {
  17049. function CSG() {
  17050. this.polygons = new Array();
  17051. }
  17052. CSG.FromMesh = function (mesh) {
  17053. var vertex, normal, uv, position, polygon, polygons = [], vertices;
  17054. if (mesh instanceof BABYLON.Mesh) {
  17055. mesh.computeWorldMatrix(true);
  17056. var matrix = mesh.getWorldMatrix();
  17057. var meshPosition = mesh.position.clone();
  17058. var meshRotation = mesh.rotation.clone();
  17059. var meshScaling = mesh.scaling.clone();
  17060. } else {
  17061. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  17062. }
  17063. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  17064. var subMeshes = mesh.subMeshes;
  17065. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  17066. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  17067. vertices = [];
  17068. for (var j = 0; j < 3; j++) {
  17069. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  17070. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  17071. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  17072. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  17073. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  17074. vertex = new Vertex(position, normal, uv);
  17075. vertices.push(vertex);
  17076. }
  17077. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  17078. if (polygon.plane)
  17079. polygons.push(polygon);
  17080. }
  17081. }
  17082. var csg = CSG.FromPolygons(polygons);
  17083. csg.matrix = matrix;
  17084. csg.position = meshPosition;
  17085. csg.rotation = meshRotation;
  17086. csg.scaling = meshScaling;
  17087. currentCSGMeshId++;
  17088. return csg;
  17089. };
  17090. CSG.FromPolygons = function (polygons) {
  17091. var csg = new BABYLON.CSG();
  17092. csg.polygons = polygons;
  17093. return csg;
  17094. };
  17095. CSG.prototype.clone = function () {
  17096. var csg = new BABYLON.CSG();
  17097. csg.polygons = this.polygons.map(function (p) {
  17098. return p.clone();
  17099. });
  17100. csg.copyTransformAttributes(this);
  17101. return csg;
  17102. };
  17103. CSG.prototype.toPolygons = function () {
  17104. return this.polygons;
  17105. };
  17106. CSG.prototype.union = function (csg) {
  17107. var a = new Node(this.clone().polygons);
  17108. var b = new Node(csg.clone().polygons);
  17109. a.clipTo(b);
  17110. b.clipTo(a);
  17111. b.invert();
  17112. b.clipTo(a);
  17113. b.invert();
  17114. a.build(b.allPolygons());
  17115. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  17116. };
  17117. CSG.prototype.unionInPlace = function (csg) {
  17118. var a = new Node(this.polygons);
  17119. var b = new Node(csg.polygons);
  17120. a.clipTo(b);
  17121. b.clipTo(a);
  17122. b.invert();
  17123. b.clipTo(a);
  17124. b.invert();
  17125. a.build(b.allPolygons());
  17126. this.polygons = a.allPolygons();
  17127. };
  17128. CSG.prototype.subtract = function (csg) {
  17129. var a = new Node(this.clone().polygons);
  17130. var b = new Node(csg.clone().polygons);
  17131. a.invert();
  17132. a.clipTo(b);
  17133. b.clipTo(a);
  17134. b.invert();
  17135. b.clipTo(a);
  17136. b.invert();
  17137. a.build(b.allPolygons());
  17138. a.invert();
  17139. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  17140. };
  17141. CSG.prototype.subtractInPlace = function (csg) {
  17142. var a = new Node(this.polygons);
  17143. var b = new Node(csg.polygons);
  17144. a.invert();
  17145. a.clipTo(b);
  17146. b.clipTo(a);
  17147. b.invert();
  17148. b.clipTo(a);
  17149. b.invert();
  17150. a.build(b.allPolygons());
  17151. a.invert();
  17152. this.polygons = a.allPolygons();
  17153. };
  17154. CSG.prototype.intersect = function (csg) {
  17155. var a = new Node(this.clone().polygons);
  17156. var b = new Node(csg.clone().polygons);
  17157. a.invert();
  17158. b.clipTo(a);
  17159. b.invert();
  17160. a.clipTo(b);
  17161. b.clipTo(a);
  17162. a.build(b.allPolygons());
  17163. a.invert();
  17164. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  17165. };
  17166. CSG.prototype.intersectInPlace = function (csg) {
  17167. var a = new Node(this.polygons);
  17168. var b = new Node(csg.polygons);
  17169. a.invert();
  17170. b.clipTo(a);
  17171. b.invert();
  17172. a.clipTo(b);
  17173. b.clipTo(a);
  17174. a.build(b.allPolygons());
  17175. a.invert();
  17176. this.polygons = a.allPolygons();
  17177. };
  17178. CSG.prototype.inverse = function () {
  17179. var csg = this.clone();
  17180. csg.inverseInPlace();
  17181. return csg;
  17182. };
  17183. CSG.prototype.inverseInPlace = function () {
  17184. this.polygons.map(function (p) {
  17185. p.flip();
  17186. });
  17187. };
  17188. CSG.prototype.copyTransformAttributes = function (csg) {
  17189. this.matrix = csg.matrix;
  17190. this.position = csg.position;
  17191. this.rotation = csg.rotation;
  17192. this.scaling = csg.scaling;
  17193. return this;
  17194. };
  17195. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  17196. var matrix = this.matrix.clone();
  17197. matrix.invert();
  17198. 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;
  17199. if (keepSubMeshes) {
  17200. polygons.sort(function (a, b) {
  17201. if (a.shared.meshId === b.shared.meshId) {
  17202. return a.shared.subMeshId - b.shared.subMeshId;
  17203. } else {
  17204. return a.shared.meshId - b.shared.meshId;
  17205. }
  17206. });
  17207. }
  17208. for (var i = 0, il = polygons.length; i < il; i++) {
  17209. polygon = polygons[i];
  17210. if (!subMesh_dict[polygon.shared.meshId]) {
  17211. subMesh_dict[polygon.shared.meshId] = {};
  17212. }
  17213. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  17214. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  17215. indexStart: +Infinity,
  17216. indexEnd: -Infinity,
  17217. materialIndex: polygon.shared.materialIndex
  17218. };
  17219. }
  17220. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  17221. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  17222. polygonIndices[0] = 0;
  17223. polygonIndices[1] = j - 1;
  17224. polygonIndices[2] = j;
  17225. for (var k = 0; k < 3; k++) {
  17226. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  17227. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  17228. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  17229. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  17230. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  17231. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  17232. if (!(typeof vertex_idx !== 'undefined' && normals[vertex_idx * 3] === localNormal.x && normals[vertex_idx * 3 + 1] === localNormal.y && normals[vertex_idx * 3 + 2] === localNormal.z && uvs[vertex_idx * 2] === uv.x && uvs[vertex_idx * 2 + 1] === uv.y)) {
  17233. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  17234. uvs.push(uv.x, uv.y);
  17235. normals.push(normal.x, normal.y, normal.z);
  17236. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  17237. }
  17238. indices.push(vertex_idx);
  17239. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  17240. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  17241. currentIndex++;
  17242. }
  17243. }
  17244. }
  17245. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  17246. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  17247. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  17248. mesh.setIndices(indices);
  17249. if (keepSubMeshes) {
  17250. var materialIndexOffset = 0, materialMaxIndex;
  17251. mesh.subMeshes.length = 0;
  17252. for (var m in subMesh_dict) {
  17253. materialMaxIndex = -1;
  17254. for (var sm in subMesh_dict[m]) {
  17255. subMesh_obj = subMesh_dict[m][sm];
  17256. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  17257. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  17258. }
  17259. materialIndexOffset += ++materialMaxIndex;
  17260. }
  17261. }
  17262. return mesh;
  17263. };
  17264. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  17265. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  17266. mesh.material = material;
  17267. mesh.position.copyFrom(this.position);
  17268. mesh.rotation.copyFrom(this.rotation);
  17269. mesh.scaling.copyFrom(this.scaling);
  17270. mesh.computeWorldMatrix(true);
  17271. return mesh;
  17272. };
  17273. return CSG;
  17274. })();
  17275. BABYLON.CSG = CSG;
  17276. })(BABYLON || (BABYLON = {}));
  17277. var __extends = this.__extends || function (d, b) {
  17278. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  17279. function __() { this.constructor = d; }
  17280. __.prototype = b.prototype;
  17281. d.prototype = new __();
  17282. };
  17283. var BABYLON;
  17284. (function (BABYLON) {
  17285. var OculusDistortionCorrectionPostProcess = (function (_super) {
  17286. __extends(OculusDistortionCorrectionPostProcess, _super);
  17287. function OculusDistortionCorrectionPostProcess(name, camera, isRightEye, cameraSettings) {
  17288. var _this = this;
  17289. _super.call(this, name, "oculusDistortionCorrection", [
  17290. 'LensCenter',
  17291. 'Scale',
  17292. 'ScaleIn',
  17293. 'HmdWarpParam'
  17294. ], null, cameraSettings.PostProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  17295. this._isRightEye = isRightEye;
  17296. this._distortionFactors = cameraSettings.DistortionK;
  17297. this._postProcessScaleFactor = cameraSettings.PostProcessScaleFactor;
  17298. this._lensCenterOffset = cameraSettings.LensCenterOffset;
  17299. this.onSizeChanged = function () {
  17300. _this.aspectRatio = _this.width * .5 / _this.height;
  17301. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  17302. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  17303. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  17304. };
  17305. this.onApply = function (effect) {
  17306. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  17307. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  17308. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  17309. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  17310. };
  17311. }
  17312. return OculusDistortionCorrectionPostProcess;
  17313. })(BABYLON.PostProcess);
  17314. BABYLON.OculusDistortionCorrectionPostProcess = OculusDistortionCorrectionPostProcess;
  17315. })(BABYLON || (BABYLON = {}));
  17316. var BABYLON;
  17317. (function (BABYLON) {
  17318. (function (JoystickAxis) {
  17319. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  17320. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  17321. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  17322. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  17323. var JoystickAxis = BABYLON.JoystickAxis;
  17324. var VirtualJoystick = (function () {
  17325. function VirtualJoystick(leftJoystick) {
  17326. var _this = this;
  17327. if (leftJoystick) {
  17328. this._leftJoystick = true;
  17329. } else {
  17330. this._leftJoystick = false;
  17331. }
  17332. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  17333. VirtualJoystick._globalJoystickIndex++;
  17334. this._axisTargetedByLeftAndRight = 0 /* X */;
  17335. this._axisTargetedByUpAndDown = 1 /* Y */;
  17336. this.reverseLeftRight = false;
  17337. this.reverseUpDown = false;
  17338. this._touches = new BABYLON.VirtualJoystick.Collection();
  17339. this.deltaPosition = BABYLON.Vector3.Zero();
  17340. this._joystickSensibility = 25;
  17341. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  17342. this._rotationSpeed = 25;
  17343. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  17344. this._rotateOnAxisRelativeToMesh = false;
  17345. if (!VirtualJoystick.vjCanvas) {
  17346. window.addEventListener("resize", function () {
  17347. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  17348. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  17349. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  17350. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  17351. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  17352. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  17353. }, false);
  17354. VirtualJoystick.vjCanvas = document.createElement("canvas");
  17355. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  17356. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  17357. VirtualJoystick.vjCanvas.width = window.innerWidth;
  17358. VirtualJoystick.vjCanvas.height = window.innerHeight;
  17359. VirtualJoystick.vjCanvas.style.width = "100%";
  17360. VirtualJoystick.vjCanvas.style.height = "100%";
  17361. VirtualJoystick.vjCanvas.style.position = "absolute";
  17362. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  17363. VirtualJoystick.vjCanvas.style.top = "0px";
  17364. VirtualJoystick.vjCanvas.style.left = "0px";
  17365. VirtualJoystick.vjCanvas.style.zIndex = "5";
  17366. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  17367. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  17368. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  17369. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  17370. document.body.appendChild(VirtualJoystick.vjCanvas);
  17371. }
  17372. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  17373. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  17374. this.pressed = false;
  17375. this._joystickColor = "cyan";
  17376. this._joystickPointerID = -1;
  17377. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  17378. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  17379. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  17380. VirtualJoystick.vjCanvas.addEventListener('pointerdown', function (evt) {
  17381. _this._onPointerDown(evt);
  17382. }, false);
  17383. VirtualJoystick.vjCanvas.addEventListener('pointermove', function (evt) {
  17384. _this._onPointerMove(evt);
  17385. }, false);
  17386. VirtualJoystick.vjCanvas.addEventListener('pointerup', function (evt) {
  17387. _this._onPointerUp(evt);
  17388. }, false);
  17389. VirtualJoystick.vjCanvas.addEventListener('pointerout', function (evt) {
  17390. _this._onPointerUp(evt);
  17391. }, false);
  17392. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  17393. evt.preventDefault();
  17394. }, false);
  17395. requestAnimationFrame(function () {
  17396. _this._drawVirtualJoystick();
  17397. });
  17398. }
  17399. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  17400. this._joystickSensibility = newJoystickSensibility;
  17401. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  17402. };
  17403. VirtualJoystick.prototype._onPointerDown = function (e) {
  17404. var positionOnScreenCondition;
  17405. e.preventDefault();
  17406. if (this._leftJoystick === true) {
  17407. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  17408. } else {
  17409. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  17410. }
  17411. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  17412. this._joystickPointerID = e.pointerId;
  17413. this._joystickPointerStartPos.x = e.clientX;
  17414. this._joystickPointerStartPos.y = e.clientY;
  17415. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  17416. this._deltaJoystickVector.x = 0;
  17417. this._deltaJoystickVector.y = 0;
  17418. this.pressed = true;
  17419. this._touches.add(e.pointerId.toString(), e);
  17420. } else {
  17421. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  17422. this._action();
  17423. this._touches.add(e.pointerId.toString(), e);
  17424. }
  17425. }
  17426. };
  17427. VirtualJoystick.prototype._onPointerMove = function (e) {
  17428. if (this._joystickPointerID == e.pointerId) {
  17429. this._joystickPointerPos.x = e.clientX;
  17430. this._joystickPointerPos.y = e.clientY;
  17431. this._deltaJoystickVector = this._joystickPointerPos.clone();
  17432. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  17433. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  17434. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  17435. switch (this._axisTargetedByLeftAndRight) {
  17436. case 0 /* X */:
  17437. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  17438. break;
  17439. case 1 /* Y */:
  17440. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  17441. break;
  17442. case 2 /* Z */:
  17443. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  17444. break;
  17445. }
  17446. var directionUpDown = this.reverseUpDown ? 1 : -1;
  17447. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  17448. switch (this._axisTargetedByUpAndDown) {
  17449. case 0 /* X */:
  17450. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  17451. break;
  17452. case 1 /* Y */:
  17453. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  17454. break;
  17455. case 2 /* Z */:
  17456. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  17457. break;
  17458. }
  17459. } else {
  17460. if (this._touches.item(e.pointerId.toString())) {
  17461. this._touches.item(e.pointerId.toString()).x = e.clientX;
  17462. this._touches.item(e.pointerId.toString()).y = e.clientY;
  17463. }
  17464. }
  17465. };
  17466. VirtualJoystick.prototype._onPointerUp = function (e) {
  17467. this._clearCanvas();
  17468. if (this._joystickPointerID == e.pointerId) {
  17469. this._joystickPointerID = -1;
  17470. this.pressed = false;
  17471. }
  17472. this._deltaJoystickVector.x = 0;
  17473. this._deltaJoystickVector.y = 0;
  17474. this._touches.remove(e.pointerId.toString());
  17475. };
  17476. /**
  17477. * Change the color of the virtual joystick
  17478. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  17479. */
  17480. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  17481. this._joystickColor = newColor;
  17482. };
  17483. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  17484. this._action = action;
  17485. };
  17486. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  17487. switch (axis) {
  17488. case 0 /* X */:
  17489. case 1 /* Y */:
  17490. case 2 /* Z */:
  17491. this._axisTargetedByLeftAndRight = axis;
  17492. break;
  17493. default:
  17494. this._axisTargetedByLeftAndRight = 0 /* X */;
  17495. break;
  17496. }
  17497. };
  17498. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  17499. switch (axis) {
  17500. case 0 /* X */:
  17501. case 1 /* Y */:
  17502. case 2 /* Z */:
  17503. this._axisTargetedByUpAndDown = axis;
  17504. break;
  17505. default:
  17506. this._axisTargetedByUpAndDown = 1 /* Y */;
  17507. break;
  17508. }
  17509. };
  17510. VirtualJoystick.prototype._clearCanvas = function () {
  17511. if (this._leftJoystick) {
  17512. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  17513. } else {
  17514. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  17515. }
  17516. };
  17517. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  17518. var _this = this;
  17519. if (this.pressed) {
  17520. this._clearCanvas();
  17521. this._touches.forEach(function (touch) {
  17522. if (touch.pointerId === _this._joystickPointerID) {
  17523. VirtualJoystick.vjCanvasContext.beginPath();
  17524. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  17525. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  17526. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  17527. VirtualJoystick.vjCanvasContext.stroke();
  17528. VirtualJoystick.vjCanvasContext.beginPath();
  17529. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  17530. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  17531. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  17532. VirtualJoystick.vjCanvasContext.stroke();
  17533. VirtualJoystick.vjCanvasContext.beginPath();
  17534. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  17535. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  17536. VirtualJoystick.vjCanvasContext.stroke();
  17537. } else {
  17538. VirtualJoystick.vjCanvasContext.beginPath();
  17539. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  17540. VirtualJoystick.vjCanvasContext.beginPath();
  17541. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  17542. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  17543. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  17544. VirtualJoystick.vjCanvasContext.stroke();
  17545. }
  17546. ;
  17547. });
  17548. }
  17549. requestAnimationFrame(function () {
  17550. _this._drawVirtualJoystick();
  17551. });
  17552. };
  17553. VirtualJoystick.prototype.releaseCanvas = function () {
  17554. if (VirtualJoystick.vjCanvas) {
  17555. document.body.removeChild(VirtualJoystick.vjCanvas);
  17556. VirtualJoystick.vjCanvas = null;
  17557. }
  17558. };
  17559. VirtualJoystick._globalJoystickIndex = 0;
  17560. return VirtualJoystick;
  17561. })();
  17562. BABYLON.VirtualJoystick = VirtualJoystick;
  17563. })(BABYLON || (BABYLON = {}));
  17564. var BABYLON;
  17565. (function (BABYLON) {
  17566. (function (VirtualJoystick) {
  17567. var Collection = (function () {
  17568. function Collection() {
  17569. this._count = 0;
  17570. this._collection = new Array();
  17571. }
  17572. Collection.prototype.Count = function () {
  17573. return this._count;
  17574. };
  17575. Collection.prototype.add = function (key, item) {
  17576. if (this._collection[key] != undefined) {
  17577. return undefined;
  17578. }
  17579. this._collection[key] = item;
  17580. return ++this._count;
  17581. };
  17582. Collection.prototype.remove = function (key) {
  17583. if (this._collection[key] == undefined) {
  17584. return undefined;
  17585. }
  17586. delete this._collection[key];
  17587. return --this._count;
  17588. };
  17589. Collection.prototype.item = function (key) {
  17590. return this._collection[key];
  17591. };
  17592. Collection.prototype.forEach = function (block) {
  17593. var key;
  17594. for (key in this._collection) {
  17595. if (this._collection.hasOwnProperty(key)) {
  17596. block(this._collection[key]);
  17597. }
  17598. }
  17599. };
  17600. return Collection;
  17601. })();
  17602. VirtualJoystick.Collection = Collection;
  17603. })(BABYLON.VirtualJoystick || (BABYLON.VirtualJoystick = {}));
  17604. var VirtualJoystick = BABYLON.VirtualJoystick;
  17605. })(BABYLON || (BABYLON = {}));
  17606. var __extends = this.__extends || function (d, b) {
  17607. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  17608. function __() { this.constructor = d; }
  17609. __.prototype = b.prototype;
  17610. d.prototype = new __();
  17611. };
  17612. var BABYLON;
  17613. (function (BABYLON) {
  17614. var OculusRiftDevKit2013_Metric = {
  17615. HResolution: 1280,
  17616. VResolution: 800,
  17617. HScreenSize: 0.149759993,
  17618. VScreenSize: 0.0935999975,
  17619. VScreenCenter: 0.0467999987,
  17620. EyeToScreenDistance: 0.0410000011,
  17621. LensSeparationDistance: 0.0635000020,
  17622. InterpupillaryDistance: 0.0640000030,
  17623. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  17624. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  17625. PostProcessScaleFactor: 1.714605507808412,
  17626. LensCenterOffset: 0.151976421
  17627. };
  17628. var _OculusInnerCamera = (function (_super) {
  17629. __extends(_OculusInnerCamera, _super);
  17630. function _OculusInnerCamera(name, position, scene, isLeftEye) {
  17631. _super.call(this, name, position, scene);
  17632. this._workMatrix = new BABYLON.Matrix();
  17633. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  17634. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  17635. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  17636. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  17637. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  17638. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  17639. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  17640. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  17641. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  17642. }
  17643. _OculusInnerCamera.prototype.getProjectionMatrix = function () {
  17644. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  17645. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  17646. return this._projectionMatrix;
  17647. };
  17648. _OculusInnerCamera.prototype._getViewMatrix = function () {
  17649. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  17650. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  17651. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  17652. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  17653. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  17654. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  17655. return this._viewMatrix;
  17656. };
  17657. return _OculusInnerCamera;
  17658. })(BABYLON.FreeCamera);
  17659. var OculusCamera = (function (_super) {
  17660. __extends(OculusCamera, _super);
  17661. function OculusCamera(name, position, scene) {
  17662. _super.call(this, name, position, scene);
  17663. this._leftCamera = new _OculusInnerCamera(name + "_left", position.clone(), scene, true);
  17664. this._rightCamera = new _OculusInnerCamera(name + "_right", position.clone(), scene, false);
  17665. this.subCameras.push(this._leftCamera);
  17666. this.subCameras.push(this._rightCamera);
  17667. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  17668. }
  17669. OculusCamera.prototype._update = function () {
  17670. this._leftCamera.position.copyFrom(this.position);
  17671. this._rightCamera.position.copyFrom(this.position);
  17672. this._updateCamera(this._leftCamera);
  17673. this._updateCamera(this._rightCamera);
  17674. _super.prototype._update.call(this);
  17675. };
  17676. OculusCamera.prototype._updateCamera = function (camera) {
  17677. camera.minZ = this.minZ;
  17678. camera.maxZ = this.maxZ;
  17679. camera.rotation.x = this.rotation.x;
  17680. camera.rotation.y = this.rotation.y;
  17681. camera.rotation.z = this.rotation.z;
  17682. };
  17683. OculusCamera.prototype._onOrientationEvent = function (evt) {
  17684. var yaw = evt.alpha / 180 * Math.PI;
  17685. var pitch = evt.beta / 180 * Math.PI;
  17686. var roll = evt.gamma / 180 * Math.PI;
  17687. if (!this._offsetOrientation) {
  17688. this._offsetOrientation = {
  17689. yaw: yaw,
  17690. pitch: pitch,
  17691. roll: roll
  17692. };
  17693. return;
  17694. } else {
  17695. this.rotation.y += yaw - this._offsetOrientation.yaw;
  17696. this.rotation.x += pitch - this._offsetOrientation.pitch;
  17697. this.rotation.z += this._offsetOrientation.roll - roll;
  17698. this._offsetOrientation.yaw = yaw;
  17699. this._offsetOrientation.pitch = pitch;
  17700. this._offsetOrientation.roll = roll;
  17701. }
  17702. };
  17703. OculusCamera.prototype.attachControl = function (element, noPreventDefault) {
  17704. _super.prototype.attachControl.call(this, element, noPreventDefault);
  17705. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  17706. };
  17707. OculusCamera.prototype.detachControl = function (element) {
  17708. _super.prototype.detachControl.call(this, element);
  17709. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  17710. };
  17711. return OculusCamera;
  17712. })(BABYLON.FreeCamera);
  17713. BABYLON.OculusCamera = OculusCamera;
  17714. })(BABYLON || (BABYLON = {}));
  17715. var __extends = this.__extends || function (d, b) {
  17716. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  17717. function __() { this.constructor = d; }
  17718. __.prototype = b.prototype;
  17719. d.prototype = new __();
  17720. };
  17721. var BABYLON;
  17722. (function (BABYLON) {
  17723. var OculusRiftDevKit2013_Metric = {
  17724. HResolution: 1280,
  17725. VResolution: 800,
  17726. HScreenSize: 0.149759993,
  17727. VScreenSize: 0.0935999975,
  17728. VScreenCenter: 0.0467999987,
  17729. EyeToScreenDistance: 0.0410000011,
  17730. LensSeparationDistance: 0.0635000020,
  17731. InterpupillaryDistance: 0.0640000030,
  17732. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  17733. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  17734. PostProcessScaleFactor: 1.714605507808412,
  17735. LensCenterOffset: 0.151976421
  17736. };
  17737. var _OculusInnerGamepadCamera = (function (_super) {
  17738. __extends(_OculusInnerGamepadCamera, _super);
  17739. function _OculusInnerGamepadCamera(name, position, scene, isLeftEye) {
  17740. _super.call(this, name, position, scene);
  17741. this._workMatrix = new BABYLON.Matrix();
  17742. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  17743. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  17744. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  17745. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  17746. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  17747. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  17748. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  17749. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  17750. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  17751. }
  17752. _OculusInnerGamepadCamera.prototype.getProjectionMatrix = function () {
  17753. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  17754. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  17755. return this._projectionMatrix;
  17756. };
  17757. _OculusInnerGamepadCamera.prototype._getViewMatrix = function () {
  17758. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  17759. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  17760. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  17761. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  17762. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  17763. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  17764. return this._viewMatrix;
  17765. };
  17766. return _OculusInnerGamepadCamera;
  17767. })(BABYLON.FreeCamera);
  17768. var OculusGamepadCamera = (function (_super) {
  17769. __extends(OculusGamepadCamera, _super);
  17770. function OculusGamepadCamera(name, position, scene) {
  17771. var _this = this;
  17772. _super.call(this, name, position, scene);
  17773. this.angularSensibility = 200;
  17774. this.moveSensibility = 75;
  17775. this._leftCamera = new _OculusInnerGamepadCamera(name + "_left", position.clone(), scene, true);
  17776. this._rightCamera = new _OculusInnerGamepadCamera(name + "_right", position.clone(), scene, false);
  17777. this.subCameras.push(this._leftCamera);
  17778. this.subCameras.push(this._rightCamera);
  17779. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  17780. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  17781. _this._onNewGameConnected(gamepad);
  17782. });
  17783. }
  17784. OculusGamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  17785. if (gamepad.index === 0) {
  17786. this._gamepad = gamepad;
  17787. }
  17788. };
  17789. OculusGamepadCamera.prototype._update = function () {
  17790. this._leftCamera.position.copyFrom(this.position);
  17791. this._rightCamera.position.copyFrom(this.position);
  17792. this._updateCamera(this._leftCamera);
  17793. this._updateCamera(this._rightCamera);
  17794. _super.prototype._update.call(this);
  17795. };
  17796. OculusGamepadCamera.prototype._checkInputs = function () {
  17797. if (!this._gamepad) {
  17798. return;
  17799. }
  17800. var LSValues = this._gamepad.leftStick;
  17801. var normalizedLX = LSValues.x / this.moveSensibility;
  17802. var normalizedLY = LSValues.y / this.moveSensibility;
  17803. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  17804. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  17805. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  17806. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x, 0, -LSValues.y), cameraTransform);
  17807. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  17808. };
  17809. OculusGamepadCamera.prototype._updateCamera = function (camera) {
  17810. camera.minZ = this.minZ;
  17811. camera.maxZ = this.maxZ;
  17812. camera.rotation.x = this.rotation.x;
  17813. camera.rotation.y = this.rotation.y;
  17814. camera.rotation.z = this.rotation.z;
  17815. };
  17816. OculusGamepadCamera.prototype._onOrientationEvent = function (evt) {
  17817. var yaw = evt.alpha / 180 * Math.PI;
  17818. var pitch = evt.beta / 180 * Math.PI;
  17819. var roll = evt.gamma / 180 * Math.PI;
  17820. if (!this._offsetOrientation) {
  17821. this._offsetOrientation = {
  17822. yaw: yaw,
  17823. pitch: pitch,
  17824. roll: roll
  17825. };
  17826. return;
  17827. } else {
  17828. this.rotation.y += yaw - this._offsetOrientation.yaw;
  17829. this.rotation.x += pitch - this._offsetOrientation.pitch;
  17830. this.rotation.z += this._offsetOrientation.roll - roll;
  17831. this._offsetOrientation.yaw = yaw;
  17832. this._offsetOrientation.pitch = pitch;
  17833. this._offsetOrientation.roll = roll;
  17834. }
  17835. };
  17836. OculusGamepadCamera.prototype.attachControl = function (element, noPreventDefault) {
  17837. _super.prototype.attachControl.call(this, element, noPreventDefault);
  17838. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  17839. };
  17840. OculusGamepadCamera.prototype.detachControl = function (element) {
  17841. _super.prototype.detachControl.call(this, element);
  17842. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  17843. };
  17844. OculusGamepadCamera.prototype.dispose = function () {
  17845. this._gamepads.dispose();
  17846. _super.prototype.dispose.call(this);
  17847. };
  17848. return OculusGamepadCamera;
  17849. })(BABYLON.FreeCamera);
  17850. BABYLON.OculusGamepadCamera = OculusGamepadCamera;
  17851. })(BABYLON || (BABYLON = {}));
  17852. var __extends = this.__extends || function (d, b) {
  17853. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  17854. function __() { this.constructor = d; }
  17855. __.prototype = b.prototype;
  17856. d.prototype = new __();
  17857. };
  17858. var BABYLON;
  17859. (function (BABYLON) {
  17860. var VirtualJoysticksCamera = (function (_super) {
  17861. __extends(VirtualJoysticksCamera, _super);
  17862. function VirtualJoysticksCamera(name, position, scene) {
  17863. _super.call(this, name, position, scene);
  17864. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  17865. this._leftjoystick.setAxisForUpDown(2 /* Z */);
  17866. this._leftjoystick.setAxisForLeftRight(0 /* X */);
  17867. this._leftjoystick.setJoystickSensibility(0.15);
  17868. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  17869. this._rightjoystick.setAxisForUpDown(0 /* X */);
  17870. this._rightjoystick.setAxisForLeftRight(1 /* Y */);
  17871. this._rightjoystick.reverseUpDown = true;
  17872. this._rightjoystick.setJoystickSensibility(0.05);
  17873. this._rightjoystick.setJoystickColor("yellow");
  17874. }
  17875. VirtualJoysticksCamera.prototype._checkInputs = function () {
  17876. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  17877. var deltaTransform = BABYLON.Vector3.TransformCoordinates(this._leftjoystick.deltaPosition, cameraTransform);
  17878. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  17879. this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  17880. if (!this._leftjoystick.pressed) {
  17881. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  17882. }
  17883. if (!this._rightjoystick.pressed) {
  17884. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  17885. }
  17886. };
  17887. VirtualJoysticksCamera.prototype.dispose = function () {
  17888. this._leftjoystick.releaseCanvas();
  17889. _super.prototype.dispose.call(this);
  17890. };
  17891. return VirtualJoysticksCamera;
  17892. })(BABYLON.FreeCamera);
  17893. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  17894. })(BABYLON || (BABYLON = {}));
  17895. var __extends = this.__extends || function (d, b) {
  17896. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  17897. function __() { this.constructor = d; }
  17898. __.prototype = b.prototype;
  17899. d.prototype = new __();
  17900. };
  17901. var BABYLON;
  17902. (function (BABYLON) {
  17903. var ShaderMaterial = (function (_super) {
  17904. __extends(ShaderMaterial, _super);
  17905. function ShaderMaterial(name, scene, shaderPath, options) {
  17906. _super.call(this, name, scene);
  17907. this._textures = new Array();
  17908. this._floats = new Array();
  17909. this._floatsArrays = {};
  17910. this._colors3 = new Array();
  17911. this._colors4 = new Array();
  17912. this._vectors2 = new Array();
  17913. this._vectors3 = new Array();
  17914. this._matrices = new Array();
  17915. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  17916. this._shaderPath = shaderPath;
  17917. options.needAlphaBlending = options.needAlphaBlending || false;
  17918. options.needAlphaTesting = options.needAlphaTesting || false;
  17919. options.attributes = options.attributes || ["position", "normal", "uv"];
  17920. options.uniforms = options.uniforms || ["worldViewProjection"];
  17921. options.samplers = options.samplers || [];
  17922. this._options = options;
  17923. }
  17924. ShaderMaterial.prototype.needAlphaBlending = function () {
  17925. return this._options.needAlphaBlending;
  17926. };
  17927. ShaderMaterial.prototype.needAlphaTesting = function () {
  17928. return this._options.needAlphaTesting;
  17929. };
  17930. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  17931. if (this._options.uniforms.indexOf(uniformName) === -1) {
  17932. this._options.uniforms.push(uniformName);
  17933. }
  17934. };
  17935. ShaderMaterial.prototype.setTexture = function (name, texture) {
  17936. if (this._options.samplers.indexOf(name) === -1) {
  17937. this._options.samplers.push(name);
  17938. }
  17939. this._textures[name] = texture;
  17940. return this;
  17941. };
  17942. ShaderMaterial.prototype.setFloat = function (name, value) {
  17943. this._checkUniform(name);
  17944. this._floats[name] = value;
  17945. return this;
  17946. };
  17947. ShaderMaterial.prototype.setFloats = function (name, value) {
  17948. this._checkUniform(name);
  17949. this._floatsArrays[name] = value;
  17950. return this;
  17951. };
  17952. ShaderMaterial.prototype.setColor3 = function (name, value) {
  17953. this._checkUniform(name);
  17954. this._colors3[name] = value;
  17955. return this;
  17956. };
  17957. ShaderMaterial.prototype.setColor4 = function (name, value) {
  17958. this._checkUniform(name);
  17959. this._colors4[name] = value;
  17960. return this;
  17961. };
  17962. ShaderMaterial.prototype.setVector2 = function (name, value) {
  17963. this._checkUniform(name);
  17964. this._vectors2[name] = value;
  17965. return this;
  17966. };
  17967. ShaderMaterial.prototype.setVector3 = function (name, value) {
  17968. this._checkUniform(name);
  17969. this._vectors3[name] = value;
  17970. return this;
  17971. };
  17972. ShaderMaterial.prototype.setMatrix = function (name, value) {
  17973. this._checkUniform(name);
  17974. this._matrices[name] = value;
  17975. return this;
  17976. };
  17977. ShaderMaterial.prototype.isReady = function () {
  17978. var engine = this.getScene().getEngine();
  17979. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, "", null, this.onCompiled, this.onError);
  17980. if (!this._effect.isReady()) {
  17981. return false;
  17982. }
  17983. return true;
  17984. };
  17985. ShaderMaterial.prototype.bind = function (world) {
  17986. if (this._options.uniforms.indexOf("world") !== -1) {
  17987. this._effect.setMatrix("world", world);
  17988. }
  17989. if (this._options.uniforms.indexOf("view") !== -1) {
  17990. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  17991. }
  17992. if (this._options.uniforms.indexOf("worldView") !== -1) {
  17993. world.multiplyToRef(this.getScene().getViewMatrix(), this._cachedWorldViewMatrix);
  17994. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  17995. }
  17996. if (this._options.uniforms.indexOf("projection") !== -1) {
  17997. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  17998. }
  17999. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  18000. this._effect.setMatrix("worldViewProjection", world.multiply(this.getScene().getTransformMatrix()));
  18001. }
  18002. for (var name in this._textures) {
  18003. this._effect.setTexture(name, this._textures[name]);
  18004. }
  18005. for (name in this._floats) {
  18006. this._effect.setFloat(name, this._floats[name]);
  18007. }
  18008. for (name in this._floatsArrays) {
  18009. this._effect.setArray(name, this._floatsArrays[name]);
  18010. }
  18011. for (name in this._colors3) {
  18012. this._effect.setColor3(name, this._colors3[name]);
  18013. }
  18014. for (name in this._colors4) {
  18015. var color = this._colors4[name];
  18016. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  18017. }
  18018. for (name in this._vectors2) {
  18019. this._effect.setVector2(name, this._vectors2[name]);
  18020. }
  18021. for (name in this._vectors3) {
  18022. this._effect.setVector3(name, this._vectors3[name]);
  18023. }
  18024. for (name in this._matrices) {
  18025. this._effect.setMatrix(name, this._matrices[name]);
  18026. }
  18027. };
  18028. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  18029. for (var name in this._textures) {
  18030. this._textures[name].dispose();
  18031. }
  18032. this._textures = [];
  18033. _super.prototype.dispose.call(this, forceDisposeEffect);
  18034. };
  18035. return ShaderMaterial;
  18036. })(BABYLON.Material);
  18037. BABYLON.ShaderMaterial = ShaderMaterial;
  18038. })(BABYLON || (BABYLON = {}));
  18039. var BABYLON;
  18040. (function (BABYLON) {
  18041. var VertexData = (function () {
  18042. function VertexData() {
  18043. }
  18044. VertexData.prototype.set = function (data, kind) {
  18045. switch (kind) {
  18046. case BABYLON.VertexBuffer.PositionKind:
  18047. this.positions = data;
  18048. break;
  18049. case BABYLON.VertexBuffer.NormalKind:
  18050. this.normals = data;
  18051. break;
  18052. case BABYLON.VertexBuffer.UVKind:
  18053. this.uvs = data;
  18054. break;
  18055. case BABYLON.VertexBuffer.UV2Kind:
  18056. this.uv2s = data;
  18057. break;
  18058. case BABYLON.VertexBuffer.ColorKind:
  18059. this.colors = data;
  18060. break;
  18061. case BABYLON.VertexBuffer.MatricesIndicesKind:
  18062. this.matricesIndices = data;
  18063. break;
  18064. case BABYLON.VertexBuffer.MatricesWeightsKind:
  18065. this.matricesWeights = data;
  18066. break;
  18067. }
  18068. };
  18069. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  18070. this._applyTo(mesh, updatable);
  18071. };
  18072. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  18073. this._applyTo(geometry, updatable);
  18074. };
  18075. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  18076. this._update(mesh);
  18077. };
  18078. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  18079. this._update(geometry);
  18080. };
  18081. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  18082. if (this.positions) {
  18083. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  18084. }
  18085. if (this.normals) {
  18086. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  18087. }
  18088. if (this.uvs) {
  18089. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  18090. }
  18091. if (this.uv2s) {
  18092. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updatable);
  18093. }
  18094. if (this.colors) {
  18095. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  18096. }
  18097. if (this.matricesIndices) {
  18098. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  18099. }
  18100. if (this.matricesWeights) {
  18101. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  18102. }
  18103. if (this.indices) {
  18104. meshOrGeometry.setIndices(this.indices);
  18105. }
  18106. };
  18107. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  18108. if (this.positions) {
  18109. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  18110. }
  18111. if (this.normals) {
  18112. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  18113. }
  18114. if (this.uvs) {
  18115. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  18116. }
  18117. if (this.uv2s) {
  18118. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updateExtends, makeItUnique);
  18119. }
  18120. if (this.colors) {
  18121. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  18122. }
  18123. if (this.matricesIndices) {
  18124. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  18125. }
  18126. if (this.matricesWeights) {
  18127. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  18128. }
  18129. if (this.indices) {
  18130. meshOrGeometry.setIndices(this.indices);
  18131. }
  18132. };
  18133. VertexData.prototype.transform = function (matrix) {
  18134. var transformed = BABYLON.Vector3.Zero();
  18135. if (this.positions) {
  18136. var position = BABYLON.Vector3.Zero();
  18137. for (var index = 0; index < this.positions.length; index += 3) {
  18138. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  18139. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  18140. this.positions[index] = transformed.x;
  18141. this.positions[index + 1] = transformed.y;
  18142. this.positions[index + 2] = transformed.z;
  18143. }
  18144. }
  18145. if (this.normals) {
  18146. var normal = BABYLON.Vector3.Zero();
  18147. for (index = 0; index < this.normals.length; index += 3) {
  18148. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  18149. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  18150. this.normals[index] = transformed.x;
  18151. this.normals[index + 1] = transformed.y;
  18152. this.normals[index + 2] = transformed.z;
  18153. }
  18154. }
  18155. };
  18156. VertexData.prototype.merge = function (other) {
  18157. if (other.indices) {
  18158. if (!this.indices) {
  18159. this.indices = [];
  18160. }
  18161. var offset = this.positions ? this.positions.length / 3 : 0;
  18162. for (var index = 0; index < other.indices.length; index++) {
  18163. this.indices.push(other.indices[index] + offset);
  18164. }
  18165. }
  18166. if (other.positions) {
  18167. if (!this.positions) {
  18168. this.positions = [];
  18169. }
  18170. for (index = 0; index < other.positions.length; index++) {
  18171. this.positions.push(other.positions[index]);
  18172. }
  18173. }
  18174. if (other.normals) {
  18175. if (!this.normals) {
  18176. this.normals = [];
  18177. }
  18178. for (index = 0; index < other.normals.length; index++) {
  18179. this.normals.push(other.normals[index]);
  18180. }
  18181. }
  18182. if (other.uvs) {
  18183. if (!this.uvs) {
  18184. this.uvs = [];
  18185. }
  18186. for (index = 0; index < other.uvs.length; index++) {
  18187. this.uvs.push(other.uvs[index]);
  18188. }
  18189. }
  18190. if (other.uv2s) {
  18191. if (!this.uv2s) {
  18192. this.uv2s = [];
  18193. }
  18194. for (index = 0; index < other.uv2s.length; index++) {
  18195. this.uv2s.push(other.uv2s[index]);
  18196. }
  18197. }
  18198. if (other.matricesIndices) {
  18199. if (!this.matricesIndices) {
  18200. this.matricesIndices = [];
  18201. }
  18202. for (index = 0; index < other.matricesIndices.length; index++) {
  18203. this.matricesIndices.push(other.matricesIndices[index]);
  18204. }
  18205. }
  18206. if (other.matricesWeights) {
  18207. if (!this.matricesWeights) {
  18208. this.matricesWeights = [];
  18209. }
  18210. for (index = 0; index < other.matricesWeights.length; index++) {
  18211. this.matricesWeights.push(other.matricesWeights[index]);
  18212. }
  18213. }
  18214. if (other.colors) {
  18215. if (!this.colors) {
  18216. this.colors = [];
  18217. }
  18218. for (index = 0; index < other.colors.length; index++) {
  18219. this.colors.push(other.colors[index]);
  18220. }
  18221. }
  18222. };
  18223. VertexData.ExtractFromMesh = function (mesh) {
  18224. return VertexData._ExtractFrom(mesh);
  18225. };
  18226. VertexData.ExtractFromGeometry = function (geometry) {
  18227. return VertexData._ExtractFrom(geometry);
  18228. };
  18229. VertexData._ExtractFrom = function (meshOrGeometry) {
  18230. var result = new BABYLON.VertexData();
  18231. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  18232. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18233. }
  18234. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  18235. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18236. }
  18237. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  18238. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind);
  18239. }
  18240. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  18241. result.uv2s = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  18242. }
  18243. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  18244. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  18245. }
  18246. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  18247. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  18248. }
  18249. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  18250. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  18251. }
  18252. result.indices = meshOrGeometry.getIndices();
  18253. return result;
  18254. };
  18255. VertexData.CreateBox = function (size) {
  18256. var normalsSource = [
  18257. new BABYLON.Vector3(0, 0, 1),
  18258. new BABYLON.Vector3(0, 0, -1),
  18259. new BABYLON.Vector3(1, 0, 0),
  18260. new BABYLON.Vector3(-1, 0, 0),
  18261. new BABYLON.Vector3(0, 1, 0),
  18262. new BABYLON.Vector3(0, -1, 0)
  18263. ];
  18264. var indices = [];
  18265. var positions = [];
  18266. var normals = [];
  18267. var uvs = [];
  18268. size = size || 1;
  18269. for (var index = 0; index < normalsSource.length; index++) {
  18270. var normal = normalsSource[index];
  18271. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  18272. var side2 = BABYLON.Vector3.Cross(normal, side1);
  18273. var verticesLength = positions.length / 3;
  18274. indices.push(verticesLength);
  18275. indices.push(verticesLength + 1);
  18276. indices.push(verticesLength + 2);
  18277. indices.push(verticesLength);
  18278. indices.push(verticesLength + 2);
  18279. indices.push(verticesLength + 3);
  18280. var vertex = normal.subtract(side1).subtract(side2).scale(size / 2);
  18281. positions.push(vertex.x, vertex.y, vertex.z);
  18282. normals.push(normal.x, normal.y, normal.z);
  18283. uvs.push(1.0, 1.0);
  18284. vertex = normal.subtract(side1).add(side2).scale(size / 2);
  18285. positions.push(vertex.x, vertex.y, vertex.z);
  18286. normals.push(normal.x, normal.y, normal.z);
  18287. uvs.push(0.0, 1.0);
  18288. vertex = normal.add(side1).add(side2).scale(size / 2);
  18289. positions.push(vertex.x, vertex.y, vertex.z);
  18290. normals.push(normal.x, normal.y, normal.z);
  18291. uvs.push(0.0, 0.0);
  18292. vertex = normal.add(side1).subtract(side2).scale(size / 2);
  18293. positions.push(vertex.x, vertex.y, vertex.z);
  18294. normals.push(normal.x, normal.y, normal.z);
  18295. uvs.push(1.0, 0.0);
  18296. }
  18297. var vertexData = new BABYLON.VertexData();
  18298. vertexData.indices = indices;
  18299. vertexData.positions = positions;
  18300. vertexData.normals = normals;
  18301. vertexData.uvs = uvs;
  18302. return vertexData;
  18303. };
  18304. VertexData.CreateSphere = function (segments, diameter) {
  18305. segments = segments || 32;
  18306. diameter = diameter || 1;
  18307. var radius = diameter / 2;
  18308. var totalZRotationSteps = 2 + segments;
  18309. var totalYRotationSteps = 2 * totalZRotationSteps;
  18310. var indices = [];
  18311. var positions = [];
  18312. var normals = [];
  18313. var uvs = [];
  18314. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  18315. var normalizedZ = zRotationStep / totalZRotationSteps;
  18316. var angleZ = (normalizedZ * Math.PI);
  18317. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  18318. var normalizedY = yRotationStep / totalYRotationSteps;
  18319. var angleY = normalizedY * Math.PI * 2;
  18320. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  18321. var rotationY = BABYLON.Matrix.RotationY(angleY);
  18322. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  18323. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  18324. var vertex = complete.scale(radius);
  18325. var normal = BABYLON.Vector3.Normalize(vertex);
  18326. positions.push(vertex.x, vertex.y, vertex.z);
  18327. normals.push(normal.x, normal.y, normal.z);
  18328. uvs.push(normalizedZ, normalizedY);
  18329. }
  18330. if (zRotationStep > 0) {
  18331. var verticesCount = positions.length / 3;
  18332. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  18333. indices.push((firstIndex));
  18334. indices.push((firstIndex + 1));
  18335. indices.push(firstIndex + totalYRotationSteps + 1);
  18336. indices.push((firstIndex + totalYRotationSteps + 1));
  18337. indices.push((firstIndex + 1));
  18338. indices.push((firstIndex + totalYRotationSteps + 2));
  18339. }
  18340. }
  18341. }
  18342. var vertexData = new BABYLON.VertexData();
  18343. vertexData.indices = indices;
  18344. vertexData.positions = positions;
  18345. vertexData.normals = normals;
  18346. vertexData.uvs = uvs;
  18347. return vertexData;
  18348. };
  18349. VertexData.CreateCylinder = function (height, diameterTop, diameterBottom, tessellation, subdivisions) {
  18350. if (typeof subdivisions === "undefined") { subdivisions = 1; }
  18351. var radiusTop = diameterTop / 2;
  18352. var radiusBottom = diameterBottom / 2;
  18353. var indices = [];
  18354. var positions = [];
  18355. var normals = [];
  18356. var uvs = [];
  18357. height = height || 1;
  18358. diameterTop = diameterTop || 0.5;
  18359. diameterBottom = diameterBottom || 1;
  18360. tessellation = tessellation || 16;
  18361. subdivisions = subdivisions || 1;
  18362. subdivisions = (subdivisions < 1) ? 1 : subdivisions;
  18363. var getCircleVector = function (i) {
  18364. var angle = (i * 2.0 * Math.PI / tessellation);
  18365. var dx = Math.cos(angle);
  18366. var dz = Math.sin(angle);
  18367. return new BABYLON.Vector3(dx, 0, dz);
  18368. };
  18369. var createCylinderCap = function (isTop) {
  18370. var radius = isTop ? radiusTop : radiusBottom;
  18371. if (radius == 0) {
  18372. return;
  18373. }
  18374. var vbase = positions.length / 3;
  18375. var offset = new BABYLON.Vector3(0, height / 2, 0);
  18376. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  18377. if (!isTop) {
  18378. offset.scaleInPlace(-1);
  18379. textureScale.x = -textureScale.x;
  18380. }
  18381. for (i = 0; i < tessellation; i++) {
  18382. var circleVector = getCircleVector(i);
  18383. var position = circleVector.scale(radius).add(offset);
  18384. var textureCoordinate = new BABYLON.Vector2(circleVector.x * textureScale.x + 0.5, circleVector.z * textureScale.y + 0.5);
  18385. positions.push(position.x, position.y, position.z);
  18386. uvs.push(textureCoordinate.x, textureCoordinate.y);
  18387. }
  18388. for (var i = 0; i < tessellation - 2; i++) {
  18389. if (!isTop) {
  18390. indices.push(vbase);
  18391. indices.push(vbase + (i + 2) % tessellation);
  18392. indices.push(vbase + (i + 1) % tessellation);
  18393. } else {
  18394. indices.push(vbase);
  18395. indices.push(vbase + (i + 1) % tessellation);
  18396. indices.push(vbase + (i + 2) % tessellation);
  18397. }
  18398. }
  18399. };
  18400. var base = new BABYLON.Vector3(0, -1, 0).scale(height / 2);
  18401. var offset = new BABYLON.Vector3(0, 1, 0).scale(height / subdivisions);
  18402. var stride = tessellation + 1;
  18403. for (var i = 0; i <= tessellation; i++) {
  18404. var circleVector = getCircleVector(i);
  18405. var textureCoordinate = new BABYLON.Vector2(i / tessellation, 0);
  18406. var position, radius = radiusBottom;
  18407. for (var s = 0; s <= subdivisions; s++) {
  18408. position = circleVector.scale(radius);
  18409. position.addInPlace(base.add(offset.scale(s)));
  18410. textureCoordinate.y += 1 / subdivisions;
  18411. radius += (radiusTop - radiusBottom) / subdivisions;
  18412. positions.push(position.x, position.y, position.z);
  18413. uvs.push(textureCoordinate.x, textureCoordinate.y);
  18414. }
  18415. }
  18416. subdivisions += 1;
  18417. for (var s = 0; s < subdivisions - 1; s++) {
  18418. for (var i = 0; i <= tessellation; i++) {
  18419. indices.push(i * subdivisions + s);
  18420. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  18421. indices.push(i * subdivisions + (s + 1));
  18422. indices.push(i * subdivisions + (s + 1));
  18423. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  18424. indices.push((i * subdivisions + (s + subdivisions + 1)) % (stride * subdivisions));
  18425. }
  18426. }
  18427. createCylinderCap(true);
  18428. createCylinderCap(false);
  18429. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  18430. var vertexData = new BABYLON.VertexData();
  18431. vertexData.indices = indices;
  18432. vertexData.positions = positions;
  18433. vertexData.normals = normals;
  18434. vertexData.uvs = uvs;
  18435. return vertexData;
  18436. };
  18437. VertexData.CreateTorus = function (diameter, thickness, tessellation) {
  18438. var indices = [];
  18439. var positions = [];
  18440. var normals = [];
  18441. var uvs = [];
  18442. diameter = diameter || 1;
  18443. thickness = thickness || 0.5;
  18444. tessellation = tessellation || 16;
  18445. var stride = tessellation + 1;
  18446. for (var i = 0; i <= tessellation; i++) {
  18447. var u = i / tessellation;
  18448. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  18449. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  18450. for (var j = 0; j <= tessellation; j++) {
  18451. var v = 1 - j / tessellation;
  18452. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  18453. var dx = Math.cos(innerAngle);
  18454. var dy = Math.sin(innerAngle);
  18455. var normal = new BABYLON.Vector3(dx, dy, 0);
  18456. var position = normal.scale(thickness / 2);
  18457. var textureCoordinate = new BABYLON.Vector2(u, v);
  18458. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  18459. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  18460. positions.push(position.x, position.y, position.z);
  18461. normals.push(normal.x, normal.y, normal.z);
  18462. uvs.push(textureCoordinate.x, textureCoordinate.y);
  18463. var nextI = (i + 1) % stride;
  18464. var nextJ = (j + 1) % stride;
  18465. indices.push(i * stride + j);
  18466. indices.push(i * stride + nextJ);
  18467. indices.push(nextI * stride + j);
  18468. indices.push(i * stride + nextJ);
  18469. indices.push(nextI * stride + nextJ);
  18470. indices.push(nextI * stride + j);
  18471. }
  18472. }
  18473. var vertexData = new BABYLON.VertexData();
  18474. vertexData.indices = indices;
  18475. vertexData.positions = positions;
  18476. vertexData.normals = normals;
  18477. vertexData.uvs = uvs;
  18478. return vertexData;
  18479. };
  18480. VertexData.CreateLines = function (points) {
  18481. var indices = [];
  18482. var positions = [];
  18483. for (var index = 0; index < points.length; index++) {
  18484. positions.push(points[index].x, points[index].y, points[index].z);
  18485. if (index > 0) {
  18486. indices.push(index - 1);
  18487. indices.push(index);
  18488. }
  18489. }
  18490. var vertexData = new BABYLON.VertexData();
  18491. vertexData.indices = indices;
  18492. vertexData.positions = positions;
  18493. return vertexData;
  18494. };
  18495. VertexData.CreateGround = function (width, height, subdivisions) {
  18496. var indices = [];
  18497. var positions = [];
  18498. var normals = [];
  18499. var uvs = [];
  18500. var row, col;
  18501. width = width || 1;
  18502. height = height || 1;
  18503. subdivisions = subdivisions || 1;
  18504. for (row = 0; row <= subdivisions; row++) {
  18505. for (col = 0; col <= subdivisions; col++) {
  18506. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  18507. var normal = new BABYLON.Vector3(0, 1.0, 0);
  18508. positions.push(position.x, position.y, position.z);
  18509. normals.push(normal.x, normal.y, normal.z);
  18510. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  18511. }
  18512. }
  18513. for (row = 0; row < subdivisions; row++) {
  18514. for (col = 0; col < subdivisions; col++) {
  18515. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  18516. indices.push(col + 1 + row * (subdivisions + 1));
  18517. indices.push(col + row * (subdivisions + 1));
  18518. indices.push(col + (row + 1) * (subdivisions + 1));
  18519. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  18520. indices.push(col + row * (subdivisions + 1));
  18521. }
  18522. }
  18523. var vertexData = new BABYLON.VertexData();
  18524. vertexData.indices = indices;
  18525. vertexData.positions = positions;
  18526. vertexData.normals = normals;
  18527. vertexData.uvs = uvs;
  18528. return vertexData;
  18529. };
  18530. VertexData.CreateTiledGround = function (xmin, zmin, xmax, zmax, subdivisions, precision) {
  18531. if (typeof subdivisions === "undefined") { subdivisions = { w: 1, h: 1 }; }
  18532. if (typeof precision === "undefined") { precision = { w: 1, h: 1 }; }
  18533. var indices = [];
  18534. var positions = [];
  18535. var normals = [];
  18536. var uvs = [];
  18537. var row, col, tileRow, tileCol;
  18538. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  18539. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  18540. precision.w = (precision.w < 1) ? 1 : precision.w;
  18541. precision.h = (precision.h < 1) ? 1 : precision.h;
  18542. var tileSize = {
  18543. 'w': (xmax - xmin) / subdivisions.w,
  18544. 'h': (zmax - zmin) / subdivisions.h
  18545. };
  18546. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  18547. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  18548. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  18549. }
  18550. }
  18551. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  18552. var base = positions.length / 3;
  18553. var rowLength = precision.w + 1;
  18554. for (row = 0; row < precision.h; row++) {
  18555. for (col = 0; col < precision.w; col++) {
  18556. var square = [
  18557. base + col + row * rowLength,
  18558. base + (col + 1) + row * rowLength,
  18559. base + (col + 1) + (row + 1) * rowLength,
  18560. base + col + (row + 1) * rowLength
  18561. ];
  18562. indices.push(square[1]);
  18563. indices.push(square[2]);
  18564. indices.push(square[3]);
  18565. indices.push(square[0]);
  18566. indices.push(square[1]);
  18567. indices.push(square[3]);
  18568. }
  18569. }
  18570. var position = BABYLON.Vector3.Zero();
  18571. var normal = new BABYLON.Vector3(0, 1.0, 0);
  18572. for (row = 0; row <= precision.h; row++) {
  18573. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  18574. for (col = 0; col <= precision.w; col++) {
  18575. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  18576. position.y = 0;
  18577. positions.push(position.x, position.y, position.z);
  18578. normals.push(normal.x, normal.y, normal.z);
  18579. uvs.push(col / precision.w, row / precision.h);
  18580. }
  18581. }
  18582. }
  18583. var vertexData = new BABYLON.VertexData();
  18584. vertexData.indices = indices;
  18585. vertexData.positions = positions;
  18586. vertexData.normals = normals;
  18587. vertexData.uvs = uvs;
  18588. return vertexData;
  18589. };
  18590. VertexData.CreateGroundFromHeightMap = function (width, height, subdivisions, minHeight, maxHeight, buffer, bufferWidth, bufferHeight) {
  18591. var indices = [];
  18592. var positions = [];
  18593. var normals = [];
  18594. var uvs = [];
  18595. var row, col;
  18596. for (row = 0; row <= subdivisions; row++) {
  18597. for (col = 0; col <= subdivisions; col++) {
  18598. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  18599. var heightMapX = (((position.x + width / 2) / width) * (bufferWidth - 1)) | 0;
  18600. var heightMapY = ((1.0 - (position.z + height / 2) / height) * (bufferHeight - 1)) | 0;
  18601. var pos = (heightMapX + heightMapY * bufferWidth) * 4;
  18602. var r = buffer[pos] / 255.0;
  18603. var g = buffer[pos + 1] / 255.0;
  18604. var b = buffer[pos + 2] / 255.0;
  18605. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  18606. position.y = minHeight + (maxHeight - minHeight) * gradient;
  18607. positions.push(position.x, position.y, position.z);
  18608. normals.push(0, 0, 0);
  18609. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  18610. }
  18611. }
  18612. for (row = 0; row < subdivisions; row++) {
  18613. for (col = 0; col < subdivisions; col++) {
  18614. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  18615. indices.push(col + 1 + row * (subdivisions + 1));
  18616. indices.push(col + row * (subdivisions + 1));
  18617. indices.push(col + (row + 1) * (subdivisions + 1));
  18618. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  18619. indices.push(col + row * (subdivisions + 1));
  18620. }
  18621. }
  18622. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  18623. var vertexData = new BABYLON.VertexData();
  18624. vertexData.indices = indices;
  18625. vertexData.positions = positions;
  18626. vertexData.normals = normals;
  18627. vertexData.uvs = uvs;
  18628. return vertexData;
  18629. };
  18630. VertexData.CreatePlane = function (size) {
  18631. var indices = [];
  18632. var positions = [];
  18633. var normals = [];
  18634. var uvs = [];
  18635. size = size || 1;
  18636. var halfSize = size / 2.0;
  18637. positions.push(-halfSize, -halfSize, 0);
  18638. normals.push(0, 0, -1.0);
  18639. uvs.push(0.0, 0.0);
  18640. positions.push(halfSize, -halfSize, 0);
  18641. normals.push(0, 0, -1.0);
  18642. uvs.push(1.0, 0.0);
  18643. positions.push(halfSize, halfSize, 0);
  18644. normals.push(0, 0, -1.0);
  18645. uvs.push(1.0, 1.0);
  18646. positions.push(-halfSize, halfSize, 0);
  18647. normals.push(0, 0, -1.0);
  18648. uvs.push(0.0, 1.0);
  18649. indices.push(0);
  18650. indices.push(1);
  18651. indices.push(2);
  18652. indices.push(0);
  18653. indices.push(2);
  18654. indices.push(3);
  18655. var vertexData = new BABYLON.VertexData();
  18656. vertexData.indices = indices;
  18657. vertexData.positions = positions;
  18658. vertexData.normals = normals;
  18659. vertexData.uvs = uvs;
  18660. return vertexData;
  18661. };
  18662. VertexData.CreateTorusKnot = function (radius, tube, radialSegments, tubularSegments, p, q) {
  18663. var indices = [];
  18664. var positions = [];
  18665. var normals = [];
  18666. var uvs = [];
  18667. radius = radius || 2;
  18668. tube = tube || 0.5;
  18669. radialSegments = radialSegments || 32;
  18670. tubularSegments = tubularSegments || 32;
  18671. p = p || 2;
  18672. q = q || 3;
  18673. var getPos = function (angle) {
  18674. var cu = Math.cos(angle);
  18675. var su = Math.sin(angle);
  18676. var quOverP = q / p * angle;
  18677. var cs = Math.cos(quOverP);
  18678. var tx = radius * (2 + cs) * 0.5 * cu;
  18679. var ty = radius * (2 + cs) * su * 0.5;
  18680. var tz = radius * Math.sin(quOverP) * 0.5;
  18681. return new BABYLON.Vector3(tx, ty, tz);
  18682. };
  18683. for (var i = 0; i <= radialSegments; i++) {
  18684. var modI = i % radialSegments;
  18685. var u = modI / radialSegments * 2 * p * Math.PI;
  18686. var p1 = getPos(u);
  18687. var p2 = getPos(u + 0.01);
  18688. var tang = p2.subtract(p1);
  18689. var n = p2.add(p1);
  18690. var bitan = BABYLON.Vector3.Cross(tang, n);
  18691. n = BABYLON.Vector3.Cross(bitan, tang);
  18692. bitan.normalize();
  18693. n.normalize();
  18694. for (var j = 0; j < tubularSegments; j++) {
  18695. var modJ = j % tubularSegments;
  18696. var v = modJ / tubularSegments * 2 * Math.PI;
  18697. var cx = -tube * Math.cos(v);
  18698. var cy = tube * Math.sin(v);
  18699. positions.push(p1.x + cx * n.x + cy * bitan.x);
  18700. positions.push(p1.y + cx * n.y + cy * bitan.y);
  18701. positions.push(p1.z + cx * n.z + cy * bitan.z);
  18702. uvs.push(i / radialSegments);
  18703. uvs.push(j / tubularSegments);
  18704. }
  18705. }
  18706. for (i = 0; i < radialSegments; i++) {
  18707. for (j = 0; j < tubularSegments; j++) {
  18708. var jNext = (j + 1) % tubularSegments;
  18709. var a = i * tubularSegments + j;
  18710. var b = (i + 1) * tubularSegments + j;
  18711. var c = (i + 1) * tubularSegments + jNext;
  18712. var d = i * tubularSegments + jNext;
  18713. indices.push(d);
  18714. indices.push(b);
  18715. indices.push(a);
  18716. indices.push(d);
  18717. indices.push(c);
  18718. indices.push(b);
  18719. }
  18720. }
  18721. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  18722. var vertexData = new BABYLON.VertexData();
  18723. vertexData.indices = indices;
  18724. vertexData.positions = positions;
  18725. vertexData.normals = normals;
  18726. vertexData.uvs = uvs;
  18727. return vertexData;
  18728. };
  18729. VertexData.ComputeNormals = function (positions, indices, normals) {
  18730. var positionVectors = [];
  18731. var facesOfVertices = [];
  18732. var index;
  18733. for (index = 0; index < positions.length; index += 3) {
  18734. var vector3 = new BABYLON.Vector3(positions[index], positions[index + 1], positions[index + 2]);
  18735. positionVectors.push(vector3);
  18736. facesOfVertices.push([]);
  18737. }
  18738. var facesNormals = [];
  18739. for (index = 0; index < indices.length / 3; index++) {
  18740. var i1 = indices[index * 3];
  18741. var i2 = indices[index * 3 + 1];
  18742. var i3 = indices[index * 3 + 2];
  18743. var p1 = positionVectors[i1];
  18744. var p2 = positionVectors[i2];
  18745. var p3 = positionVectors[i3];
  18746. var p1p2 = p1.subtract(p2);
  18747. var p3p2 = p3.subtract(p2);
  18748. facesNormals[index] = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  18749. facesOfVertices[i1].push(index);
  18750. facesOfVertices[i2].push(index);
  18751. facesOfVertices[i3].push(index);
  18752. }
  18753. for (index = 0; index < positionVectors.length; index++) {
  18754. var faces = facesOfVertices[index];
  18755. var normal = BABYLON.Vector3.Zero();
  18756. for (var faceIndex = 0; faceIndex < faces.length; faceIndex++) {
  18757. normal.addInPlace(facesNormals[faces[faceIndex]]);
  18758. }
  18759. normal = BABYLON.Vector3.Normalize(normal.scale(1.0 / faces.length));
  18760. normals[index * 3] = normal.x;
  18761. normals[index * 3 + 1] = normal.y;
  18762. normals[index * 3 + 2] = normal.z;
  18763. }
  18764. };
  18765. return VertexData;
  18766. })();
  18767. BABYLON.VertexData = VertexData;
  18768. })(BABYLON || (BABYLON = {}));
  18769. var __extends = this.__extends || function (d, b) {
  18770. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  18771. function __() { this.constructor = d; }
  18772. __.prototype = b.prototype;
  18773. d.prototype = new __();
  18774. };
  18775. var BABYLON;
  18776. (function (BABYLON) {
  18777. var buildCamera = function (that, name) {
  18778. that._leftCamera.isIntermediate = true;
  18779. that.subCameras.push(that._leftCamera);
  18780. that.subCameras.push(that._rightCamera);
  18781. that._leftTexture = new BABYLON.PassPostProcess(name + "_leftTexture", 1.0, that._leftCamera);
  18782. that._anaglyphPostProcess = new BABYLON.AnaglyphPostProcess(name + "_anaglyph", 1.0, that._rightCamera);
  18783. that._anaglyphPostProcess.onApply = function (effect) {
  18784. effect.setTextureFromPostProcess("leftSampler", that._leftTexture);
  18785. };
  18786. that._update();
  18787. };
  18788. var AnaglyphArcRotateCamera = (function (_super) {
  18789. __extends(AnaglyphArcRotateCamera, _super);
  18790. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, eyeSpace, scene) {
  18791. _super.call(this, name, alpha, beta, radius, target, scene);
  18792. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  18793. this._leftCamera = new BABYLON.ArcRotateCamera(name + "_left", alpha - this._eyeSpace, beta, radius, target, scene);
  18794. this._rightCamera = new BABYLON.ArcRotateCamera(name + "_right", alpha + this._eyeSpace, beta, radius, target, scene);
  18795. buildCamera(this, name);
  18796. }
  18797. AnaglyphArcRotateCamera.prototype._update = function () {
  18798. this._updateCamera(this._leftCamera);
  18799. this._updateCamera(this._rightCamera);
  18800. this._leftCamera.alpha = this.alpha - this._eyeSpace;
  18801. this._rightCamera.alpha = this.alpha + this._eyeSpace;
  18802. _super.prototype._update.call(this);
  18803. };
  18804. AnaglyphArcRotateCamera.prototype._updateCamera = function (camera) {
  18805. camera.beta = this.beta;
  18806. camera.radius = this.radius;
  18807. camera.minZ = this.minZ;
  18808. camera.maxZ = this.maxZ;
  18809. camera.fov = this.fov;
  18810. camera.target = this.target;
  18811. };
  18812. return AnaglyphArcRotateCamera;
  18813. })(BABYLON.ArcRotateCamera);
  18814. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  18815. var AnaglyphFreeCamera = (function (_super) {
  18816. __extends(AnaglyphFreeCamera, _super);
  18817. function AnaglyphFreeCamera(name, position, eyeSpace, scene) {
  18818. _super.call(this, name, position, scene);
  18819. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  18820. this._transformMatrix = new BABYLON.Matrix();
  18821. this._leftCamera = new BABYLON.FreeCamera(name + "_left", position.clone(), scene);
  18822. this._rightCamera = new BABYLON.FreeCamera(name + "_right", position.clone(), scene);
  18823. buildCamera(this, name);
  18824. }
  18825. AnaglyphFreeCamera.prototype._getSubCameraPosition = function (eyeSpace, result) {
  18826. var target = this.getTarget();
  18827. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(eyeSpace), this._transformMatrix);
  18828. this._transformMatrix = this._transformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  18829. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._transformMatrix, result);
  18830. };
  18831. AnaglyphFreeCamera.prototype._update = function () {
  18832. this._getSubCameraPosition(-this._eyeSpace, this._leftCamera.position);
  18833. this._getSubCameraPosition(this._eyeSpace, this._rightCamera.position);
  18834. this._updateCamera(this._leftCamera);
  18835. this._updateCamera(this._rightCamera);
  18836. _super.prototype._update.call(this);
  18837. };
  18838. AnaglyphFreeCamera.prototype._updateCamera = function (camera) {
  18839. camera.minZ = this.minZ;
  18840. camera.maxZ = this.maxZ;
  18841. camera.fov = this.fov;
  18842. camera.viewport = this.viewport;
  18843. camera.setTarget(this.getTarget());
  18844. };
  18845. return AnaglyphFreeCamera;
  18846. })(BABYLON.FreeCamera);
  18847. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  18848. })(BABYLON || (BABYLON = {}));
  18849. var __extends = this.__extends || function (d, b) {
  18850. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  18851. function __() { this.constructor = d; }
  18852. __.prototype = b.prototype;
  18853. d.prototype = new __();
  18854. };
  18855. var BABYLON;
  18856. (function (BABYLON) {
  18857. var AnaglyphPostProcess = (function (_super) {
  18858. __extends(AnaglyphPostProcess, _super);
  18859. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  18860. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  18861. }
  18862. return AnaglyphPostProcess;
  18863. })(BABYLON.PostProcess);
  18864. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  18865. })(BABYLON || (BABYLON = {}));
  18866. var BABYLON;
  18867. (function (BABYLON) {
  18868. var Tags = (function () {
  18869. function Tags() {
  18870. }
  18871. Tags.EnableFor = function (obj) {
  18872. obj._tags = obj._tags || {};
  18873. obj.hasTags = function () {
  18874. return Tags.HasTags(obj);
  18875. };
  18876. obj.addTags = function (tagsString) {
  18877. return Tags.AddTagsTo(obj, tagsString);
  18878. };
  18879. obj.removeTags = function (tagsString) {
  18880. return Tags.RemoveTagsFrom(obj, tagsString);
  18881. };
  18882. obj.matchesTagsQuery = function (tagsQuery) {
  18883. return Tags.MatchesQuery(obj, tagsQuery);
  18884. };
  18885. };
  18886. Tags.DisableFor = function (obj) {
  18887. delete obj._tags;
  18888. delete obj.hasTags;
  18889. delete obj.addTags;
  18890. delete obj.removeTags;
  18891. delete obj.matchesTagsQuery;
  18892. };
  18893. Tags.HasTags = function (obj) {
  18894. if (!obj._tags) {
  18895. return false;
  18896. }
  18897. return !BABYLON.Tools.IsEmpty(obj._tags);
  18898. };
  18899. Tags.GetTags = function (obj) {
  18900. if (!obj._tags) {
  18901. return null;
  18902. }
  18903. return obj._tags;
  18904. };
  18905. Tags.AddTagsTo = function (obj, tagsString) {
  18906. if (!tagsString) {
  18907. return;
  18908. }
  18909. var tags = tagsString.split(" ");
  18910. for (var t in tags) {
  18911. Tags._AddTagTo(obj, tags[t]);
  18912. }
  18913. };
  18914. Tags._AddTagTo = function (obj, tag) {
  18915. tag = tag.trim();
  18916. if (tag === "" || tag === "true" || tag === "false") {
  18917. return;
  18918. }
  18919. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  18920. return;
  18921. }
  18922. Tags.EnableFor(obj);
  18923. obj._tags[tag] = true;
  18924. };
  18925. Tags.RemoveTagsFrom = function (obj, tagsString) {
  18926. if (!Tags.HasTags(obj)) {
  18927. return;
  18928. }
  18929. var tags = tagsString.split(" ");
  18930. for (var t in tags) {
  18931. Tags._RemoveTagFrom(obj, tags[t]);
  18932. }
  18933. };
  18934. Tags._RemoveTagFrom = function (obj, tag) {
  18935. delete obj._tags[tag];
  18936. };
  18937. Tags.MatchesQuery = function (obj, tagsQuery) {
  18938. if (tagsQuery === undefined) {
  18939. return true;
  18940. }
  18941. if (tagsQuery === "") {
  18942. return Tags.HasTags(obj);
  18943. }
  18944. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) {
  18945. return Tags.HasTags(obj) && obj._tags[r];
  18946. });
  18947. };
  18948. return Tags;
  18949. })();
  18950. BABYLON.Tags = Tags;
  18951. })(BABYLON || (BABYLON = {}));
  18952. var BABYLON;
  18953. (function (BABYLON) {
  18954. (function (Internals) {
  18955. var AndOrNotEvaluator = (function () {
  18956. function AndOrNotEvaluator() {
  18957. }
  18958. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  18959. if (!query.match(/\([^\(\)]*\)/g)) {
  18960. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  18961. } else {
  18962. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  18963. r = r.slice(1, r.length - 1);
  18964. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  18965. });
  18966. }
  18967. if (query === "true") {
  18968. return true;
  18969. }
  18970. if (query === "false") {
  18971. return false;
  18972. }
  18973. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  18974. };
  18975. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  18976. evaluateCallback = evaluateCallback || (function (r) {
  18977. return r === "true" ? true : false;
  18978. });
  18979. var result;
  18980. var or = parenthesisContent.split("||");
  18981. for (var i in or) {
  18982. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  18983. var and = ori.split("&&");
  18984. if (and.length > 1) {
  18985. for (var j = 0; j < and.length; ++j) {
  18986. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  18987. if (andj !== "true" && andj !== "false") {
  18988. if (andj[0] === "!") {
  18989. result = !evaluateCallback(andj.substring(1));
  18990. } else {
  18991. result = evaluateCallback(andj);
  18992. }
  18993. } else {
  18994. result = andj === "true" ? true : false;
  18995. }
  18996. if (!result) {
  18997. ori = "false";
  18998. break;
  18999. }
  19000. }
  19001. }
  19002. if (result || ori === "true") {
  19003. result = true;
  19004. break;
  19005. }
  19006. if (ori !== "true" && ori !== "false") {
  19007. if (ori[0] === "!") {
  19008. result = !evaluateCallback(ori.substring(1));
  19009. } else {
  19010. result = evaluateCallback(ori);
  19011. }
  19012. } else {
  19013. result = ori === "true" ? true : false;
  19014. }
  19015. }
  19016. return result ? "true" : "false";
  19017. };
  19018. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  19019. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  19020. r = r.replace(/[\s]/g, function () {
  19021. return "";
  19022. });
  19023. return r.length % 2 ? "!" : "";
  19024. });
  19025. booleanString = booleanString.trim();
  19026. if (booleanString === "!true") {
  19027. booleanString = "false";
  19028. } else if (booleanString === "!false") {
  19029. booleanString = "true";
  19030. }
  19031. return booleanString;
  19032. };
  19033. return AndOrNotEvaluator;
  19034. })();
  19035. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  19036. })(BABYLON.Internals || (BABYLON.Internals = {}));
  19037. var Internals = BABYLON.Internals;
  19038. })(BABYLON || (BABYLON = {}));
  19039. var BABYLON;
  19040. (function (BABYLON) {
  19041. var PostProcessRenderPass = (function () {
  19042. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  19043. this._enabled = true;
  19044. this._refCount = 0;
  19045. this._name = name;
  19046. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  19047. this.setRenderList(renderList);
  19048. this._renderTexture.onBeforeRender = beforeRender;
  19049. this._renderTexture.onAfterRender = afterRender;
  19050. this._scene = scene;
  19051. this._renderList = renderList;
  19052. }
  19053. PostProcessRenderPass.prototype._incRefCount = function () {
  19054. if (this._refCount === 0) {
  19055. this._scene.customRenderTargets.push(this._renderTexture);
  19056. }
  19057. return ++this._refCount;
  19058. };
  19059. PostProcessRenderPass.prototype._decRefCount = function () {
  19060. this._refCount--;
  19061. if (this._refCount <= 0) {
  19062. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  19063. }
  19064. return this._refCount;
  19065. };
  19066. PostProcessRenderPass.prototype._update = function () {
  19067. this.setRenderList(this._renderList);
  19068. };
  19069. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  19070. this._renderTexture.renderList = renderList;
  19071. };
  19072. PostProcessRenderPass.prototype.getRenderTexture = function () {
  19073. return this._renderTexture;
  19074. };
  19075. return PostProcessRenderPass;
  19076. })();
  19077. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  19078. })(BABYLON || (BABYLON = {}));
  19079. var BABYLON;
  19080. (function (BABYLON) {
  19081. var PostProcessRenderEffect = (function () {
  19082. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  19083. this._engine = engine;
  19084. this._name = name;
  19085. this._singleInstance = singleInstance || true;
  19086. this._getPostProcess = getPostProcess;
  19087. this._cameras = [];
  19088. this._postProcesses = [];
  19089. this._indicesForCamera = [];
  19090. this._renderPasses = [];
  19091. this._renderEffectAsPasses = [];
  19092. }
  19093. PostProcessRenderEffect.prototype._update = function () {
  19094. for (var renderPassName in this._renderPasses) {
  19095. this._renderPasses[renderPassName]._update();
  19096. }
  19097. };
  19098. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  19099. this._renderPasses[renderPass._name] = renderPass;
  19100. this._linkParameters();
  19101. };
  19102. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  19103. delete this._renderPasses[renderPass._name];
  19104. this._linkParameters();
  19105. };
  19106. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  19107. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  19108. this._linkParameters();
  19109. };
  19110. PostProcessRenderEffect.prototype.getPass = function (passName) {
  19111. for (var renderPassName in this._renderPasses) {
  19112. if (renderPassName === passName) {
  19113. return this._renderPasses[passName];
  19114. }
  19115. }
  19116. };
  19117. PostProcessRenderEffect.prototype.emptyPasses = function () {
  19118. this._renderPasses.length = 0;
  19119. this._linkParameters();
  19120. };
  19121. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  19122. var cameraKey;
  19123. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  19124. for (var i = 0; i < _cam.length; i++) {
  19125. var camera = _cam[i];
  19126. var cameraName = camera.name;
  19127. if (this._singleInstance) {
  19128. cameraKey = 0;
  19129. } else {
  19130. cameraKey = cameraName;
  19131. }
  19132. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  19133. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  19134. if (!this._indicesForCamera[cameraName]) {
  19135. this._indicesForCamera[cameraName] = [];
  19136. }
  19137. this._indicesForCamera[cameraName].push(index);
  19138. if (this._cameras.indexOf(camera) === -1) {
  19139. this._cameras[cameraName] = camera;
  19140. }
  19141. for (var passName in this._renderPasses) {
  19142. this._renderPasses[passName]._incRefCount();
  19143. }
  19144. }
  19145. this._linkParameters();
  19146. };
  19147. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  19148. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  19149. for (var i = 0; i < _cam.length; i++) {
  19150. var camera = _cam[i];
  19151. var cameraName = camera.name;
  19152. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  19153. var index = this._cameras.indexOf(cameraName);
  19154. this._indicesForCamera.splice(index, 1);
  19155. this._cameras.splice(index, 1);
  19156. for (var passName in this._renderPasses) {
  19157. this._renderPasses[passName]._decRefCount();
  19158. }
  19159. }
  19160. };
  19161. PostProcessRenderEffect.prototype._enable = function (cameras) {
  19162. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  19163. for (var i = 0; i < _cam.length; i++) {
  19164. var camera = _cam[i];
  19165. var cameraName = camera.name;
  19166. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  19167. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  19168. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  19169. }
  19170. }
  19171. for (var passName in this._renderPasses) {
  19172. this._renderPasses[passName]._incRefCount();
  19173. }
  19174. }
  19175. };
  19176. PostProcessRenderEffect.prototype._disable = function (cameras) {
  19177. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  19178. for (var i = 0; i < _cam.length; i++) {
  19179. var camera = _cam[i];
  19180. var cameraName = camera.Name;
  19181. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  19182. for (var passName in this._renderPasses) {
  19183. this._renderPasses[passName]._decRefCount();
  19184. }
  19185. }
  19186. };
  19187. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  19188. if (this._singleInstance) {
  19189. return this._postProcesses[0];
  19190. } else {
  19191. return this._postProcesses[camera.name];
  19192. }
  19193. };
  19194. PostProcessRenderEffect.prototype._linkParameters = function () {
  19195. var _this = this;
  19196. for (var index in this._postProcesses) {
  19197. if (this.applyParameters) {
  19198. this.applyParameters(this._postProcesses[index]);
  19199. }
  19200. this._postProcesses[index].onBeforeRender = function (effect) {
  19201. _this._linkTextures(effect);
  19202. };
  19203. }
  19204. };
  19205. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  19206. for (var renderPassName in this._renderPasses) {
  19207. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  19208. }
  19209. for (var renderEffectName in this._renderEffectAsPasses) {
  19210. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  19211. }
  19212. };
  19213. return PostProcessRenderEffect;
  19214. })();
  19215. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  19216. })(BABYLON || (BABYLON = {}));
  19217. var BABYLON;
  19218. (function (BABYLON) {
  19219. var PostProcessRenderPipeline = (function () {
  19220. function PostProcessRenderPipeline(engine, name) {
  19221. this._engine = engine;
  19222. this._name = name;
  19223. this._renderEffects = [];
  19224. this._renderEffectsForIsolatedPass = [];
  19225. this._cameras = [];
  19226. }
  19227. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  19228. this._renderEffects[renderEffect._name] = renderEffect;
  19229. };
  19230. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  19231. var renderEffects = this._renderEffects[renderEffectName];
  19232. if (!renderEffects) {
  19233. return;
  19234. }
  19235. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  19236. };
  19237. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  19238. var renderEffects = this._renderEffects[renderEffectName];
  19239. if (!renderEffects) {
  19240. return;
  19241. }
  19242. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  19243. };
  19244. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  19245. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  19246. var indicesToDelete = [];
  19247. for (var i = 0; i < _cam.length; i++) {
  19248. var camera = _cam[i];
  19249. var cameraName = camera.name;
  19250. if (this._cameras.indexOf(camera) === -1) {
  19251. this._cameras[cameraName] = camera;
  19252. } else if (unique) {
  19253. indicesToDelete.push(i);
  19254. }
  19255. }
  19256. for (var i = 0; i < indicesToDelete.length; i++) {
  19257. cameras.splice(indicesToDelete[i], 1);
  19258. }
  19259. for (var renderEffectName in this._renderEffects) {
  19260. this._renderEffects[renderEffectName]._attachCameras(_cam);
  19261. }
  19262. };
  19263. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  19264. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  19265. for (var renderEffectName in this._renderEffects) {
  19266. this._renderEffects[renderEffectName]._detachCameras(_cam);
  19267. }
  19268. for (var i = 0; i < _cam.length; i++) {
  19269. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  19270. }
  19271. };
  19272. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  19273. var _this = this;
  19274. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  19275. var pass = null;
  19276. for (var renderEffectName in this._renderEffects) {
  19277. pass = this._renderEffects[renderEffectName].getPass(passName);
  19278. if (pass != null) {
  19279. break;
  19280. }
  19281. }
  19282. if (pass === null) {
  19283. return;
  19284. }
  19285. for (var renderEffectName in this._renderEffects) {
  19286. this._renderEffects[renderEffectName]._disable(_cam);
  19287. }
  19288. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  19289. for (var i = 0; i < _cam.length; i++) {
  19290. var camera = _cam[i];
  19291. var cameraName = camera.name;
  19292. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () {
  19293. return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true);
  19294. });
  19295. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  19296. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  19297. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  19298. }
  19299. };
  19300. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  19301. var _this = this;
  19302. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  19303. for (var i = 0; i < _cam.length; i++) {
  19304. var camera = _cam[i];
  19305. var cameraName = camera.name;
  19306. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () {
  19307. return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true);
  19308. });
  19309. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  19310. }
  19311. for (var renderEffectName in this._renderEffects) {
  19312. this._renderEffects[renderEffectName]._enable(_cam);
  19313. }
  19314. };
  19315. PostProcessRenderPipeline.prototype._update = function () {
  19316. for (var renderEffectName in this._renderEffects) {
  19317. this._renderEffects[renderEffectName]._update();
  19318. }
  19319. for (var i = 0; i < this._cameras.length; i++) {
  19320. var cameraName = this._cameras[i].name;
  19321. if (this._renderEffectsForIsolatedPass[cameraName]) {
  19322. this._renderEffectsForIsolatedPass[cameraName]._update();
  19323. }
  19324. }
  19325. };
  19326. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  19327. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  19328. return PostProcessRenderPipeline;
  19329. })();
  19330. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  19331. })(BABYLON || (BABYLON = {}));
  19332. var BABYLON;
  19333. (function (BABYLON) {
  19334. var PostProcessRenderPipelineManager = (function () {
  19335. function PostProcessRenderPipelineManager() {
  19336. this._renderPipelines = new Array();
  19337. }
  19338. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  19339. this._renderPipelines[renderPipeline._name] = renderPipeline;
  19340. };
  19341. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  19342. var renderPipeline = this._renderPipelines[renderPipelineName];
  19343. if (!renderPipeline) {
  19344. return;
  19345. }
  19346. renderPipeline._attachCameras(cameras, unique);
  19347. };
  19348. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  19349. var renderPipeline = this._renderPipelines[renderPipelineName];
  19350. if (!renderPipeline) {
  19351. return;
  19352. }
  19353. renderPipeline._detachCameras(cameras);
  19354. };
  19355. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  19356. var renderPipeline = this._renderPipelines[renderPipelineName];
  19357. if (!renderPipeline) {
  19358. return;
  19359. }
  19360. renderPipeline._enableEffect(renderEffectName, cameras);
  19361. };
  19362. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  19363. var renderPipeline = this._renderPipelines[renderPipelineName];
  19364. if (!renderPipeline) {
  19365. return;
  19366. }
  19367. renderPipeline._disableEffect(renderEffectName, cameras);
  19368. };
  19369. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  19370. var renderPipeline = this._renderPipelines[renderPipelineName];
  19371. if (!renderPipeline) {
  19372. return;
  19373. }
  19374. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  19375. };
  19376. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  19377. var renderPipeline = this._renderPipelines[renderPipelineName];
  19378. if (!renderPipeline) {
  19379. return;
  19380. }
  19381. renderPipeline._disableDisplayOnlyPass(cameras);
  19382. };
  19383. PostProcessRenderPipelineManager.prototype.update = function () {
  19384. for (var renderPipelineName in this._renderPipelines) {
  19385. this._renderPipelines[renderPipelineName]._update();
  19386. }
  19387. };
  19388. return PostProcessRenderPipelineManager;
  19389. })();
  19390. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  19391. })(BABYLON || (BABYLON = {}));
  19392. var __extends = this.__extends || function (d, b) {
  19393. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  19394. function __() { this.constructor = d; }
  19395. __.prototype = b.prototype;
  19396. d.prototype = new __();
  19397. };
  19398. var BABYLON;
  19399. (function (BABYLON) {
  19400. var DisplayPassPostProcess = (function (_super) {
  19401. __extends(DisplayPassPostProcess, _super);
  19402. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  19403. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  19404. }
  19405. return DisplayPassPostProcess;
  19406. })(BABYLON.PostProcess);
  19407. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  19408. })(BABYLON || (BABYLON = {}));
  19409. var BABYLON;
  19410. (function (BABYLON) {
  19411. var BoundingBoxRenderer = (function () {
  19412. function BoundingBoxRenderer(scene) {
  19413. this.frontColor = new BABYLON.Color3(1, 1, 1);
  19414. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  19415. this.showBackLines = true;
  19416. this.renderList = new BABYLON.SmartArray(32);
  19417. this._scene = scene;
  19418. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  19419. attributes: ["position"],
  19420. uniforms: ["worldViewProjection", "color"]
  19421. });
  19422. var engine = this._scene.getEngine();
  19423. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  19424. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  19425. 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]);
  19426. }
  19427. BoundingBoxRenderer.prototype.reset = function () {
  19428. this.renderList.reset();
  19429. };
  19430. BoundingBoxRenderer.prototype.render = function () {
  19431. if (this.renderList.length == 0 || !this._colorShader.isReady()) {
  19432. return;
  19433. }
  19434. var engine = this._scene.getEngine();
  19435. engine.setDepthWrite(false);
  19436. this._colorShader._preBind();
  19437. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  19438. var boundingBox = this.renderList.data[boundingBoxIndex];
  19439. var min = boundingBox.minimum;
  19440. var max = boundingBox.maximum;
  19441. var diff = max.subtract(min);
  19442. var median = min.add(diff.scale(0.5));
  19443. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z).multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z)).multiply(boundingBox.getWorldMatrix());
  19444. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  19445. if (this.showBackLines) {
  19446. engine.setDepthFunctionToGreaterOrEqual();
  19447. this._colorShader.setColor4("color", this.backColor.toColor4());
  19448. this._colorShader.bind(worldMatrix);
  19449. engine.draw(false, 0, 24);
  19450. }
  19451. engine.setDepthFunctionToLess();
  19452. this._colorShader.setColor4("color", this.frontColor.toColor4());
  19453. this._colorShader.bind(worldMatrix);
  19454. engine.draw(false, 0, 24);
  19455. }
  19456. this._colorShader.unbind();
  19457. engine.setDepthFunctionToLessOrEqual();
  19458. engine.setDepthWrite(true);
  19459. };
  19460. BoundingBoxRenderer.prototype.dispose = function () {
  19461. this._colorShader.dispose();
  19462. this._vb.dispose();
  19463. this._scene.getEngine()._releaseBuffer(this._ib);
  19464. };
  19465. return BoundingBoxRenderer;
  19466. })();
  19467. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  19468. })(BABYLON || (BABYLON = {}));
  19469. /**
  19470. * Based on jsTGALoader - Javascript loader for TGA file
  19471. * By Vincent Thibault
  19472. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  19473. */
  19474. var BABYLON;
  19475. (function (BABYLON) {
  19476. (function (Internals) {
  19477. var TGATools = (function () {
  19478. function TGATools() {
  19479. }
  19480. TGATools.GetTGAHeader = function (data) {
  19481. var offset = 0;
  19482. var header = {
  19483. id_length: data[offset++],
  19484. colormap_type: data[offset++],
  19485. image_type: data[offset++],
  19486. colormap_index: data[offset++] | data[offset++] << 8,
  19487. colormap_length: data[offset++] | data[offset++] << 8,
  19488. colormap_size: data[offset++],
  19489. origin: [
  19490. data[offset++] | data[offset++] << 8,
  19491. data[offset++] | data[offset++] << 8
  19492. ],
  19493. width: data[offset++] | data[offset++] << 8,
  19494. height: data[offset++] | data[offset++] << 8,
  19495. pixel_size: data[offset++],
  19496. flags: data[offset++]
  19497. };
  19498. return header;
  19499. };
  19500. TGATools.UploadContent = function (gl, data) {
  19501. if (data.length < 19) {
  19502. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  19503. return;
  19504. }
  19505. var offset = 18;
  19506. var header = TGATools.GetTGAHeader(data);
  19507. if (header.id_length + offset > data.length) {
  19508. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  19509. return;
  19510. }
  19511. offset += header.id_length;
  19512. var use_rle = false;
  19513. var use_pal = false;
  19514. var use_rgb = false;
  19515. var use_grey = false;
  19516. switch (header.image_type) {
  19517. case TGATools._TYPE_RLE_INDEXED:
  19518. use_rle = true;
  19519. case TGATools._TYPE_INDEXED:
  19520. use_pal = true;
  19521. break;
  19522. case TGATools._TYPE_RLE_RGB:
  19523. use_rle = true;
  19524. case TGATools._TYPE_RGB:
  19525. use_rgb = true;
  19526. break;
  19527. case TGATools._TYPE_RLE_GREY:
  19528. use_rle = true;
  19529. case TGATools._TYPE_GREY:
  19530. use_grey = true;
  19531. break;
  19532. }
  19533. var pixel_data;
  19534. var numAlphaBits = header.flags & 0xf;
  19535. var pixel_size = header.pixel_size >> 3;
  19536. var pixel_total = header.width * header.height * pixel_size;
  19537. var palettes;
  19538. if (use_pal) {
  19539. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  19540. }
  19541. if (use_rle) {
  19542. pixel_data = new Uint8Array(pixel_total);
  19543. var c, count, i;
  19544. var localOffset = 0;
  19545. var pixels = new Uint8Array(pixel_size);
  19546. while (offset < pixel_total && localOffset < pixel_total) {
  19547. c = data[offset++];
  19548. count = (c & 0x7f) + 1;
  19549. if (c & 0x80) {
  19550. for (i = 0; i < pixel_size; ++i) {
  19551. pixels[i] = data[offset++];
  19552. }
  19553. for (i = 0; i < count; ++i) {
  19554. pixel_data.set(pixels, localOffset + i * pixel_size);
  19555. }
  19556. localOffset += pixel_size * count;
  19557. } else {
  19558. count *= pixel_size;
  19559. for (i = 0; i < count; ++i) {
  19560. pixel_data[localOffset + i] = data[offset++];
  19561. }
  19562. localOffset += count;
  19563. }
  19564. }
  19565. } else {
  19566. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  19567. }
  19568. var x_start, y_start, x_step, y_step, y_end, x_end;
  19569. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  19570. default:
  19571. case TGATools._ORIGIN_UL:
  19572. x_start = 0;
  19573. x_step = 1;
  19574. x_end = header.width;
  19575. y_start = 0;
  19576. y_step = 1;
  19577. y_end = header.height;
  19578. break;
  19579. case TGATools._ORIGIN_BL:
  19580. x_start = 0;
  19581. x_step = 1;
  19582. x_end = header.width;
  19583. y_start = header.height - 1;
  19584. y_step = -1;
  19585. y_end = -1;
  19586. break;
  19587. case TGATools._ORIGIN_UR:
  19588. x_start = header.width - 1;
  19589. x_step = -1;
  19590. x_end = -1;
  19591. y_start = 0;
  19592. y_step = 1;
  19593. y_end = header.height;
  19594. break;
  19595. case TGATools._ORIGIN_BR:
  19596. x_start = header.width - 1;
  19597. x_step = -1;
  19598. x_end = -1;
  19599. y_start = header.height - 1;
  19600. y_step = -1;
  19601. y_end = -1;
  19602. break;
  19603. }
  19604. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  19605. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  19606. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  19607. };
  19608. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  19609. var image = pixel_data, colormap = palettes;
  19610. var width = header.width, height = header.height;
  19611. var color, i = 0, x, y;
  19612. var imageData = new Uint8Array(width * height * 4);
  19613. for (y = y_start; y !== y_end; y += y_step) {
  19614. for (x = x_start; x !== x_end; x += x_step, i++) {
  19615. color = image[i];
  19616. imageData[(x + width * y) * 4 + 3] = 255;
  19617. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  19618. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  19619. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  19620. }
  19621. }
  19622. return imageData;
  19623. };
  19624. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  19625. var image = pixel_data;
  19626. var width = header.width, height = header.height;
  19627. var color, i = 0, x, y;
  19628. var imageData = new Uint8Array(width * height * 4);
  19629. for (y = y_start; y !== y_end; y += y_step) {
  19630. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  19631. color = image[i + 0] + (image[i + 1] << 8);
  19632. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  19633. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  19634. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  19635. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  19636. }
  19637. }
  19638. return imageData;
  19639. };
  19640. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  19641. var image = pixel_data;
  19642. var width = header.width, height = header.height;
  19643. var i = 0, x, y;
  19644. var imageData = new Uint8Array(width * height * 4);
  19645. for (y = y_start; y !== y_end; y += y_step) {
  19646. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  19647. imageData[(x + width * y) * 4 + 3] = 255;
  19648. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  19649. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  19650. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  19651. }
  19652. }
  19653. return imageData;
  19654. };
  19655. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  19656. var image = pixel_data;
  19657. var width = header.width, height = header.height;
  19658. var i = 0, x, y;
  19659. var imageData = new Uint8Array(width * height * 4);
  19660. for (y = y_start; y !== y_end; y += y_step) {
  19661. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  19662. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  19663. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  19664. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  19665. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  19666. }
  19667. }
  19668. return imageData;
  19669. };
  19670. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  19671. var image = pixel_data;
  19672. var width = header.width, height = header.height;
  19673. var color, i = 0, x, y;
  19674. var imageData = new Uint8Array(width * height * 4);
  19675. for (y = y_start; y !== y_end; y += y_step) {
  19676. for (x = x_start; x !== x_end; x += x_step, i++) {
  19677. color = image[i];
  19678. imageData[(x + width * y) * 4 + 0] = color;
  19679. imageData[(x + width * y) * 4 + 1] = color;
  19680. imageData[(x + width * y) * 4 + 2] = color;
  19681. imageData[(x + width * y) * 4 + 3] = 255;
  19682. }
  19683. }
  19684. return imageData;
  19685. };
  19686. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  19687. var image = pixel_data;
  19688. var width = header.width, height = header.height;
  19689. var i = 0, x, y;
  19690. var imageData = new Uint8Array(width * height * 4);
  19691. for (y = y_start; y !== y_end; y += y_step) {
  19692. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  19693. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  19694. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  19695. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  19696. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  19697. }
  19698. }
  19699. return imageData;
  19700. };
  19701. TGATools._TYPE_NO_DATA = 0;
  19702. TGATools._TYPE_INDEXED = 1;
  19703. TGATools._TYPE_RGB = 2;
  19704. TGATools._TYPE_GREY = 3;
  19705. TGATools._TYPE_RLE_INDEXED = 9;
  19706. TGATools._TYPE_RLE_RGB = 10;
  19707. TGATools._TYPE_RLE_GREY = 11;
  19708. TGATools._ORIGIN_MASK = 0x30;
  19709. TGATools._ORIGIN_SHIFT = 0x04;
  19710. TGATools._ORIGIN_BL = 0x00;
  19711. TGATools._ORIGIN_BR = 0x01;
  19712. TGATools._ORIGIN_UL = 0x02;
  19713. TGATools._ORIGIN_UR = 0x03;
  19714. return TGATools;
  19715. })();
  19716. Internals.TGATools = TGATools;
  19717. })(BABYLON.Internals || (BABYLON.Internals = {}));
  19718. var Internals = BABYLON.Internals;
  19719. })(BABYLON || (BABYLON = {}));
  19720. var BABYLON;
  19721. (function (BABYLON) {
  19722. (function (Internals) {
  19723. var DDS_MAGIC = 0x20534444;
  19724. 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;
  19725. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  19726. 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;
  19727. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  19728. function FourCCToInt32(value) {
  19729. return value.charCodeAt(0) + (value.charCodeAt(1) << 8) + (value.charCodeAt(2) << 16) + (value.charCodeAt(3) << 24);
  19730. }
  19731. function Int32ToFourCC(value) {
  19732. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  19733. }
  19734. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  19735. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  19736. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  19737. var headerLengthInt = 31;
  19738. var off_magic = 0;
  19739. var off_size = 1;
  19740. var off_flags = 2;
  19741. var off_height = 3;
  19742. var off_width = 4;
  19743. var off_mipmapCount = 7;
  19744. var off_pfFlags = 20;
  19745. var off_pfFourCC = 21;
  19746. var off_RGBbpp = 22;
  19747. var off_RMask = 23;
  19748. var off_GMask = 24;
  19749. var off_BMask = 25;
  19750. var off_AMask = 26;
  19751. var off_caps1 = 27;
  19752. var off_caps2 = 28;
  19753. ;
  19754. var DDSTools = (function () {
  19755. function DDSTools() {
  19756. }
  19757. DDSTools.GetDDSInfo = function (arrayBuffer) {
  19758. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  19759. var mipmapCount = 1;
  19760. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  19761. mipmapCount = Math.max(1, header[off_mipmapCount]);
  19762. }
  19763. return {
  19764. width: header[off_width],
  19765. height: header[off_height],
  19766. mipmapCount: mipmapCount,
  19767. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  19768. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  19769. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  19770. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  19771. };
  19772. };
  19773. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  19774. var byteArray = new Uint8Array(dataLength);
  19775. var srcData = new Uint8Array(arrayBuffer);
  19776. var index = 0;
  19777. for (var y = height - 1; y >= 0; y--) {
  19778. for (var x = 0; x < width; x++) {
  19779. var srcPos = dataOffset + (x + y * width) * 4;
  19780. byteArray[index + 2] = srcData[srcPos];
  19781. byteArray[index + 1] = srcData[srcPos + 1];
  19782. byteArray[index] = srcData[srcPos + 2];
  19783. byteArray[index + 3] = srcData[srcPos + 3];
  19784. index += 4;
  19785. }
  19786. }
  19787. return byteArray;
  19788. };
  19789. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  19790. var byteArray = new Uint8Array(dataLength);
  19791. var srcData = new Uint8Array(arrayBuffer);
  19792. var index = 0;
  19793. for (var y = height - 1; y >= 0; y--) {
  19794. for (var x = 0; x < width; x++) {
  19795. var srcPos = dataOffset + (x + y * width) * 3;
  19796. byteArray[index + 2] = srcData[srcPos];
  19797. byteArray[index + 1] = srcData[srcPos + 1];
  19798. byteArray[index] = srcData[srcPos + 2];
  19799. index += 3;
  19800. }
  19801. }
  19802. return byteArray;
  19803. };
  19804. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  19805. var byteArray = new Uint8Array(dataLength);
  19806. var srcData = new Uint8Array(arrayBuffer);
  19807. var index = 0;
  19808. for (var y = height - 1; y >= 0; y--) {
  19809. for (var x = 0; x < width; x++) {
  19810. var srcPos = dataOffset + (x + y * width);
  19811. byteArray[index] = srcData[srcPos];
  19812. index++;
  19813. }
  19814. }
  19815. return byteArray;
  19816. };
  19817. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  19818. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  19819. if (header[off_magic] != DDS_MAGIC) {
  19820. BABYLON.Tools.Error("Invalid magic number in DDS header");
  19821. return;
  19822. }
  19823. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  19824. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  19825. return;
  19826. }
  19827. if (info.isFourCC) {
  19828. fourCC = header[off_pfFourCC];
  19829. switch (fourCC) {
  19830. case FOURCC_DXT1:
  19831. blockBytes = 8;
  19832. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  19833. break;
  19834. case FOURCC_DXT3:
  19835. blockBytes = 16;
  19836. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  19837. break;
  19838. case FOURCC_DXT5:
  19839. blockBytes = 16;
  19840. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  19841. break;
  19842. default:
  19843. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  19844. return;
  19845. }
  19846. }
  19847. mipmapCount = 1;
  19848. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  19849. mipmapCount = Math.max(1, header[off_mipmapCount]);
  19850. }
  19851. var bpp = header[off_RGBbpp];
  19852. for (var face = 0; face < faces; face++) {
  19853. var sampler = faces == 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  19854. width = header[off_width];
  19855. height = header[off_height];
  19856. dataOffset = header[off_size] + 4;
  19857. for (i = 0; i < mipmapCount; ++i) {
  19858. if (info.isRGB) {
  19859. if (bpp == 24) {
  19860. dataLength = width * height * 3;
  19861. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  19862. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  19863. } else {
  19864. dataLength = width * height * 4;
  19865. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  19866. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  19867. }
  19868. } else if (info.isLuminance) {
  19869. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  19870. var unpaddedRowSize = width;
  19871. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  19872. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  19873. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  19874. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  19875. } else {
  19876. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  19877. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  19878. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  19879. }
  19880. dataOffset += dataLength;
  19881. width *= 0.5;
  19882. height *= 0.5;
  19883. width = Math.max(1.0, width);
  19884. height = Math.max(1.0, height);
  19885. }
  19886. }
  19887. };
  19888. return DDSTools;
  19889. })();
  19890. Internals.DDSTools = DDSTools;
  19891. })(BABYLON.Internals || (BABYLON.Internals = {}));
  19892. var Internals = BABYLON.Internals;
  19893. })(BABYLON || (BABYLON = {}));
  19894. var BABYLON;
  19895. (function (BABYLON) {
  19896. var SmartArray = (function () {
  19897. function SmartArray(capacity) {
  19898. this.length = 0;
  19899. this._duplicateId = 0;
  19900. this.data = new Array(capacity);
  19901. this._id = SmartArray._GlobalId++;
  19902. }
  19903. SmartArray.prototype.push = function (value) {
  19904. this.data[this.length++] = value;
  19905. if (this.length > this.data.length) {
  19906. this.data.length *= 2;
  19907. }
  19908. if (!value.__smartArrayFlags) {
  19909. value.__smartArrayFlags = {};
  19910. }
  19911. value.__smartArrayFlags[this._id] = this._duplicateId;
  19912. };
  19913. SmartArray.prototype.pushNoDuplicate = function (value) {
  19914. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  19915. return;
  19916. }
  19917. this.push(value);
  19918. };
  19919. SmartArray.prototype.sort = function (compareFn) {
  19920. this.data.sort(compareFn);
  19921. };
  19922. SmartArray.prototype.reset = function () {
  19923. this.length = 0;
  19924. this._duplicateId++;
  19925. };
  19926. SmartArray.prototype.concat = function (array) {
  19927. if (array.length === 0) {
  19928. return;
  19929. }
  19930. if (this.length + array.length > this.data.length) {
  19931. this.data.length = (this.length + array.length) * 2;
  19932. }
  19933. for (var index = 0; index < array.length; index++) {
  19934. this.data[this.length++] = (array.data || array)[index];
  19935. }
  19936. };
  19937. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  19938. if (array.length === 0) {
  19939. return;
  19940. }
  19941. if (this.length + array.length > this.data.length) {
  19942. this.data.length = (this.length + array.length) * 2;
  19943. }
  19944. for (var index = 0; index < array.length; index++) {
  19945. var item = (array.data || array)[index];
  19946. this.pushNoDuplicate(item);
  19947. }
  19948. };
  19949. SmartArray.prototype.indexOf = function (value) {
  19950. var position = this.data.indexOf(value);
  19951. if (position >= this.length) {
  19952. return -1;
  19953. }
  19954. return position;
  19955. };
  19956. SmartArray._GlobalId = 0;
  19957. return SmartArray;
  19958. })();
  19959. BABYLON.SmartArray = SmartArray;
  19960. })(BABYLON || (BABYLON = {}));
  19961. var BABYLON;
  19962. (function (BABYLON) {
  19963. var CannonJSPlugin = (function () {
  19964. function CannonJSPlugin() {
  19965. this._registeredMeshes = [];
  19966. this._physicsMaterials = [];
  19967. this.updateBodyPosition = function (mesh) {
  19968. for (var index = 0; index < this._registeredMeshes.length; index++) {
  19969. var registeredMesh = this._registeredMeshes[index];
  19970. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  19971. var body = registeredMesh.body;
  19972. var center = mesh.getBoundingInfo().boundingBox.center;
  19973. body.position.set(center.x, center.z, center.y);
  19974. body.quaternion.x = mesh.rotationQuaternion.x;
  19975. body.quaternion.z = mesh.rotationQuaternion.y;
  19976. body.quaternion.y = mesh.rotationQuaternion.z;
  19977. body.quaternion.w = -mesh.rotationQuaternion.w;
  19978. return;
  19979. }
  19980. }
  19981. };
  19982. }
  19983. CannonJSPlugin.prototype.initialize = function (iterations) {
  19984. if (typeof iterations === "undefined") { iterations = 10; }
  19985. this._world = new CANNON.World();
  19986. this._world.broadphase = new CANNON.NaiveBroadphase();
  19987. this._world.solver.iterations = iterations;
  19988. };
  19989. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  19990. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  19991. };
  19992. CannonJSPlugin.prototype.runOneStep = function (delta) {
  19993. this._world.step(delta);
  19994. for (var index = 0; index < this._registeredMeshes.length; index++) {
  19995. var registeredMesh = this._registeredMeshes[index];
  19996. if (registeredMesh.isChild) {
  19997. continue;
  19998. }
  19999. var bodyX = registeredMesh.body.position.x, bodyY = registeredMesh.body.position.y, bodyZ = registeredMesh.body.position.z;
  20000. var deltaPos = registeredMesh.delta;
  20001. if (deltaPos) {
  20002. registeredMesh.mesh.position.x = bodyX + deltaPos.x;
  20003. registeredMesh.mesh.position.y = bodyZ + deltaPos.y;
  20004. registeredMesh.mesh.position.z = bodyY + deltaPos.z;
  20005. } else {
  20006. registeredMesh.mesh.position.x = bodyX;
  20007. registeredMesh.mesh.position.y = bodyZ;
  20008. registeredMesh.mesh.position.z = bodyY;
  20009. }
  20010. if (!registeredMesh.mesh.rotationQuaternion) {
  20011. registeredMesh.mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  20012. }
  20013. registeredMesh.mesh.rotationQuaternion.x = registeredMesh.body.quaternion.x;
  20014. registeredMesh.mesh.rotationQuaternion.y = registeredMesh.body.quaternion.z;
  20015. registeredMesh.mesh.rotationQuaternion.z = registeredMesh.body.quaternion.y;
  20016. registeredMesh.mesh.rotationQuaternion.w = -registeredMesh.body.quaternion.w;
  20017. }
  20018. };
  20019. CannonJSPlugin.prototype.setGravity = function (gravity) {
  20020. this._world.gravity.set(gravity.x, gravity.z, gravity.y);
  20021. };
  20022. CannonJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  20023. this.unregisterMesh(mesh);
  20024. mesh.computeWorldMatrix(true);
  20025. switch (impostor) {
  20026. case BABYLON.PhysicsEngine.SphereImpostor:
  20027. var bbox = mesh.getBoundingInfo().boundingBox;
  20028. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  20029. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  20030. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  20031. return this._createSphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2, mesh, options);
  20032. case BABYLON.PhysicsEngine.BoxImpostor:
  20033. bbox = mesh.getBoundingInfo().boundingBox;
  20034. var min = bbox.minimumWorld;
  20035. var max = bbox.maximumWorld;
  20036. var box = max.subtract(min).scale(0.5);
  20037. return this._createBox(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z), mesh, options);
  20038. case BABYLON.PhysicsEngine.PlaneImpostor:
  20039. return this._createPlane(mesh, options);
  20040. case BABYLON.PhysicsEngine.MeshImpostor:
  20041. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20042. var rawFaces = mesh.getIndices();
  20043. return this._createConvexPolyhedron(rawVerts, rawFaces, mesh, options);
  20044. }
  20045. return null;
  20046. };
  20047. CannonJSPlugin.prototype._createSphere = function (radius, mesh, options) {
  20048. var shape = new CANNON.Sphere(radius);
  20049. if (!options) {
  20050. return shape;
  20051. }
  20052. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  20053. };
  20054. CannonJSPlugin.prototype._createBox = function (x, y, z, mesh, options) {
  20055. var shape = new CANNON.Box(new CANNON.Vec3(x, z, y));
  20056. if (!options) {
  20057. return shape;
  20058. }
  20059. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  20060. };
  20061. CannonJSPlugin.prototype._createPlane = function (mesh, options) {
  20062. var shape = new CANNON.Plane();
  20063. if (!options) {
  20064. return shape;
  20065. }
  20066. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  20067. };
  20068. CannonJSPlugin.prototype._createConvexPolyhedron = function (rawVerts, rawFaces, mesh, options) {
  20069. var verts = [], faces = [];
  20070. mesh.computeWorldMatrix(true);
  20071. for (var i = 0; i < rawVerts.length; i += 3) {
  20072. var transformed = BABYLON.Vector3.Zero();
  20073. BABYLON.Vector3.TransformNormalFromFloatsToRef(rawVerts[i], rawVerts[i + 1], rawVerts[i + 2], mesh.getWorldMatrix(), transformed);
  20074. verts.push(new CANNON.Vec3(transformed.x, transformed.z, transformed.y));
  20075. }
  20076. for (var j = 0; j < rawFaces.length; j += 3) {
  20077. faces.push([rawFaces[j], rawFaces[j + 2], rawFaces[j + 1]]);
  20078. }
  20079. var shape = new CANNON.ConvexPolyhedron(verts, faces);
  20080. if (!options) {
  20081. return shape;
  20082. }
  20083. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  20084. };
  20085. CannonJSPlugin.prototype._addMaterial = function (friction, restitution) {
  20086. var index;
  20087. var mat;
  20088. for (index = 0; index < this._physicsMaterials.length; index++) {
  20089. mat = this._physicsMaterials[index];
  20090. if (mat.friction === friction && mat.restitution === restitution) {
  20091. return mat;
  20092. }
  20093. }
  20094. var currentMat = new CANNON.Material();
  20095. currentMat.friction = friction;
  20096. currentMat.restitution = restitution;
  20097. this._physicsMaterials.push(currentMat);
  20098. for (index = 0; index < this._physicsMaterials.length; index++) {
  20099. mat = this._physicsMaterials[index];
  20100. var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, mat.friction * currentMat.friction, mat.restitution * currentMat.restitution);
  20101. contactMaterial.contactEquationStiffness = 1e10;
  20102. contactMaterial.contactEquationRegularizationTime = 10;
  20103. this._world.addContactMaterial(contactMaterial);
  20104. }
  20105. return currentMat;
  20106. };
  20107. CannonJSPlugin.prototype._createRigidBodyFromShape = function (shape, mesh, mass, friction, restitution) {
  20108. var initialRotation = null;
  20109. if (mesh.rotationQuaternion) {
  20110. initialRotation = mesh.rotationQuaternion.clone();
  20111. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  20112. }
  20113. var bbox = mesh.getBoundingInfo().boundingBox;
  20114. var deltaPosition = mesh.position.subtract(bbox.center);
  20115. var material = this._addMaterial(friction, restitution);
  20116. var body = new CANNON.RigidBody(mass, shape, material);
  20117. if (initialRotation) {
  20118. body.quaternion.x = initialRotation.x;
  20119. body.quaternion.z = initialRotation.y;
  20120. body.quaternion.y = initialRotation.z;
  20121. body.quaternion.w = -initialRotation.w;
  20122. }
  20123. body.position.set(bbox.center.x, bbox.center.z, bbox.center.y);
  20124. this._world.add(body);
  20125. this._registeredMeshes.push({ mesh: mesh, body: body, material: material, delta: deltaPosition });
  20126. return body;
  20127. };
  20128. CannonJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  20129. var compoundShape = new CANNON.Compound();
  20130. for (var index = 0; index < parts.length; index++) {
  20131. var mesh = parts[index].mesh;
  20132. var shape = this.registerMesh(mesh, parts[index].impostor);
  20133. if (index == 0) {
  20134. compoundShape.addChild(shape, new CANNON.Vec3(0, 0, 0));
  20135. } else {
  20136. compoundShape.addChild(shape, new CANNON.Vec3(mesh.position.x, mesh.position.z, mesh.position.y));
  20137. }
  20138. }
  20139. var initialMesh = parts[0].mesh;
  20140. var body = this._createRigidBodyFromShape(compoundShape, initialMesh, options.mass, options.friction, options.restitution);
  20141. body.parts = parts;
  20142. return body;
  20143. };
  20144. CannonJSPlugin.prototype._unbindBody = function (body) {
  20145. for (var index = 0; index < this._registeredMeshes.length; index++) {
  20146. var registeredMesh = this._registeredMeshes[index];
  20147. if (registeredMesh.body === body) {
  20148. registeredMesh.body = null;
  20149. registeredMesh.delta = 0;
  20150. }
  20151. }
  20152. };
  20153. CannonJSPlugin.prototype.unregisterMesh = function (mesh) {
  20154. for (var index = 0; index < this._registeredMeshes.length; index++) {
  20155. var registeredMesh = this._registeredMeshes[index];
  20156. if (registeredMesh.mesh === mesh) {
  20157. if (registeredMesh.body) {
  20158. this._world.remove(registeredMesh.body);
  20159. this._unbindBody(registeredMesh.body);
  20160. }
  20161. this._registeredMeshes.splice(index, 1);
  20162. return;
  20163. }
  20164. }
  20165. };
  20166. CannonJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  20167. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.z, contactPoint.y);
  20168. var impulse = new CANNON.Vec3(force.x, force.z, force.y);
  20169. for (var index = 0; index < this._registeredMeshes.length; index++) {
  20170. var registeredMesh = this._registeredMeshes[index];
  20171. if (registeredMesh.mesh === mesh) {
  20172. registeredMesh.body.applyImpulse(impulse, worldPoint);
  20173. return;
  20174. }
  20175. }
  20176. };
  20177. CannonJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2) {
  20178. var body1 = null, body2 = null;
  20179. for (var index = 0; index < this._registeredMeshes.length; index++) {
  20180. var registeredMesh = this._registeredMeshes[index];
  20181. if (registeredMesh.mesh === mesh1) {
  20182. body1 = registeredMesh.body;
  20183. } else if (registeredMesh.mesh === mesh2) {
  20184. body2 = registeredMesh.body;
  20185. }
  20186. }
  20187. if (!body1 || !body2) {
  20188. return false;
  20189. }
  20190. 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));
  20191. this._world.addConstraint(constraint);
  20192. return true;
  20193. };
  20194. CannonJSPlugin.prototype.dispose = function () {
  20195. while (this._registeredMeshes.length) {
  20196. this.unregisterMesh(this._registeredMeshes[0].mesh);
  20197. }
  20198. };
  20199. CannonJSPlugin.prototype.isSupported = function () {
  20200. return window.CANNON !== undefined;
  20201. };
  20202. return CannonJSPlugin;
  20203. })();
  20204. BABYLON.CannonJSPlugin = CannonJSPlugin;
  20205. })(BABYLON || (BABYLON = {}));
  20206. var __extends = this.__extends || function (d, b) {
  20207. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  20208. function __() { this.constructor = d; }
  20209. __.prototype = b.prototype;
  20210. d.prototype = new __();
  20211. };
  20212. var BABYLON;
  20213. (function (BABYLON) {
  20214. var Condition = (function () {
  20215. function Condition(actionManager) {
  20216. this._actionManager = actionManager;
  20217. }
  20218. Condition.prototype.isValid = function () {
  20219. return true;
  20220. };
  20221. Condition.prototype._getProperty = function (propertyPath) {
  20222. return this._actionManager._getProperty(propertyPath);
  20223. };
  20224. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  20225. return this._actionManager._getEffectiveTarget(target, propertyPath);
  20226. };
  20227. return Condition;
  20228. })();
  20229. BABYLON.Condition = Condition;
  20230. var ValueCondition = (function (_super) {
  20231. __extends(ValueCondition, _super);
  20232. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  20233. if (typeof operator === "undefined") { operator = ValueCondition.IsEqual; }
  20234. _super.call(this, actionManager);
  20235. this.propertyPath = propertyPath;
  20236. this.value = value;
  20237. this.operator = operator;
  20238. this._target = this._getEffectiveTarget(target, this.propertyPath);
  20239. this._property = this._getProperty(this.propertyPath);
  20240. }
  20241. Object.defineProperty(ValueCondition, "IsEqual", {
  20242. get: function () {
  20243. return ValueCondition._IsEqual;
  20244. },
  20245. enumerable: true,
  20246. configurable: true
  20247. });
  20248. Object.defineProperty(ValueCondition, "IsDifferent", {
  20249. get: function () {
  20250. return ValueCondition._IsDifferent;
  20251. },
  20252. enumerable: true,
  20253. configurable: true
  20254. });
  20255. Object.defineProperty(ValueCondition, "IsGreater", {
  20256. get: function () {
  20257. return ValueCondition._IsGreater;
  20258. },
  20259. enumerable: true,
  20260. configurable: true
  20261. });
  20262. Object.defineProperty(ValueCondition, "IsLesser", {
  20263. get: function () {
  20264. return ValueCondition._IsLesser;
  20265. },
  20266. enumerable: true,
  20267. configurable: true
  20268. });
  20269. ValueCondition.prototype.isValid = function () {
  20270. switch (this.operator) {
  20271. case ValueCondition.IsGreater:
  20272. return this._target[this._property] > this.value;
  20273. case ValueCondition.IsLesser:
  20274. return this._target[this._property] < this.value;
  20275. case ValueCondition.IsEqual:
  20276. case ValueCondition.IsDifferent:
  20277. var check;
  20278. if (this.value.equals) {
  20279. check = this.value.equals(this._target[this._property]);
  20280. } else {
  20281. check = this.value === this._target[this._property];
  20282. }
  20283. return this.operator === ValueCondition.IsEqual ? check : !check;
  20284. }
  20285. return false;
  20286. };
  20287. ValueCondition._IsEqual = 0;
  20288. ValueCondition._IsDifferent = 1;
  20289. ValueCondition._IsGreater = 2;
  20290. ValueCondition._IsLesser = 3;
  20291. return ValueCondition;
  20292. })(Condition);
  20293. BABYLON.ValueCondition = ValueCondition;
  20294. var PredicateCondition = (function (_super) {
  20295. __extends(PredicateCondition, _super);
  20296. function PredicateCondition(actionManager, predicate) {
  20297. _super.call(this, actionManager);
  20298. this.predicate = predicate;
  20299. }
  20300. PredicateCondition.prototype.isValid = function () {
  20301. return this.predicate();
  20302. };
  20303. return PredicateCondition;
  20304. })(Condition);
  20305. BABYLON.PredicateCondition = PredicateCondition;
  20306. var StateCondition = (function (_super) {
  20307. __extends(StateCondition, _super);
  20308. function StateCondition(actionManager, target, value) {
  20309. _super.call(this, actionManager);
  20310. this.value = value;
  20311. this._target = target;
  20312. }
  20313. StateCondition.prototype.isValid = function () {
  20314. return this._target.state === this.value;
  20315. };
  20316. return StateCondition;
  20317. })(Condition);
  20318. BABYLON.StateCondition = StateCondition;
  20319. })(BABYLON || (BABYLON = {}));
  20320. var BABYLON;
  20321. (function (BABYLON) {
  20322. var Action = (function () {
  20323. function Action(triggerOptions, condition) {
  20324. this.triggerOptions = triggerOptions;
  20325. if (triggerOptions.parameter) {
  20326. this.trigger = triggerOptions.trigger;
  20327. this._triggerParameter = triggerOptions.parameter;
  20328. } else {
  20329. this.trigger = triggerOptions;
  20330. }
  20331. this._nextActiveAction = this;
  20332. this._condition = condition;
  20333. }
  20334. Action.prototype._prepare = function () {
  20335. };
  20336. Action.prototype.getTriggerParameter = function () {
  20337. return this._triggerParameter;
  20338. };
  20339. Action.prototype._executeCurrent = function (evt) {
  20340. if (this._condition) {
  20341. var currentRenderId = this._actionManager.getScene().getRenderId();
  20342. if (this._condition._evaluationId === currentRenderId) {
  20343. if (!this._condition._currentResult) {
  20344. return;
  20345. }
  20346. } else {
  20347. this._condition._evaluationId = currentRenderId;
  20348. if (!this._condition.isValid()) {
  20349. this._condition._currentResult = false;
  20350. return;
  20351. }
  20352. this._condition._currentResult = true;
  20353. }
  20354. }
  20355. this._nextActiveAction.execute(evt);
  20356. if (this._nextActiveAction._child) {
  20357. if (!this._nextActiveAction._child._actionManager) {
  20358. this._nextActiveAction._child._actionManager = this._actionManager;
  20359. }
  20360. this._nextActiveAction = this._nextActiveAction._child;
  20361. } else {
  20362. this._nextActiveAction = this;
  20363. }
  20364. };
  20365. Action.prototype.execute = function (evt) {
  20366. };
  20367. Action.prototype.then = function (action) {
  20368. this._child = action;
  20369. action._actionManager = this._actionManager;
  20370. action._prepare();
  20371. return action;
  20372. };
  20373. Action.prototype._getProperty = function (propertyPath) {
  20374. return this._actionManager._getProperty(propertyPath);
  20375. };
  20376. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  20377. return this._actionManager._getEffectiveTarget(target, propertyPath);
  20378. };
  20379. return Action;
  20380. })();
  20381. BABYLON.Action = Action;
  20382. })(BABYLON || (BABYLON = {}));
  20383. var BABYLON;
  20384. (function (BABYLON) {
  20385. var ActionEvent = (function () {
  20386. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent) {
  20387. this.source = source;
  20388. this.pointerX = pointerX;
  20389. this.pointerY = pointerY;
  20390. this.meshUnderPointer = meshUnderPointer;
  20391. this.sourceEvent = sourceEvent;
  20392. }
  20393. ActionEvent.CreateNew = function (source) {
  20394. var scene = source.getScene();
  20395. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer);
  20396. };
  20397. ActionEvent.CreateNewFromScene = function (scene, evt) {
  20398. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  20399. };
  20400. return ActionEvent;
  20401. })();
  20402. BABYLON.ActionEvent = ActionEvent;
  20403. var ActionManager = (function () {
  20404. function ActionManager(scene) {
  20405. this.actions = new Array();
  20406. this._scene = scene;
  20407. scene._actionManagers.push(this);
  20408. }
  20409. Object.defineProperty(ActionManager, "NothingTrigger", {
  20410. get: function () {
  20411. return ActionManager._NothingTrigger;
  20412. },
  20413. enumerable: true,
  20414. configurable: true
  20415. });
  20416. Object.defineProperty(ActionManager, "OnPickTrigger", {
  20417. get: function () {
  20418. return ActionManager._OnPickTrigger;
  20419. },
  20420. enumerable: true,
  20421. configurable: true
  20422. });
  20423. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  20424. get: function () {
  20425. return ActionManager._OnLeftPickTrigger;
  20426. },
  20427. enumerable: true,
  20428. configurable: true
  20429. });
  20430. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  20431. get: function () {
  20432. return ActionManager._OnRightPickTrigger;
  20433. },
  20434. enumerable: true,
  20435. configurable: true
  20436. });
  20437. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  20438. get: function () {
  20439. return ActionManager._OnCenterPickTrigger;
  20440. },
  20441. enumerable: true,
  20442. configurable: true
  20443. });
  20444. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  20445. get: function () {
  20446. return ActionManager._OnPointerOverTrigger;
  20447. },
  20448. enumerable: true,
  20449. configurable: true
  20450. });
  20451. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  20452. get: function () {
  20453. return ActionManager._OnPointerOutTrigger;
  20454. },
  20455. enumerable: true,
  20456. configurable: true
  20457. });
  20458. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  20459. get: function () {
  20460. return ActionManager._OnEveryFrameTrigger;
  20461. },
  20462. enumerable: true,
  20463. configurable: true
  20464. });
  20465. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  20466. get: function () {
  20467. return ActionManager._OnIntersectionEnterTrigger;
  20468. },
  20469. enumerable: true,
  20470. configurable: true
  20471. });
  20472. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  20473. get: function () {
  20474. return ActionManager._OnIntersectionExitTrigger;
  20475. },
  20476. enumerable: true,
  20477. configurable: true
  20478. });
  20479. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  20480. get: function () {
  20481. return ActionManager._OnKeyDownTrigger;
  20482. },
  20483. enumerable: true,
  20484. configurable: true
  20485. });
  20486. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  20487. get: function () {
  20488. return ActionManager._OnKeyUpTrigger;
  20489. },
  20490. enumerable: true,
  20491. configurable: true
  20492. });
  20493. ActionManager.prototype.dispose = function () {
  20494. var index = this._scene._actionManagers.indexOf(this);
  20495. if (index > -1) {
  20496. this._scene._actionManagers.splice(index, 1);
  20497. }
  20498. };
  20499. ActionManager.prototype.getScene = function () {
  20500. return this._scene;
  20501. };
  20502. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  20503. for (var index = 0; index < this.actions.length; index++) {
  20504. var action = this.actions[index];
  20505. if (triggers.indexOf(action.trigger) > -1) {
  20506. return true;
  20507. }
  20508. }
  20509. return false;
  20510. };
  20511. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  20512. get: function () {
  20513. for (var index = 0; index < this.actions.length; index++) {
  20514. var action = this.actions[index];
  20515. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  20516. return true;
  20517. }
  20518. }
  20519. return false;
  20520. },
  20521. enumerable: true,
  20522. configurable: true
  20523. });
  20524. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  20525. get: function () {
  20526. for (var index = 0; index < this.actions.length; index++) {
  20527. var action = this.actions[index];
  20528. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnCenterPickTrigger) {
  20529. return true;
  20530. }
  20531. }
  20532. return false;
  20533. },
  20534. enumerable: true,
  20535. configurable: true
  20536. });
  20537. ActionManager.prototype.registerAction = function (action) {
  20538. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  20539. if (this.getScene().actionManager !== this) {
  20540. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  20541. return null;
  20542. }
  20543. }
  20544. this.actions.push(action);
  20545. action._actionManager = this;
  20546. action._prepare();
  20547. return action;
  20548. };
  20549. ActionManager.prototype.processTrigger = function (trigger, evt) {
  20550. for (var index = 0; index < this.actions.length; index++) {
  20551. var action = this.actions[index];
  20552. if (action.trigger === trigger) {
  20553. if (trigger == ActionManager.OnKeyUpTrigger || trigger == ActionManager.OnKeyDownTrigger) {
  20554. var parameter = action.getTriggerParameter();
  20555. if (parameter) {
  20556. if (evt.sourceEvent.key !== parameter) {
  20557. continue;
  20558. }
  20559. }
  20560. }
  20561. action._executeCurrent(evt);
  20562. }
  20563. }
  20564. };
  20565. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  20566. var properties = propertyPath.split(".");
  20567. for (var index = 0; index < properties.length - 1; index++) {
  20568. target = target[properties[index]];
  20569. }
  20570. return target;
  20571. };
  20572. ActionManager.prototype._getProperty = function (propertyPath) {
  20573. var properties = propertyPath.split(".");
  20574. return properties[properties.length - 1];
  20575. };
  20576. ActionManager._NothingTrigger = 0;
  20577. ActionManager._OnPickTrigger = 1;
  20578. ActionManager._OnLeftPickTrigger = 2;
  20579. ActionManager._OnRightPickTrigger = 3;
  20580. ActionManager._OnCenterPickTrigger = 4;
  20581. ActionManager._OnPointerOverTrigger = 5;
  20582. ActionManager._OnPointerOutTrigger = 6;
  20583. ActionManager._OnEveryFrameTrigger = 7;
  20584. ActionManager._OnIntersectionEnterTrigger = 8;
  20585. ActionManager._OnIntersectionExitTrigger = 9;
  20586. ActionManager._OnKeyDownTrigger = 10;
  20587. ActionManager._OnKeyUpTrigger = 11;
  20588. return ActionManager;
  20589. })();
  20590. BABYLON.ActionManager = ActionManager;
  20591. })(BABYLON || (BABYLON = {}));
  20592. var __extends = this.__extends || function (d, b) {
  20593. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  20594. function __() { this.constructor = d; }
  20595. __.prototype = b.prototype;
  20596. d.prototype = new __();
  20597. };
  20598. var BABYLON;
  20599. (function (BABYLON) {
  20600. var InterpolateValueAction = (function (_super) {
  20601. __extends(InterpolateValueAction, _super);
  20602. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations) {
  20603. if (typeof duration === "undefined") { duration = 1000; }
  20604. _super.call(this, triggerOptions, condition);
  20605. this.propertyPath = propertyPath;
  20606. this.value = value;
  20607. this.duration = duration;
  20608. this.stopOtherAnimations = stopOtherAnimations;
  20609. this._target = target;
  20610. }
  20611. InterpolateValueAction.prototype._prepare = function () {
  20612. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  20613. this._property = this._getProperty(this.propertyPath);
  20614. };
  20615. InterpolateValueAction.prototype.execute = function () {
  20616. var scene = this._actionManager.getScene();
  20617. var keys = [
  20618. {
  20619. frame: 0,
  20620. value: this._target[this._property]
  20621. }, {
  20622. frame: 100,
  20623. value: this.value
  20624. }
  20625. ];
  20626. var dataType;
  20627. if (typeof this.value === "number") {
  20628. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  20629. } else if (this.value instanceof BABYLON.Color3) {
  20630. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  20631. } else if (this.value instanceof BABYLON.Vector3) {
  20632. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  20633. } else if (this.value instanceof BABYLON.Matrix) {
  20634. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  20635. } else if (this.value instanceof BABYLON.Quaternion) {
  20636. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  20637. } else {
  20638. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  20639. return;
  20640. }
  20641. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  20642. animation.setKeys(keys);
  20643. if (this.stopOtherAnimations) {
  20644. scene.stopAnimation(this._target);
  20645. }
  20646. scene.beginDirectAnimation(this._target, [animation], 0, 100);
  20647. };
  20648. return InterpolateValueAction;
  20649. })(BABYLON.Action);
  20650. BABYLON.InterpolateValueAction = InterpolateValueAction;
  20651. })(BABYLON || (BABYLON = {}));
  20652. var __extends = this.__extends || function (d, b) {
  20653. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  20654. function __() { this.constructor = d; }
  20655. __.prototype = b.prototype;
  20656. d.prototype = new __();
  20657. };
  20658. var BABYLON;
  20659. (function (BABYLON) {
  20660. var SwitchBooleanAction = (function (_super) {
  20661. __extends(SwitchBooleanAction, _super);
  20662. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  20663. _super.call(this, triggerOptions, condition);
  20664. this.propertyPath = propertyPath;
  20665. this._target = target;
  20666. }
  20667. SwitchBooleanAction.prototype._prepare = function () {
  20668. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  20669. this._property = this._getProperty(this.propertyPath);
  20670. };
  20671. SwitchBooleanAction.prototype.execute = function () {
  20672. this._target[this._property] = !this._target[this._property];
  20673. };
  20674. return SwitchBooleanAction;
  20675. })(BABYLON.Action);
  20676. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  20677. var SetStateAction = (function (_super) {
  20678. __extends(SetStateAction, _super);
  20679. function SetStateAction(triggerOptions, target, value, condition) {
  20680. _super.call(this, triggerOptions, condition);
  20681. this.value = value;
  20682. this._target = target;
  20683. }
  20684. SetStateAction.prototype.execute = function () {
  20685. this._target.state = this.value;
  20686. };
  20687. return SetStateAction;
  20688. })(BABYLON.Action);
  20689. BABYLON.SetStateAction = SetStateAction;
  20690. var SetValueAction = (function (_super) {
  20691. __extends(SetValueAction, _super);
  20692. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  20693. _super.call(this, triggerOptions, condition);
  20694. this.propertyPath = propertyPath;
  20695. this.value = value;
  20696. this._target = target;
  20697. }
  20698. SetValueAction.prototype._prepare = function () {
  20699. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  20700. this._property = this._getProperty(this.propertyPath);
  20701. };
  20702. SetValueAction.prototype.execute = function () {
  20703. this._target[this._property] = this.value;
  20704. };
  20705. return SetValueAction;
  20706. })(BABYLON.Action);
  20707. BABYLON.SetValueAction = SetValueAction;
  20708. var IncrementValueAction = (function (_super) {
  20709. __extends(IncrementValueAction, _super);
  20710. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  20711. _super.call(this, triggerOptions, condition);
  20712. this.propertyPath = propertyPath;
  20713. this.value = value;
  20714. this._target = target;
  20715. }
  20716. IncrementValueAction.prototype._prepare = function () {
  20717. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  20718. this._property = this._getProperty(this.propertyPath);
  20719. if (typeof this._target[this._property] !== "number") {
  20720. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  20721. }
  20722. };
  20723. IncrementValueAction.prototype.execute = function () {
  20724. this._target[this._property] += this.value;
  20725. };
  20726. return IncrementValueAction;
  20727. })(BABYLON.Action);
  20728. BABYLON.IncrementValueAction = IncrementValueAction;
  20729. var PlayAnimationAction = (function (_super) {
  20730. __extends(PlayAnimationAction, _super);
  20731. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  20732. _super.call(this, triggerOptions, condition);
  20733. this.from = from;
  20734. this.to = to;
  20735. this.loop = loop;
  20736. this._target = target;
  20737. }
  20738. PlayAnimationAction.prototype._prepare = function () {
  20739. };
  20740. PlayAnimationAction.prototype.execute = function () {
  20741. var scene = this._actionManager.getScene();
  20742. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  20743. };
  20744. return PlayAnimationAction;
  20745. })(BABYLON.Action);
  20746. BABYLON.PlayAnimationAction = PlayAnimationAction;
  20747. var StopAnimationAction = (function (_super) {
  20748. __extends(StopAnimationAction, _super);
  20749. function StopAnimationAction(triggerOptions, target, condition) {
  20750. _super.call(this, triggerOptions, condition);
  20751. this._target = target;
  20752. }
  20753. StopAnimationAction.prototype._prepare = function () {
  20754. };
  20755. StopAnimationAction.prototype.execute = function () {
  20756. var scene = this._actionManager.getScene();
  20757. scene.stopAnimation(this._target);
  20758. };
  20759. return StopAnimationAction;
  20760. })(BABYLON.Action);
  20761. BABYLON.StopAnimationAction = StopAnimationAction;
  20762. var DoNothingAction = (function (_super) {
  20763. __extends(DoNothingAction, _super);
  20764. function DoNothingAction(triggerOptions, condition) {
  20765. if (typeof triggerOptions === "undefined") { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  20766. _super.call(this, triggerOptions, condition);
  20767. }
  20768. DoNothingAction.prototype.execute = function () {
  20769. };
  20770. return DoNothingAction;
  20771. })(BABYLON.Action);
  20772. BABYLON.DoNothingAction = DoNothingAction;
  20773. var CombineAction = (function (_super) {
  20774. __extends(CombineAction, _super);
  20775. function CombineAction(triggerOptions, children, condition) {
  20776. _super.call(this, triggerOptions, condition);
  20777. this.children = children;
  20778. }
  20779. CombineAction.prototype._prepare = function () {
  20780. for (var index = 0; index < this.children.length; index++) {
  20781. this.children[index]._actionManager = this._actionManager;
  20782. this.children[index]._prepare();
  20783. }
  20784. };
  20785. CombineAction.prototype.execute = function (evt) {
  20786. for (var index = 0; index < this.children.length; index++) {
  20787. this.children[index].execute(evt);
  20788. }
  20789. };
  20790. return CombineAction;
  20791. })(BABYLON.Action);
  20792. BABYLON.CombineAction = CombineAction;
  20793. var ExecuteCodeAction = (function (_super) {
  20794. __extends(ExecuteCodeAction, _super);
  20795. function ExecuteCodeAction(triggerOptions, func, condition) {
  20796. _super.call(this, triggerOptions, condition);
  20797. this.func = func;
  20798. }
  20799. ExecuteCodeAction.prototype.execute = function (evt) {
  20800. this.func(evt);
  20801. };
  20802. return ExecuteCodeAction;
  20803. })(BABYLON.Action);
  20804. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  20805. var SetParentAction = (function (_super) {
  20806. __extends(SetParentAction, _super);
  20807. function SetParentAction(triggerOptions, target, parent, condition) {
  20808. _super.call(this, triggerOptions, condition);
  20809. this._target = target;
  20810. this._parent = parent;
  20811. }
  20812. SetParentAction.prototype._prepare = function () {
  20813. };
  20814. SetParentAction.prototype.execute = function () {
  20815. if (this._target.parent === this._parent) {
  20816. return;
  20817. }
  20818. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  20819. invertParentWorldMatrix.invert();
  20820. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  20821. this._target.parent = this._parent;
  20822. };
  20823. return SetParentAction;
  20824. })(BABYLON.Action);
  20825. BABYLON.SetParentAction = SetParentAction;
  20826. })(BABYLON || (BABYLON = {}));
  20827. var __extends = this.__extends || function (d, b) {
  20828. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  20829. function __() { this.constructor = d; }
  20830. __.prototype = b.prototype;
  20831. d.prototype = new __();
  20832. };
  20833. var BABYLON;
  20834. (function (BABYLON) {
  20835. var Geometry = (function () {
  20836. function Geometry(id, scene, vertexData, updatable, mesh) {
  20837. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  20838. this._totalVertices = 0;
  20839. this._indices = [];
  20840. this.id = id;
  20841. this._engine = scene.getEngine();
  20842. this._meshes = [];
  20843. this._scene = scene;
  20844. if (vertexData) {
  20845. this.setAllVerticesData(vertexData, updatable);
  20846. } else {
  20847. this._totalVertices = 0;
  20848. this._indices = [];
  20849. }
  20850. if (mesh) {
  20851. this.applyToMesh(mesh);
  20852. }
  20853. }
  20854. Geometry.prototype.getScene = function () {
  20855. return this._scene;
  20856. };
  20857. Geometry.prototype.getEngine = function () {
  20858. return this._engine;
  20859. };
  20860. Geometry.prototype.isReady = function () {
  20861. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  20862. };
  20863. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  20864. vertexData.applyToGeometry(this, updatable);
  20865. };
  20866. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  20867. this._vertexBuffers = this._vertexBuffers || {};
  20868. if (this._vertexBuffers[kind]) {
  20869. this._vertexBuffers[kind].dispose();
  20870. }
  20871. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  20872. if (kind === BABYLON.VertexBuffer.PositionKind) {
  20873. stride = this._vertexBuffers[kind].getStrideSize();
  20874. this._totalVertices = data.length / stride;
  20875. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  20876. var meshes = this._meshes;
  20877. var numOfMeshes = meshes.length;
  20878. for (var index = 0; index < numOfMeshes; index++) {
  20879. var mesh = meshes[index];
  20880. mesh._resetPointsArrayCache();
  20881. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  20882. mesh._createGlobalSubMesh();
  20883. mesh.computeWorldMatrix(true);
  20884. }
  20885. }
  20886. };
  20887. Geometry.prototype.updateVerticesDataDirectly = function (kind, data) {
  20888. var vertexBuffer = this.getVertexBuffer(kind);
  20889. if (!vertexBuffer) {
  20890. return;
  20891. }
  20892. vertexBuffer.updateDirectly(data);
  20893. };
  20894. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  20895. var vertexBuffer = this.getVertexBuffer(kind);
  20896. if (!vertexBuffer) {
  20897. return;
  20898. }
  20899. vertexBuffer.update(data);
  20900. if (kind === BABYLON.VertexBuffer.PositionKind) {
  20901. var extend;
  20902. if (updateExtends) {
  20903. var stride = vertexBuffer.getStrideSize();
  20904. this._totalVertices = data.length / stride;
  20905. extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  20906. }
  20907. var meshes = this._meshes;
  20908. var numOfMeshes = meshes.length;
  20909. for (var index = 0; index < numOfMeshes; index++) {
  20910. var mesh = meshes[index];
  20911. mesh._resetPointsArrayCache();
  20912. if (updateExtends) {
  20913. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  20914. }
  20915. }
  20916. }
  20917. };
  20918. Geometry.prototype.getTotalVertices = function () {
  20919. if (!this.isReady()) {
  20920. return 0;
  20921. }
  20922. return this._totalVertices;
  20923. };
  20924. Geometry.prototype.getVerticesData = function (kind) {
  20925. var vertexBuffer = this.getVertexBuffer(kind);
  20926. if (!vertexBuffer) {
  20927. return null;
  20928. }
  20929. return vertexBuffer.getData();
  20930. };
  20931. Geometry.prototype.getVertexBuffer = function (kind) {
  20932. if (!this.isReady()) {
  20933. return null;
  20934. }
  20935. return this._vertexBuffers[kind];
  20936. };
  20937. Geometry.prototype.getVertexBuffers = function () {
  20938. if (!this.isReady()) {
  20939. return null;
  20940. }
  20941. return this._vertexBuffers;
  20942. };
  20943. Geometry.prototype.isVerticesDataPresent = function (kind) {
  20944. if (!this._vertexBuffers) {
  20945. if (this._delayInfo) {
  20946. return this._delayInfo.indexOf(kind) !== -1;
  20947. }
  20948. return false;
  20949. }
  20950. return this._vertexBuffers[kind] !== undefined;
  20951. };
  20952. Geometry.prototype.getVerticesDataKinds = function () {
  20953. var result = [];
  20954. if (!this._vertexBuffers && this._delayInfo) {
  20955. for (var kind in this._delayInfo) {
  20956. result.push(kind);
  20957. }
  20958. } else {
  20959. for (kind in this._vertexBuffers) {
  20960. result.push(kind);
  20961. }
  20962. }
  20963. return result;
  20964. };
  20965. Geometry.prototype.setIndices = function (indices) {
  20966. if (this._indexBuffer) {
  20967. this._engine._releaseBuffer(this._indexBuffer);
  20968. }
  20969. this._indices = indices;
  20970. if (this._meshes.length !== 0 && this._indices) {
  20971. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  20972. }
  20973. var meshes = this._meshes;
  20974. var numOfMeshes = meshes.length;
  20975. for (var index = 0; index < numOfMeshes; index++) {
  20976. meshes[index]._createGlobalSubMesh();
  20977. }
  20978. };
  20979. Geometry.prototype.getTotalIndices = function () {
  20980. if (!this.isReady()) {
  20981. return 0;
  20982. }
  20983. return this._indices.length;
  20984. };
  20985. Geometry.prototype.getIndices = function () {
  20986. if (!this.isReady()) {
  20987. return null;
  20988. }
  20989. return this._indices;
  20990. };
  20991. Geometry.prototype.getIndexBuffer = function () {
  20992. if (!this.isReady()) {
  20993. return null;
  20994. }
  20995. return this._indexBuffer;
  20996. };
  20997. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  20998. var meshes = this._meshes;
  20999. var index = meshes.indexOf(mesh);
  21000. if (index === -1) {
  21001. return;
  21002. }
  21003. for (var kind in this._vertexBuffers) {
  21004. this._vertexBuffers[kind].dispose();
  21005. }
  21006. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  21007. this._indexBuffer = null;
  21008. }
  21009. meshes.splice(index, 1);
  21010. mesh._geometry = null;
  21011. if (meshes.length == 0 && shouldDispose) {
  21012. this.dispose();
  21013. }
  21014. };
  21015. Geometry.prototype.applyToMesh = function (mesh) {
  21016. if (mesh._geometry === this) {
  21017. return;
  21018. }
  21019. var previousGeometry = mesh._geometry;
  21020. if (previousGeometry) {
  21021. previousGeometry.releaseForMesh(mesh);
  21022. }
  21023. var meshes = this._meshes;
  21024. mesh._geometry = this;
  21025. this._scene.pushGeometry(this);
  21026. meshes.push(mesh);
  21027. if (this.isReady()) {
  21028. this._applyToMesh(mesh);
  21029. } else {
  21030. mesh._boundingInfo = this._boundingInfo;
  21031. }
  21032. };
  21033. Geometry.prototype._applyToMesh = function (mesh) {
  21034. var numOfMeshes = this._meshes.length;
  21035. for (var kind in this._vertexBuffers) {
  21036. if (numOfMeshes === 1) {
  21037. this._vertexBuffers[kind].create();
  21038. }
  21039. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  21040. if (kind === BABYLON.VertexBuffer.PositionKind) {
  21041. mesh._resetPointsArrayCache();
  21042. var extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  21043. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  21044. mesh._createGlobalSubMesh();
  21045. }
  21046. }
  21047. if (numOfMeshes === 1 && this._indices) {
  21048. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  21049. }
  21050. if (this._indexBuffer) {
  21051. this._indexBuffer.references = numOfMeshes;
  21052. }
  21053. };
  21054. Geometry.prototype.load = function (scene, onLoaded) {
  21055. var _this = this;
  21056. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  21057. return;
  21058. }
  21059. if (this.isReady()) {
  21060. if (onLoaded) {
  21061. onLoaded();
  21062. }
  21063. return;
  21064. }
  21065. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  21066. scene._addPendingData(this);
  21067. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  21068. _this._delayLoadingFunction(JSON.parse(data), _this);
  21069. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  21070. _this._delayInfo = [];
  21071. scene._removePendingData(_this);
  21072. var meshes = _this._meshes;
  21073. var numOfMeshes = meshes.length;
  21074. for (var index = 0; index < numOfMeshes; index++) {
  21075. _this._applyToMesh(meshes[index]);
  21076. }
  21077. if (onLoaded) {
  21078. onLoaded();
  21079. }
  21080. }, function () {
  21081. }, scene.database);
  21082. };
  21083. Geometry.prototype.dispose = function () {
  21084. var meshes = this._meshes;
  21085. var numOfMeshes = meshes.length;
  21086. for (var index = 0; index < numOfMeshes; index++) {
  21087. this.releaseForMesh(meshes[index]);
  21088. }
  21089. this._meshes = [];
  21090. for (var kind in this._vertexBuffers) {
  21091. this._vertexBuffers[kind].dispose();
  21092. }
  21093. this._vertexBuffers = [];
  21094. this._totalVertices = 0;
  21095. if (this._indexBuffer) {
  21096. this._engine._releaseBuffer(this._indexBuffer);
  21097. }
  21098. this._indexBuffer = null;
  21099. this._indices = [];
  21100. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  21101. this.delayLoadingFile = null;
  21102. this._delayLoadingFunction = null;
  21103. this._delayInfo = [];
  21104. this._boundingInfo = null;
  21105. var geometries = this._scene.getGeometries();
  21106. index = geometries.indexOf(this);
  21107. if (index > -1) {
  21108. geometries.splice(index, 1);
  21109. }
  21110. };
  21111. Geometry.prototype.copy = function (id) {
  21112. var vertexData = new BABYLON.VertexData();
  21113. vertexData.indices = [];
  21114. var indices = this.getIndices();
  21115. for (var index = 0; index < indices.length; index++) {
  21116. vertexData.indices.push(indices[index]);
  21117. }
  21118. var updatable = false;
  21119. var stopChecking = false;
  21120. for (var kind in this._vertexBuffers) {
  21121. vertexData.set(this.getVerticesData(kind), kind);
  21122. if (!stopChecking) {
  21123. updatable = this.getVertexBuffer(kind).isUpdatable();
  21124. stopChecking = !updatable;
  21125. }
  21126. }
  21127. var geometry = new BABYLON.Geometry(id, this._scene, vertexData, updatable, null);
  21128. geometry.delayLoadState = this.delayLoadState;
  21129. geometry.delayLoadingFile = this.delayLoadingFile;
  21130. geometry._delayLoadingFunction = this._delayLoadingFunction;
  21131. for (kind in this._delayInfo) {
  21132. geometry._delayInfo = geometry._delayInfo || [];
  21133. geometry._delayInfo.push(kind);
  21134. }
  21135. var extend = BABYLON.Tools.ExtractMinAndMax(this.getVerticesData(BABYLON.VertexBuffer.PositionKind), 0, this.getTotalVertices());
  21136. geometry._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  21137. return geometry;
  21138. };
  21139. Geometry.ExtractFromMesh = function (mesh, id) {
  21140. var geometry = mesh._geometry;
  21141. if (!geometry) {
  21142. return null;
  21143. }
  21144. return geometry.copy(id);
  21145. };
  21146. Geometry.RandomId = function () {
  21147. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  21148. var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
  21149. return v.toString(16);
  21150. });
  21151. };
  21152. return Geometry;
  21153. })();
  21154. BABYLON.Geometry = Geometry;
  21155. (function (Geometry) {
  21156. (function (Primitives) {
  21157. var _Primitive = (function (_super) {
  21158. __extends(_Primitive, _super);
  21159. function _Primitive(id, scene, vertexData, canBeRegenerated, mesh) {
  21160. this._beingRegenerated = true;
  21161. this._canBeRegenerated = canBeRegenerated;
  21162. _super.call(this, id, scene, vertexData, false, mesh);
  21163. this._beingRegenerated = false;
  21164. }
  21165. _Primitive.prototype.canBeRegenerated = function () {
  21166. return this._canBeRegenerated;
  21167. };
  21168. _Primitive.prototype.regenerate = function () {
  21169. if (!this._canBeRegenerated) {
  21170. return;
  21171. }
  21172. this._beingRegenerated = true;
  21173. this.setAllVerticesData(this._regenerateVertexData(), false);
  21174. this._beingRegenerated = false;
  21175. };
  21176. _Primitive.prototype.asNewGeometry = function (id) {
  21177. return _super.prototype.copy.call(this, id);
  21178. };
  21179. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  21180. if (!this._beingRegenerated) {
  21181. return;
  21182. }
  21183. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  21184. };
  21185. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  21186. if (!this._beingRegenerated) {
  21187. return;
  21188. }
  21189. _super.prototype.setVerticesData.call(this, kind, data, false);
  21190. };
  21191. _Primitive.prototype._regenerateVertexData = function () {
  21192. throw new Error("Abstract method");
  21193. };
  21194. _Primitive.prototype.copy = function (id) {
  21195. throw new Error("Must be overriden in sub-classes.");
  21196. };
  21197. return _Primitive;
  21198. })(Geometry);
  21199. Primitives._Primitive = _Primitive;
  21200. var Box = (function (_super) {
  21201. __extends(Box, _super);
  21202. function Box(id, scene, size, canBeRegenerated, mesh) {
  21203. this.size = size;
  21204. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  21205. }
  21206. Box.prototype._regenerateVertexData = function () {
  21207. return BABYLON.VertexData.CreateBox(this.size);
  21208. };
  21209. Box.prototype.copy = function (id) {
  21210. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null);
  21211. };
  21212. return Box;
  21213. })(_Primitive);
  21214. Primitives.Box = Box;
  21215. var Sphere = (function (_super) {
  21216. __extends(Sphere, _super);
  21217. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh) {
  21218. this.segments = segments;
  21219. this.diameter = diameter;
  21220. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  21221. }
  21222. Sphere.prototype._regenerateVertexData = function () {
  21223. return BABYLON.VertexData.CreateSphere(this.segments, this.diameter);
  21224. };
  21225. Sphere.prototype.copy = function (id) {
  21226. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null);
  21227. };
  21228. return Sphere;
  21229. })(_Primitive);
  21230. Primitives.Sphere = Sphere;
  21231. var Cylinder = (function (_super) {
  21232. __extends(Cylinder, _super);
  21233. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh) {
  21234. if (typeof subdivisions === "undefined") { subdivisions = 1; }
  21235. this.height = height;
  21236. this.diameterTop = diameterTop;
  21237. this.diameterBottom = diameterBottom;
  21238. this.tessellation = tessellation;
  21239. this.subdivisions = subdivisions;
  21240. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  21241. }
  21242. Cylinder.prototype._regenerateVertexData = function () {
  21243. return BABYLON.VertexData.CreateCylinder(this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions);
  21244. };
  21245. Cylinder.prototype.copy = function (id) {
  21246. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null);
  21247. };
  21248. return Cylinder;
  21249. })(_Primitive);
  21250. Primitives.Cylinder = Cylinder;
  21251. var Torus = (function (_super) {
  21252. __extends(Torus, _super);
  21253. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh) {
  21254. this.diameter = diameter;
  21255. this.thickness = thickness;
  21256. this.tessellation = tessellation;
  21257. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  21258. }
  21259. Torus.prototype._regenerateVertexData = function () {
  21260. return BABYLON.VertexData.CreateTorus(this.diameter, this.thickness, this.tessellation);
  21261. };
  21262. Torus.prototype.copy = function (id) {
  21263. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null);
  21264. };
  21265. return Torus;
  21266. })(_Primitive);
  21267. Primitives.Torus = Torus;
  21268. var Ground = (function (_super) {
  21269. __extends(Ground, _super);
  21270. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  21271. this.width = width;
  21272. this.height = height;
  21273. this.subdivisions = subdivisions;
  21274. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  21275. }
  21276. Ground.prototype._regenerateVertexData = function () {
  21277. return BABYLON.VertexData.CreateGround(this.width, this.height, this.subdivisions);
  21278. };
  21279. Ground.prototype.copy = function (id) {
  21280. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  21281. };
  21282. return Ground;
  21283. })(_Primitive);
  21284. Primitives.Ground = Ground;
  21285. var TiledGround = (function (_super) {
  21286. __extends(TiledGround, _super);
  21287. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  21288. this.xmin = xmin;
  21289. this.zmin = zmin;
  21290. this.xmax = xmax;
  21291. this.zmax = zmax;
  21292. this.subdivisions = subdivisions;
  21293. this.precision = precision;
  21294. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  21295. }
  21296. TiledGround.prototype._regenerateVertexData = function () {
  21297. return BABYLON.VertexData.CreateTiledGround(this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision);
  21298. };
  21299. TiledGround.prototype.copy = function (id) {
  21300. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  21301. };
  21302. return TiledGround;
  21303. })(_Primitive);
  21304. Primitives.TiledGround = TiledGround;
  21305. var Plane = (function (_super) {
  21306. __extends(Plane, _super);
  21307. function Plane(id, scene, size, canBeRegenerated, mesh) {
  21308. this.size = size;
  21309. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  21310. }
  21311. Plane.prototype._regenerateVertexData = function () {
  21312. return BABYLON.VertexData.CreatePlane(this.size);
  21313. };
  21314. Plane.prototype.copy = function (id) {
  21315. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null);
  21316. };
  21317. return Plane;
  21318. })(_Primitive);
  21319. Primitives.Plane = Plane;
  21320. var TorusKnot = (function (_super) {
  21321. __extends(TorusKnot, _super);
  21322. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh) {
  21323. this.radius = radius;
  21324. this.tube = tube;
  21325. this.radialSegments = radialSegments;
  21326. this.tubularSegments = tubularSegments;
  21327. this.p = p;
  21328. this.q = q;
  21329. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  21330. }
  21331. TorusKnot.prototype._regenerateVertexData = function () {
  21332. return BABYLON.VertexData.CreateTorusKnot(this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q);
  21333. };
  21334. TorusKnot.prototype.copy = function (id) {
  21335. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null);
  21336. };
  21337. return TorusKnot;
  21338. })(_Primitive);
  21339. Primitives.TorusKnot = TorusKnot;
  21340. })(Geometry.Primitives || (Geometry.Primitives = {}));
  21341. var Primitives = Geometry.Primitives;
  21342. })(BABYLON.Geometry || (BABYLON.Geometry = {}));
  21343. var Geometry = BABYLON.Geometry;
  21344. })(BABYLON || (BABYLON = {}));
  21345. var __extends = this.__extends || function (d, b) {
  21346. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  21347. function __() { this.constructor = d; }
  21348. __.prototype = b.prototype;
  21349. d.prototype = new __();
  21350. };
  21351. var BABYLON;
  21352. (function (BABYLON) {
  21353. var Gamepads = (function () {
  21354. function Gamepads(ongamedpadconnected) {
  21355. var _this = this;
  21356. this.babylonGamepads = [];
  21357. this.oneGamepadConnected = false;
  21358. this.isMonitoring = false;
  21359. this.gamepadEventSupported = 'GamepadEvent' in window;
  21360. this.gamepadSupportAvailable = (navigator.getGamepads || !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  21361. 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=";
  21362. this._callbackGamepadConnected = ongamedpadconnected;
  21363. if (this.gamepadSupportAvailable) {
  21364. if (this.gamepadEventSupported) {
  21365. window.addEventListener('gamepadconnected', function (evt) {
  21366. _this._onGamepadConnected(evt);
  21367. }, false);
  21368. window.addEventListener('gamepaddisconnected', function (evt) {
  21369. _this._onGamepadDisconnected(evt);
  21370. }, false);
  21371. } else {
  21372. this._startMonitoringGamepads();
  21373. }
  21374. if (!this.oneGamepadConnected) {
  21375. this._insertGamepadDOMInstructions();
  21376. }
  21377. } else {
  21378. this._insertGamepadDOMNotSupported();
  21379. }
  21380. }
  21381. Gamepads.prototype._insertGamepadDOMInstructions = function () {
  21382. Gamepads.gamepadDOMInfo = document.createElement("div");
  21383. var buttonAImage = document.createElement("img");
  21384. buttonAImage.src = this.buttonADataURL;
  21385. var spanMessage = document.createElement("span");
  21386. spanMessage.innerHTML = "<strong>to activate gamepad</strong>";
  21387. Gamepads.gamepadDOMInfo.appendChild(buttonAImage);
  21388. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  21389. Gamepads.gamepadDOMInfo.style.position = "absolute";
  21390. Gamepads.gamepadDOMInfo.style.width = "100%";
  21391. Gamepads.gamepadDOMInfo.style.height = "48px";
  21392. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  21393. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  21394. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  21395. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  21396. buttonAImage.style.position = "relative";
  21397. buttonAImage.style.bottom = "8px";
  21398. spanMessage.style.position = "relative";
  21399. spanMessage.style.fontSize = "32px";
  21400. spanMessage.style.bottom = "32px";
  21401. spanMessage.style.color = "green";
  21402. document.body.appendChild(Gamepads.gamepadDOMInfo);
  21403. };
  21404. Gamepads.prototype._insertGamepadDOMNotSupported = function () {
  21405. Gamepads.gamepadDOMInfo = document.createElement("div");
  21406. var spanMessage = document.createElement("span");
  21407. spanMessage.innerHTML = "<strong>gamepad not supported</strong>";
  21408. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  21409. Gamepads.gamepadDOMInfo.style.position = "absolute";
  21410. Gamepads.gamepadDOMInfo.style.width = "100%";
  21411. Gamepads.gamepadDOMInfo.style.height = "40px";
  21412. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  21413. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  21414. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  21415. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  21416. spanMessage.style.position = "relative";
  21417. spanMessage.style.fontSize = "32px";
  21418. spanMessage.style.color = "red";
  21419. document.body.appendChild(Gamepads.gamepadDOMInfo);
  21420. };
  21421. Gamepads.prototype.dispose = function () {
  21422. document.body.removeChild(Gamepads.gamepadDOMInfo);
  21423. };
  21424. Gamepads.prototype._onGamepadConnected = function (evt) {
  21425. var newGamepad = this._addNewGamepad(evt.gamepad);
  21426. if (this._callbackGamepadConnected)
  21427. this._callbackGamepadConnected(newGamepad);
  21428. this._startMonitoringGamepads();
  21429. };
  21430. Gamepads.prototype._addNewGamepad = function (gamepad) {
  21431. if (!this.oneGamepadConnected) {
  21432. this.oneGamepadConnected = true;
  21433. if (Gamepads.gamepadDOMInfo) {
  21434. document.body.removeChild(Gamepads.gamepadDOMInfo);
  21435. Gamepads.gamepadDOMInfo = null;
  21436. }
  21437. }
  21438. var newGamepad;
  21439. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  21440. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  21441. } else {
  21442. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  21443. }
  21444. this.babylonGamepads.push(newGamepad);
  21445. return newGamepad;
  21446. };
  21447. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  21448. for (var i in this.babylonGamepads) {
  21449. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  21450. this.babylonGamepads.splice(i, 1);
  21451. break;
  21452. }
  21453. }
  21454. if (this.babylonGamepads.length == 0) {
  21455. this._stopMonitoringGamepads();
  21456. }
  21457. };
  21458. Gamepads.prototype._startMonitoringGamepads = function () {
  21459. if (!this.isMonitoring) {
  21460. this.isMonitoring = true;
  21461. this._checkGamepadsStatus();
  21462. }
  21463. };
  21464. Gamepads.prototype._stopMonitoringGamepads = function () {
  21465. this.isMonitoring = false;
  21466. };
  21467. Gamepads.prototype._checkGamepadsStatus = function () {
  21468. var _this = this;
  21469. this._updateGamepadObjects();
  21470. for (var i in this.babylonGamepads) {
  21471. this.babylonGamepads[i].update();
  21472. }
  21473. if (this.isMonitoring) {
  21474. if (window.requestAnimationFrame) {
  21475. window.requestAnimationFrame(function () {
  21476. _this._checkGamepadsStatus();
  21477. });
  21478. } else if (window.mozRequestAnimationFrame) {
  21479. window.mozRequestAnimationFrame(function () {
  21480. _this._checkGamepadsStatus();
  21481. });
  21482. } else if (window.webkitRequestAnimationFrame) {
  21483. window.webkitRequestAnimationFrame(function () {
  21484. _this._checkGamepadsStatus();
  21485. });
  21486. }
  21487. }
  21488. };
  21489. Gamepads.prototype._updateGamepadObjects = function () {
  21490. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  21491. for (var i = 0; i < gamepads.length; i++) {
  21492. if (gamepads[i]) {
  21493. if (!(gamepads[i].index in this.babylonGamepads)) {
  21494. var newGamepad = this._addNewGamepad(gamepads[i]);
  21495. if (this._callbackGamepadConnected) {
  21496. this._callbackGamepadConnected(newGamepad);
  21497. }
  21498. } else {
  21499. this.babylonGamepads[i].browserGamepad = gamepads[i];
  21500. }
  21501. }
  21502. }
  21503. };
  21504. return Gamepads;
  21505. })();
  21506. BABYLON.Gamepads = Gamepads;
  21507. var StickValues = (function () {
  21508. function StickValues(x, y) {
  21509. this.x = x;
  21510. this.y = y;
  21511. }
  21512. return StickValues;
  21513. })();
  21514. BABYLON.StickValues = StickValues;
  21515. var Gamepad = (function () {
  21516. function Gamepad(id, index, browserGamepad) {
  21517. this.id = id;
  21518. this.index = index;
  21519. this.browserGamepad = browserGamepad;
  21520. if (this.browserGamepad.axes.length >= 2) {
  21521. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  21522. }
  21523. if (this.browserGamepad.axes.length >= 4) {
  21524. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  21525. }
  21526. }
  21527. Gamepad.prototype.onleftstickchanged = function (callback) {
  21528. this._onleftstickchanged = callback;
  21529. };
  21530. Gamepad.prototype.onrightstickchanged = function (callback) {
  21531. this._onrightstickchanged = callback;
  21532. };
  21533. Object.defineProperty(Gamepad.prototype, "leftStick", {
  21534. get: function () {
  21535. return this._leftStick;
  21536. },
  21537. set: function (newValues) {
  21538. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  21539. this._onleftstickchanged(newValues);
  21540. }
  21541. this._leftStick = newValues;
  21542. },
  21543. enumerable: true,
  21544. configurable: true
  21545. });
  21546. Object.defineProperty(Gamepad.prototype, "rightStick", {
  21547. get: function () {
  21548. return this._rightStick;
  21549. },
  21550. set: function (newValues) {
  21551. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  21552. this._onrightstickchanged(newValues);
  21553. }
  21554. this._rightStick = newValues;
  21555. },
  21556. enumerable: true,
  21557. configurable: true
  21558. });
  21559. Gamepad.prototype.update = function () {
  21560. if (this._leftStick) {
  21561. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  21562. }
  21563. if (this._rightStick) {
  21564. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  21565. }
  21566. };
  21567. return Gamepad;
  21568. })();
  21569. BABYLON.Gamepad = Gamepad;
  21570. var GenericPad = (function (_super) {
  21571. __extends(GenericPad, _super);
  21572. function GenericPad(id, index, gamepad) {
  21573. _super.call(this, id, index, gamepad);
  21574. this.id = id;
  21575. this.index = index;
  21576. this.gamepad = gamepad;
  21577. this._buttons = new Array(gamepad.buttons.length);
  21578. }
  21579. GenericPad.prototype.onbuttondown = function (callback) {
  21580. this._onbuttondown = callback;
  21581. };
  21582. GenericPad.prototype.onbuttonup = function (callback) {
  21583. this._onbuttonup = callback;
  21584. };
  21585. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  21586. if (newValue !== currentValue) {
  21587. if (this._onbuttondown && newValue === 1) {
  21588. this._onbuttondown(buttonIndex);
  21589. }
  21590. if (this._onbuttonup && newValue === 0) {
  21591. this._onbuttonup(buttonIndex);
  21592. }
  21593. }
  21594. return newValue;
  21595. };
  21596. GenericPad.prototype.update = function () {
  21597. _super.prototype.update.call(this);
  21598. for (var index = 0; index < this._buttons.length; index++) {
  21599. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  21600. }
  21601. };
  21602. return GenericPad;
  21603. })(Gamepad);
  21604. BABYLON.GenericPad = GenericPad;
  21605. (function (Xbox360Button) {
  21606. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  21607. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  21608. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  21609. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  21610. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  21611. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  21612. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  21613. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  21614. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  21615. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  21616. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  21617. var Xbox360Button = BABYLON.Xbox360Button;
  21618. (function (Xbox360Dpad) {
  21619. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  21620. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  21621. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  21622. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  21623. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  21624. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  21625. var Xbox360Pad = (function (_super) {
  21626. __extends(Xbox360Pad, _super);
  21627. function Xbox360Pad() {
  21628. _super.apply(this, arguments);
  21629. this._leftTrigger = 0;
  21630. this._rightTrigger = 0;
  21631. this._buttonA = 0;
  21632. this._buttonB = 0;
  21633. this._buttonX = 0;
  21634. this._buttonY = 0;
  21635. this._buttonBack = 0;
  21636. this._buttonStart = 0;
  21637. this._buttonLB = 0;
  21638. this._buttonRB = 0;
  21639. this._buttonLeftStick = 0;
  21640. this._buttonRightStick = 0;
  21641. this._dPadUp = 0;
  21642. this._dPadDown = 0;
  21643. this._dPadLeft = 0;
  21644. this._dPadRight = 0;
  21645. }
  21646. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  21647. this._onlefttriggerchanged = callback;
  21648. };
  21649. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  21650. this._onrighttriggerchanged = callback;
  21651. };
  21652. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  21653. get: function () {
  21654. return this._leftTrigger;
  21655. },
  21656. set: function (newValue) {
  21657. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  21658. this._onlefttriggerchanged(newValue);
  21659. }
  21660. this._leftTrigger = newValue;
  21661. },
  21662. enumerable: true,
  21663. configurable: true
  21664. });
  21665. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  21666. get: function () {
  21667. return this._rightTrigger;
  21668. },
  21669. set: function (newValue) {
  21670. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  21671. this._onrighttriggerchanged(newValue);
  21672. }
  21673. this._rightTrigger = newValue;
  21674. },
  21675. enumerable: true,
  21676. configurable: true
  21677. });
  21678. Xbox360Pad.prototype.onbuttondown = function (callback) {
  21679. this._onbuttondown = callback;
  21680. };
  21681. Xbox360Pad.prototype.onbuttonup = function (callback) {
  21682. this._onbuttonup = callback;
  21683. };
  21684. Xbox360Pad.prototype.ondpaddown = function (callback) {
  21685. this._ondpaddown = callback;
  21686. };
  21687. Xbox360Pad.prototype.ondpadup = function (callback) {
  21688. this._ondpadup = callback;
  21689. };
  21690. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  21691. if (newValue !== currentValue) {
  21692. if (this._onbuttondown && newValue === 1) {
  21693. this._onbuttondown(buttonType);
  21694. }
  21695. if (this._onbuttonup && newValue === 0) {
  21696. this._onbuttonup(buttonType);
  21697. }
  21698. }
  21699. return newValue;
  21700. };
  21701. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  21702. if (newValue !== currentValue) {
  21703. if (this._ondpaddown && newValue === 1) {
  21704. this._ondpaddown(buttonType);
  21705. }
  21706. if (this._ondpadup && newValue === 0) {
  21707. this._ondpadup(buttonType);
  21708. }
  21709. }
  21710. return newValue;
  21711. };
  21712. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  21713. get: function () {
  21714. return this._buttonA;
  21715. },
  21716. set: function (value) {
  21717. this._buttonA = this._setButtonValue(value, this._buttonA, 0 /* A */);
  21718. },
  21719. enumerable: true,
  21720. configurable: true
  21721. });
  21722. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  21723. get: function () {
  21724. return this._buttonB;
  21725. },
  21726. set: function (value) {
  21727. this._buttonB = this._setButtonValue(value, this._buttonB, 1 /* B */);
  21728. },
  21729. enumerable: true,
  21730. configurable: true
  21731. });
  21732. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  21733. get: function () {
  21734. return this._buttonX;
  21735. },
  21736. set: function (value) {
  21737. this._buttonX = this._setButtonValue(value, this._buttonX, 2 /* X */);
  21738. },
  21739. enumerable: true,
  21740. configurable: true
  21741. });
  21742. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  21743. get: function () {
  21744. return this._buttonY;
  21745. },
  21746. set: function (value) {
  21747. this._buttonY = this._setButtonValue(value, this._buttonY, 3 /* Y */);
  21748. },
  21749. enumerable: true,
  21750. configurable: true
  21751. });
  21752. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  21753. get: function () {
  21754. return this._buttonStart;
  21755. },
  21756. set: function (value) {
  21757. this._buttonStart = this._setButtonValue(value, this._buttonStart, 4 /* Start */);
  21758. },
  21759. enumerable: true,
  21760. configurable: true
  21761. });
  21762. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  21763. get: function () {
  21764. return this._buttonBack;
  21765. },
  21766. set: function (value) {
  21767. this._buttonBack = this._setButtonValue(value, this._buttonBack, 5 /* Back */);
  21768. },
  21769. enumerable: true,
  21770. configurable: true
  21771. });
  21772. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  21773. get: function () {
  21774. return this._buttonLB;
  21775. },
  21776. set: function (value) {
  21777. this._buttonLB = this._setButtonValue(value, this._buttonLB, 6 /* LB */);
  21778. },
  21779. enumerable: true,
  21780. configurable: true
  21781. });
  21782. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  21783. get: function () {
  21784. return this._buttonRB;
  21785. },
  21786. set: function (value) {
  21787. this._buttonRB = this._setButtonValue(value, this._buttonRB, 7 /* RB */);
  21788. },
  21789. enumerable: true,
  21790. configurable: true
  21791. });
  21792. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  21793. get: function () {
  21794. return this._buttonLeftStick;
  21795. },
  21796. set: function (value) {
  21797. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, 8 /* LeftStick */);
  21798. },
  21799. enumerable: true,
  21800. configurable: true
  21801. });
  21802. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  21803. get: function () {
  21804. return this._buttonRightStick;
  21805. },
  21806. set: function (value) {
  21807. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, 9 /* RightStick */);
  21808. },
  21809. enumerable: true,
  21810. configurable: true
  21811. });
  21812. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  21813. get: function () {
  21814. return this._dPadUp;
  21815. },
  21816. set: function (value) {
  21817. this._dPadUp = this._setDPadValue(value, this._dPadUp, 0 /* Up */);
  21818. },
  21819. enumerable: true,
  21820. configurable: true
  21821. });
  21822. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  21823. get: function () {
  21824. return this._dPadDown;
  21825. },
  21826. set: function (value) {
  21827. this._dPadDown = this._setDPadValue(value, this._dPadDown, 1 /* Down */);
  21828. },
  21829. enumerable: true,
  21830. configurable: true
  21831. });
  21832. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  21833. get: function () {
  21834. return this._dPadLeft;
  21835. },
  21836. set: function (value) {
  21837. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, 2 /* Left */);
  21838. },
  21839. enumerable: true,
  21840. configurable: true
  21841. });
  21842. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  21843. get: function () {
  21844. return this._dPadRight;
  21845. },
  21846. set: function (value) {
  21847. this._dPadRight = this._setDPadValue(value, this._dPadRight, 3 /* Right */);
  21848. },
  21849. enumerable: true,
  21850. configurable: true
  21851. });
  21852. Xbox360Pad.prototype.update = function () {
  21853. _super.prototype.update.call(this);
  21854. this.buttonA = this.browserGamepad.buttons[0].value;
  21855. this.buttonB = this.browserGamepad.buttons[1].value;
  21856. this.buttonX = this.browserGamepad.buttons[2].value;
  21857. this.buttonY = this.browserGamepad.buttons[3].value;
  21858. this.buttonLB = this.browserGamepad.buttons[4].value;
  21859. this.buttonRB = this.browserGamepad.buttons[5].value;
  21860. this.leftTrigger = this.browserGamepad.buttons[6].value;
  21861. this.rightTrigger = this.browserGamepad.buttons[7].value;
  21862. this.buttonBack = this.browserGamepad.buttons[8].value;
  21863. this.buttonStart = this.browserGamepad.buttons[9].value;
  21864. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  21865. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  21866. this.dPadUp = this.browserGamepad.buttons[12].value;
  21867. this.dPadDown = this.browserGamepad.buttons[13].value;
  21868. this.dPadLeft = this.browserGamepad.buttons[14].value;
  21869. this.dPadRight = this.browserGamepad.buttons[15].value;
  21870. };
  21871. return Xbox360Pad;
  21872. })(Gamepad);
  21873. BABYLON.Xbox360Pad = Xbox360Pad;
  21874. })(BABYLON || (BABYLON = {}));
  21875. var __extends = this.__extends || function (d, b) {
  21876. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  21877. function __() { this.constructor = d; }
  21878. __.prototype = b.prototype;
  21879. d.prototype = new __();
  21880. };
  21881. var BABYLON;
  21882. (function (BABYLON) {
  21883. var GamepadCamera = (function (_super) {
  21884. __extends(GamepadCamera, _super);
  21885. function GamepadCamera(name, position, scene) {
  21886. var _this = this;
  21887. _super.call(this, name, position, scene);
  21888. this.angularSensibility = 200;
  21889. this.moveSensibility = 75;
  21890. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  21891. _this._onNewGameConnected(gamepad);
  21892. });
  21893. }
  21894. GamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  21895. if (gamepad.index === 0) {
  21896. this._gamepad = gamepad;
  21897. }
  21898. };
  21899. GamepadCamera.prototype._checkInputs = function () {
  21900. if (!this._gamepad) {
  21901. return;
  21902. }
  21903. var LSValues = this._gamepad.leftStick;
  21904. var normalizedLX = LSValues.x / this.moveSensibility;
  21905. var normalizedLY = LSValues.y / this.moveSensibility;
  21906. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  21907. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  21908. var RSValues = this._gamepad.rightStick;
  21909. var normalizedRX = RSValues.x / this.angularSensibility;
  21910. var normalizedRY = RSValues.y / this.angularSensibility;
  21911. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  21912. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  21913. ;
  21914. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  21915. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x, 0, -LSValues.y), cameraTransform);
  21916. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  21917. this.cameraRotation = this.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  21918. };
  21919. GamepadCamera.prototype.dispose = function () {
  21920. this._gamepads.dispose();
  21921. _super.prototype.dispose.call(this);
  21922. };
  21923. return GamepadCamera;
  21924. })(BABYLON.FreeCamera);
  21925. BABYLON.GamepadCamera = GamepadCamera;
  21926. })(BABYLON || (BABYLON = {}));
  21927. var __extends = this.__extends || function (d, b) {
  21928. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  21929. function __() { this.constructor = d; }
  21930. __.prototype = b.prototype;
  21931. d.prototype = new __();
  21932. };
  21933. var BABYLON;
  21934. (function (BABYLON) {
  21935. var LinesMesh = (function (_super) {
  21936. __extends(LinesMesh, _super);
  21937. function LinesMesh(name, scene, updatable) {
  21938. if (typeof updatable === "undefined") { updatable = false; }
  21939. _super.call(this, name, scene);
  21940. this.color = new BABYLON.Color3(1, 1, 1);
  21941. this.alpha = 1;
  21942. this._indices = new Array();
  21943. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  21944. attributes: ["position"],
  21945. uniforms: ["worldViewProjection", "color"],
  21946. needAlphaBlending: true
  21947. });
  21948. }
  21949. Object.defineProperty(LinesMesh.prototype, "material", {
  21950. get: function () {
  21951. return this._colorShader;
  21952. },
  21953. enumerable: true,
  21954. configurable: true
  21955. });
  21956. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  21957. get: function () {
  21958. return false;
  21959. },
  21960. enumerable: true,
  21961. configurable: true
  21962. });
  21963. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  21964. get: function () {
  21965. return false;
  21966. },
  21967. enumerable: true,
  21968. configurable: true
  21969. });
  21970. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  21971. var engine = this.getScene().getEngine();
  21972. var indexToBind = this._geometry.getIndexBuffer();
  21973. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  21974. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  21975. };
  21976. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  21977. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  21978. return;
  21979. }
  21980. var engine = this.getScene().getEngine();
  21981. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  21982. };
  21983. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  21984. return null;
  21985. };
  21986. LinesMesh.prototype.dispose = function (doNotRecurse) {
  21987. this._colorShader.dispose();
  21988. _super.prototype.dispose.call(this, doNotRecurse);
  21989. };
  21990. return LinesMesh;
  21991. })(BABYLON.Mesh);
  21992. BABYLON.LinesMesh = LinesMesh;
  21993. })(BABYLON || (BABYLON = {}));
  21994. var BABYLON;
  21995. (function (BABYLON) {
  21996. var OutlineRenderer = (function () {
  21997. function OutlineRenderer(scene) {
  21998. this._scene = scene;
  21999. }
  22000. OutlineRenderer.prototype.render = function (subMesh, batch) {
  22001. var scene = this._scene;
  22002. var engine = this._scene.getEngine();
  22003. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances !== null);
  22004. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  22005. return;
  22006. }
  22007. var mesh = subMesh.getRenderingMesh();
  22008. var material = subMesh.getMaterial();
  22009. engine.enableEffect(this._effect);
  22010. this._effect.setFloat("offset", mesh.outlineWidth);
  22011. this._effect.setColor3("color", mesh.outlineColor);
  22012. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  22013. var useBones = mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  22014. if (useBones) {
  22015. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  22016. }
  22017. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  22018. if (material && material.needAlphaTesting()) {
  22019. var alphaTexture = material.getAlphaTestTexture();
  22020. this._effect.setTexture("diffuseSampler", alphaTexture);
  22021. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  22022. }
  22023. if (hardwareInstancedRendering) {
  22024. mesh._renderWithInstances(subMesh, BABYLON.Material.TriangleFillMode, batch, this._effect, engine);
  22025. } else {
  22026. if (batch.renderSelf[subMesh._id]) {
  22027. this._effect.setMatrix("world", mesh.getWorldMatrix());
  22028. mesh._draw(subMesh, BABYLON.Material.TriangleFillMode);
  22029. }
  22030. if (batch.visibleInstances[subMesh._id]) {
  22031. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  22032. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  22033. this._effect.setMatrix("world", instance.getWorldMatrix());
  22034. mesh._draw(subMesh, BABYLON.Material.TriangleFillMode);
  22035. }
  22036. }
  22037. }
  22038. };
  22039. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  22040. var defines = [];
  22041. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  22042. var mesh = subMesh.getMesh();
  22043. var material = subMesh.getMaterial();
  22044. if (material && material.needAlphaTesting()) {
  22045. defines.push("#define ALPHATEST");
  22046. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  22047. attribs.push(BABYLON.VertexBuffer.UVKind);
  22048. defines.push("#define UV1");
  22049. }
  22050. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  22051. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  22052. defines.push("#define UV2");
  22053. }
  22054. }
  22055. if (mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  22056. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  22057. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  22058. defines.push("#define BONES");
  22059. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  22060. }
  22061. if (useInstances) {
  22062. defines.push("#define INSTANCES");
  22063. attribs.push("world0");
  22064. attribs.push("world1");
  22065. attribs.push("world2");
  22066. attribs.push("world3");
  22067. }
  22068. var join = defines.join("\n");
  22069. if (this._cachedDefines != join) {
  22070. this._cachedDefines = join;
  22071. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  22072. }
  22073. return this._effect.isReady();
  22074. };
  22075. return OutlineRenderer;
  22076. })();
  22077. BABYLON.OutlineRenderer = OutlineRenderer;
  22078. })(BABYLON || (BABYLON = {}));
  22079. var BABYLON;
  22080. (function (BABYLON) {
  22081. var MeshAssetTask = (function () {
  22082. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  22083. this.name = name;
  22084. this.meshesNames = meshesNames;
  22085. this.rootUrl = rootUrl;
  22086. this.sceneFilename = sceneFilename;
  22087. this.isCompleted = false;
  22088. }
  22089. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  22090. var _this = this;
  22091. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  22092. _this.loadedMeshes = meshes;
  22093. _this.loadedParticleSystems = particleSystems;
  22094. _this.loadedSkeletons = skeletons;
  22095. _this.isCompleted = true;
  22096. if (_this.onSuccess) {
  22097. _this.onSuccess(_this);
  22098. }
  22099. onSuccess();
  22100. }, null, function () {
  22101. if (_this.onError) {
  22102. _this.onError(_this);
  22103. }
  22104. onError();
  22105. });
  22106. };
  22107. return MeshAssetTask;
  22108. })();
  22109. BABYLON.MeshAssetTask = MeshAssetTask;
  22110. var TextFileAssetTask = (function () {
  22111. function TextFileAssetTask(name, url) {
  22112. this.name = name;
  22113. this.url = url;
  22114. this.isCompleted = false;
  22115. }
  22116. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  22117. var _this = this;
  22118. BABYLON.Tools.LoadFile(this.url, function (data) {
  22119. _this.text = data;
  22120. _this.isCompleted = true;
  22121. if (_this.onSuccess) {
  22122. _this.onSuccess(_this);
  22123. }
  22124. onSuccess();
  22125. }, null, scene.database, false, function () {
  22126. if (_this.onError) {
  22127. _this.onError(_this);
  22128. }
  22129. onError();
  22130. });
  22131. };
  22132. return TextFileAssetTask;
  22133. })();
  22134. BABYLON.TextFileAssetTask = TextFileAssetTask;
  22135. var BinaryFileAssetTask = (function () {
  22136. function BinaryFileAssetTask(name, url) {
  22137. this.name = name;
  22138. this.url = url;
  22139. this.isCompleted = false;
  22140. }
  22141. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  22142. var _this = this;
  22143. BABYLON.Tools.LoadFile(this.url, function (data) {
  22144. _this.data = data;
  22145. _this.isCompleted = true;
  22146. if (_this.onSuccess) {
  22147. _this.onSuccess(_this);
  22148. }
  22149. onSuccess();
  22150. }, null, scene.database, true, function () {
  22151. if (_this.onError) {
  22152. _this.onError(_this);
  22153. }
  22154. onError();
  22155. });
  22156. };
  22157. return BinaryFileAssetTask;
  22158. })();
  22159. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  22160. var ImageAssetTask = (function () {
  22161. function ImageAssetTask(name, url) {
  22162. this.name = name;
  22163. this.url = url;
  22164. this.isCompleted = false;
  22165. }
  22166. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  22167. var _this = this;
  22168. var img = new Image();
  22169. img.onload = function () {
  22170. _this.image = img;
  22171. _this.isCompleted = true;
  22172. if (_this.onSuccess) {
  22173. _this.onSuccess(_this);
  22174. }
  22175. onSuccess();
  22176. };
  22177. img.onerror = function () {
  22178. if (_this.onError) {
  22179. _this.onError(_this);
  22180. }
  22181. onError();
  22182. };
  22183. img.src = this.url;
  22184. };
  22185. return ImageAssetTask;
  22186. })();
  22187. BABYLON.ImageAssetTask = ImageAssetTask;
  22188. var TextureAssetTask = (function () {
  22189. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  22190. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  22191. this.name = name;
  22192. this.url = url;
  22193. this.noMipmap = noMipmap;
  22194. this.invertY = invertY;
  22195. this.samplingMode = samplingMode;
  22196. this.isCompleted = false;
  22197. }
  22198. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  22199. var _this = this;
  22200. var onload = function () {
  22201. _this.isCompleted = true;
  22202. if (_this.onSuccess) {
  22203. _this.onSuccess(_this);
  22204. }
  22205. onSuccess();
  22206. };
  22207. var onerror = function () {
  22208. if (_this.onError) {
  22209. _this.onError(_this);
  22210. }
  22211. onError();
  22212. };
  22213. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onError);
  22214. };
  22215. return TextureAssetTask;
  22216. })();
  22217. BABYLON.TextureAssetTask = TextureAssetTask;
  22218. var AssetsManager = (function () {
  22219. function AssetsManager(scene) {
  22220. this._tasks = new Array();
  22221. this._waitingTasksCount = 0;
  22222. this.useDefaultLoadingScreen = true;
  22223. this._scene = scene;
  22224. }
  22225. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  22226. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  22227. this._tasks.push(task);
  22228. return task;
  22229. };
  22230. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  22231. var task = new TextFileAssetTask(taskName, url);
  22232. this._tasks.push(task);
  22233. return task;
  22234. };
  22235. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  22236. var task = new BinaryFileAssetTask(taskName, url);
  22237. this._tasks.push(task);
  22238. return task;
  22239. };
  22240. AssetsManager.prototype.addImageTask = function (taskName, url) {
  22241. var task = new ImageAssetTask(taskName, url);
  22242. this._tasks.push(task);
  22243. return task;
  22244. };
  22245. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  22246. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  22247. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  22248. this._tasks.push(task);
  22249. return task;
  22250. };
  22251. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  22252. this._waitingTasksCount--;
  22253. if (this._waitingTasksCount === 0) {
  22254. if (this.onFinish) {
  22255. this.onFinish(this._tasks);
  22256. }
  22257. this._scene.getEngine().hideLoadingUI();
  22258. }
  22259. };
  22260. AssetsManager.prototype._runTask = function (task) {
  22261. var _this = this;
  22262. task.run(this._scene, function () {
  22263. if (_this.onTaskSuccess) {
  22264. _this.onTaskSuccess(task);
  22265. }
  22266. _this._decreaseWaitingTasksCount();
  22267. }, function () {
  22268. if (_this.onTaskError) {
  22269. _this.onTaskError(task);
  22270. }
  22271. _this._decreaseWaitingTasksCount();
  22272. });
  22273. };
  22274. AssetsManager.prototype.reset = function () {
  22275. this._tasks = new Array();
  22276. return this;
  22277. };
  22278. AssetsManager.prototype.load = function () {
  22279. this._waitingTasksCount = this._tasks.length;
  22280. if (this._waitingTasksCount === 0) {
  22281. if (this.onFinish) {
  22282. this.onFinish(this._tasks);
  22283. }
  22284. return this;
  22285. }
  22286. if (this.useDefaultLoadingScreen) {
  22287. this._scene.getEngine().displayLoadingUI();
  22288. }
  22289. for (var index = 0; index < this._tasks.length; index++) {
  22290. var task = this._tasks[index];
  22291. this._runTask(task);
  22292. }
  22293. return this;
  22294. };
  22295. return AssetsManager;
  22296. })();
  22297. BABYLON.AssetsManager = AssetsManager;
  22298. })(BABYLON || (BABYLON = {}));
  22299. var __extends = this.__extends || function (d, b) {
  22300. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  22301. function __() { this.constructor = d; }
  22302. __.prototype = b.prototype;
  22303. d.prototype = new __();
  22304. };
  22305. var BABYLON;
  22306. (function (BABYLON) {
  22307. var VRDeviceOrientationCamera = (function (_super) {
  22308. __extends(VRDeviceOrientationCamera, _super);
  22309. function VRDeviceOrientationCamera(name, position, scene) {
  22310. _super.call(this, name, position, scene);
  22311. this._alpha = 0;
  22312. this._beta = 0;
  22313. this._gamma = 0;
  22314. }
  22315. VRDeviceOrientationCamera.prototype._onOrientationEvent = function (evt) {
  22316. this._alpha = +evt.alpha | 0;
  22317. this._beta = +evt.beta | 0;
  22318. this._gamma = +evt.gamma | 0;
  22319. if (this._gamma < 0) {
  22320. this._gamma = 90 + this._gamma;
  22321. } else {
  22322. this._gamma = 270 - this._gamma;
  22323. }
  22324. this.rotation.x = this._gamma / 180.0 * Math.PI;
  22325. this.rotation.y = -this._alpha / 180.0 * Math.PI;
  22326. this.rotation.z = this._beta / 180.0 * Math.PI;
  22327. };
  22328. return VRDeviceOrientationCamera;
  22329. })(BABYLON.OculusCamera);
  22330. BABYLON.VRDeviceOrientationCamera = VRDeviceOrientationCamera;
  22331. })(BABYLON || (BABYLON = {}));
  22332. var __extends = this.__extends || function (d, b) {
  22333. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  22334. function __() { this.constructor = d; }
  22335. __.prototype = b.prototype;
  22336. d.prototype = new __();
  22337. };
  22338. var BABYLON;
  22339. (function (BABYLON) {
  22340. var WebVRCamera = (function (_super) {
  22341. __extends(WebVRCamera, _super);
  22342. function WebVRCamera(name, position, scene) {
  22343. _super.call(this, name, position, scene);
  22344. this._hmdDevice = null;
  22345. this._sensorDevice = null;
  22346. this._cacheState = null;
  22347. this._cacheQuaternion = new BABYLON.Quaternion();
  22348. this._cacheRotation = BABYLON.Vector3.Zero();
  22349. this._vrEnabled = false;
  22350. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  22351. }
  22352. WebVRCamera.prototype._getWebVRDevices = function (devices) {
  22353. var size = devices.length;
  22354. var i = 0;
  22355. this._sensorDevice = null;
  22356. this._hmdDevice = null;
  22357. while (i < size && this._hmdDevice === null) {
  22358. if (devices[i] instanceof HMDVRDevice) {
  22359. this._hmdDevice = devices[i];
  22360. }
  22361. i++;
  22362. }
  22363. i = 0;
  22364. while (i < size && this._sensorDevice === null) {
  22365. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  22366. this._sensorDevice = devices[i];
  22367. }
  22368. i++;
  22369. }
  22370. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  22371. };
  22372. WebVRCamera.prototype._update = function () {
  22373. if (this._vrEnabled) {
  22374. this._cacheState = this._sensorDevice.getState();
  22375. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  22376. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  22377. this.rotation.x = -this._cacheRotation.z;
  22378. this.rotation.y = -this._cacheRotation.y;
  22379. this.rotation.z = this._cacheRotation.x;
  22380. }
  22381. _super.prototype._update.call(this);
  22382. };
  22383. WebVRCamera.prototype.attachControl = function (element, noPreventDefault) {
  22384. _super.prototype.attachControl.call(this, element, noPreventDefault);
  22385. if (navigator.getVRDevices) {
  22386. navigator.getVRDevices().then(this._getWebVRDevices);
  22387. } else if (navigator.mozGetVRDevices) {
  22388. navigator.mozGetVRDevices(this._getWebVRDevices);
  22389. }
  22390. };
  22391. WebVRCamera.prototype.detachControl = function (element) {
  22392. _super.prototype.detachControl.call(this, element);
  22393. this._vrEnabled = false;
  22394. };
  22395. return WebVRCamera;
  22396. })(BABYLON.OculusCamera);
  22397. BABYLON.WebVRCamera = WebVRCamera;
  22398. })(BABYLON || (BABYLON = {}));
  22399. var __extends = this.__extends || function (d, b) {
  22400. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  22401. function __() { this.constructor = d; }
  22402. __.prototype = b.prototype;
  22403. d.prototype = new __();
  22404. };
  22405. var BABYLON;
  22406. (function (BABYLON) {
  22407. var SceneOptimization = (function () {
  22408. function SceneOptimization(priority) {
  22409. if (typeof priority === "undefined") { priority = 0; }
  22410. this.priority = priority;
  22411. this.apply = function (scene) {
  22412. return true;
  22413. };
  22414. }
  22415. return SceneOptimization;
  22416. })();
  22417. BABYLON.SceneOptimization = SceneOptimization;
  22418. var TextureOptimization = (function (_super) {
  22419. __extends(TextureOptimization, _super);
  22420. function TextureOptimization(priority, maximumSize) {
  22421. if (typeof priority === "undefined") { priority = 0; }
  22422. if (typeof maximumSize === "undefined") { maximumSize = 1024; }
  22423. var _this = this;
  22424. _super.call(this, priority);
  22425. this.priority = priority;
  22426. this.maximumSize = maximumSize;
  22427. this.apply = function (scene) {
  22428. var allDone = true;
  22429. for (var index = 0; index < scene.textures.length; index++) {
  22430. var texture = scene.textures[index];
  22431. if (!texture.canRescale) {
  22432. continue;
  22433. }
  22434. var currentSize = texture.getSize();
  22435. var maxDimension = Math.max(currentSize.width, currentSize.height);
  22436. if (maxDimension > _this.maximumSize) {
  22437. texture.scale(0.5);
  22438. allDone = false;
  22439. }
  22440. }
  22441. return allDone;
  22442. };
  22443. }
  22444. return TextureOptimization;
  22445. })(SceneOptimization);
  22446. BABYLON.TextureOptimization = TextureOptimization;
  22447. var HardwareScalingOptimization = (function (_super) {
  22448. __extends(HardwareScalingOptimization, _super);
  22449. function HardwareScalingOptimization(priority, maximumScale) {
  22450. if (typeof priority === "undefined") { priority = 0; }
  22451. if (typeof maximumScale === "undefined") { maximumScale = 2; }
  22452. var _this = this;
  22453. _super.call(this, priority);
  22454. this.priority = priority;
  22455. this.maximumScale = maximumScale;
  22456. this._currentScale = 1;
  22457. this.apply = function (scene) {
  22458. _this._currentScale++;
  22459. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  22460. return _this._currentScale >= _this.maximumScale;
  22461. };
  22462. }
  22463. return HardwareScalingOptimization;
  22464. })(SceneOptimization);
  22465. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  22466. var ShadowsOptimization = (function (_super) {
  22467. __extends(ShadowsOptimization, _super);
  22468. function ShadowsOptimization() {
  22469. _super.apply(this, arguments);
  22470. this.apply = function (scene) {
  22471. scene.shadowsEnabled = false;
  22472. return true;
  22473. };
  22474. }
  22475. return ShadowsOptimization;
  22476. })(SceneOptimization);
  22477. BABYLON.ShadowsOptimization = ShadowsOptimization;
  22478. var PostProcessesOptimization = (function (_super) {
  22479. __extends(PostProcessesOptimization, _super);
  22480. function PostProcessesOptimization() {
  22481. _super.apply(this, arguments);
  22482. this.apply = function (scene) {
  22483. scene.postProcessesEnabled = false;
  22484. return true;
  22485. };
  22486. }
  22487. return PostProcessesOptimization;
  22488. })(SceneOptimization);
  22489. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  22490. var LensFlaresOptimization = (function (_super) {
  22491. __extends(LensFlaresOptimization, _super);
  22492. function LensFlaresOptimization() {
  22493. _super.apply(this, arguments);
  22494. this.apply = function (scene) {
  22495. scene.lensFlaresEnabled = false;
  22496. return true;
  22497. };
  22498. }
  22499. return LensFlaresOptimization;
  22500. })(SceneOptimization);
  22501. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  22502. var ParticlesOptimization = (function (_super) {
  22503. __extends(ParticlesOptimization, _super);
  22504. function ParticlesOptimization() {
  22505. _super.apply(this, arguments);
  22506. this.apply = function (scene) {
  22507. scene.particlesEnabled = false;
  22508. return true;
  22509. };
  22510. }
  22511. return ParticlesOptimization;
  22512. })(SceneOptimization);
  22513. BABYLON.ParticlesOptimization = ParticlesOptimization;
  22514. var RenderTargetsOptimization = (function (_super) {
  22515. __extends(RenderTargetsOptimization, _super);
  22516. function RenderTargetsOptimization() {
  22517. _super.apply(this, arguments);
  22518. this.apply = function (scene) {
  22519. scene.renderTargetsEnabled = false;
  22520. return true;
  22521. };
  22522. }
  22523. return RenderTargetsOptimization;
  22524. })(SceneOptimization);
  22525. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  22526. var SceneOptimizerOptions = (function () {
  22527. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  22528. if (typeof targetFrameRate === "undefined") { targetFrameRate = 60; }
  22529. if (typeof trackerDuration === "undefined") { trackerDuration = 2000; }
  22530. this.targetFrameRate = targetFrameRate;
  22531. this.trackerDuration = trackerDuration;
  22532. this.optimizations = new Array();
  22533. }
  22534. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  22535. var result = new SceneOptimizerOptions(targetFrameRate);
  22536. var priority = 0;
  22537. result.optimizations.push(new ShadowsOptimization(priority));
  22538. result.optimizations.push(new LensFlaresOptimization(priority));
  22539. priority++;
  22540. result.optimizations.push(new PostProcessesOptimization(priority));
  22541. result.optimizations.push(new ParticlesOptimization(priority));
  22542. priority++;
  22543. result.optimizations.push(new TextureOptimization(priority, 1024));
  22544. return result;
  22545. };
  22546. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  22547. var result = new SceneOptimizerOptions(targetFrameRate);
  22548. var priority = 0;
  22549. result.optimizations.push(new ShadowsOptimization(priority));
  22550. result.optimizations.push(new LensFlaresOptimization(priority));
  22551. priority++;
  22552. result.optimizations.push(new PostProcessesOptimization(priority));
  22553. result.optimizations.push(new ParticlesOptimization(priority));
  22554. priority++;
  22555. result.optimizations.push(new TextureOptimization(priority, 512));
  22556. priority++;
  22557. result.optimizations.push(new RenderTargetsOptimization(priority));
  22558. priority++;
  22559. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  22560. return result;
  22561. };
  22562. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  22563. var result = new SceneOptimizerOptions(targetFrameRate);
  22564. var priority = 0;
  22565. result.optimizations.push(new ShadowsOptimization(priority));
  22566. result.optimizations.push(new LensFlaresOptimization(priority));
  22567. priority++;
  22568. result.optimizations.push(new PostProcessesOptimization(priority));
  22569. result.optimizations.push(new ParticlesOptimization(priority));
  22570. priority++;
  22571. result.optimizations.push(new TextureOptimization(priority, 256));
  22572. priority++;
  22573. result.optimizations.push(new RenderTargetsOptimization(priority));
  22574. priority++;
  22575. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  22576. return result;
  22577. };
  22578. return SceneOptimizerOptions;
  22579. })();
  22580. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  22581. var SceneOptimizer = (function () {
  22582. function SceneOptimizer() {
  22583. }
  22584. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  22585. if (BABYLON.Tools.GetFps() >= options.targetFrameRate) {
  22586. if (onSuccess) {
  22587. onSuccess();
  22588. }
  22589. return;
  22590. }
  22591. var allDone = true;
  22592. var noOptimizationApplied = true;
  22593. for (var index = 0; index < options.optimizations.length; index++) {
  22594. var optimization = options.optimizations[index];
  22595. if (optimization.priority === currentPriorityLevel) {
  22596. noOptimizationApplied = false;
  22597. allDone = allDone && optimization.apply(scene);
  22598. }
  22599. }
  22600. if (noOptimizationApplied) {
  22601. if (onFailure) {
  22602. onFailure();
  22603. }
  22604. return;
  22605. }
  22606. if (allDone) {
  22607. currentPriorityLevel++;
  22608. }
  22609. scene.executeWhenReady(function () {
  22610. setTimeout(function () {
  22611. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  22612. }, options.trackerDuration);
  22613. });
  22614. };
  22615. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  22616. if (!options) {
  22617. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  22618. }
  22619. scene.executeWhenReady(function () {
  22620. setTimeout(function () {
  22621. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  22622. }, options.trackerDuration);
  22623. });
  22624. };
  22625. return SceneOptimizer;
  22626. })();
  22627. BABYLON.SceneOptimizer = SceneOptimizer;
  22628. })(BABYLON || (BABYLON = {}));
  22629. var BABYLON;
  22630. (function (BABYLON) {
  22631. (function (Internals) {
  22632. var MeshLODLevel = (function () {
  22633. function MeshLODLevel(distance, mesh) {
  22634. this.distance = distance;
  22635. this.mesh = mesh;
  22636. }
  22637. return MeshLODLevel;
  22638. })();
  22639. Internals.MeshLODLevel = MeshLODLevel;
  22640. })(BABYLON.Internals || (BABYLON.Internals = {}));
  22641. var Internals = BABYLON.Internals;
  22642. })(BABYLON || (BABYLON = {}));
  22643. var BABYLON;
  22644. (function (BABYLON) {
  22645. var AudioEngine = (function () {
  22646. function AudioEngine() {
  22647. this.audioContext = null;
  22648. this.canUseWebAudio = false;
  22649. try {
  22650. if (typeof AudioContext !== 'undefined') {
  22651. this.audioContext = new AudioContext();
  22652. this.canUseWebAudio = true;
  22653. } else if (typeof webkitAudioContext !== 'undefined') {
  22654. this.audioContext = new webkitAudioContext();
  22655. this.canUseWebAudio = true;
  22656. }
  22657. } catch (e) {
  22658. this.canUseWebAudio = false;
  22659. }
  22660. if (this.canUseWebAudio) {
  22661. this.masterGain = this.audioContext.createGain();
  22662. this.masterGain.gain.value = 1;
  22663. this.masterGain.connect(this.audioContext.destination);
  22664. }
  22665. }
  22666. AudioEngine.prototype.getGlobalVolume = function () {
  22667. if (this.canUseWebAudio) {
  22668. return this.masterGain.gain.value;
  22669. } else {
  22670. return -1;
  22671. }
  22672. };
  22673. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  22674. if (this.canUseWebAudio) {
  22675. this.masterGain.gain.value = newVolume;
  22676. }
  22677. };
  22678. return AudioEngine;
  22679. })();
  22680. BABYLON.AudioEngine = AudioEngine;
  22681. })(BABYLON || (BABYLON = {}));
  22682. var BABYLON;
  22683. (function (BABYLON) {
  22684. var Sound = (function () {
  22685. function Sound(url, engine, readyToPlayCallback, distanceMax, autoplay, loop) {
  22686. var _this = this;
  22687. this.distanceMax = 10;
  22688. this.autoplay = false;
  22689. this.loop = false;
  22690. this._position = BABYLON.Vector3.Zero();
  22691. this._orientation = BABYLON.Vector3.Zero();
  22692. this._isLoaded = false;
  22693. this._isReadyToPlay = false;
  22694. this._audioEngine = engine.getAudioEngine();
  22695. ;
  22696. this._readyToPlayCallback = readyToPlayCallback;
  22697. if (distanceMax)
  22698. this.distanceMax = distanceMax;
  22699. if (autoplay)
  22700. this.autoplay = autoplay;
  22701. if (loop)
  22702. this.loop = loop;
  22703. if (this._audioEngine.canUseWebAudio) {
  22704. BABYLON.Tools.LoadFile(url, function (data) {
  22705. _this._soundLoaded(data);
  22706. }, null, null, true);
  22707. }
  22708. }
  22709. Sound.prototype.setPosition = function (newPosition) {
  22710. this._position = newPosition;
  22711. if (this._isReadyToPlay) {
  22712. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  22713. }
  22714. };
  22715. Sound.prototype.setOrientiation = function (newOrientation) {
  22716. this._orientation = newOrientation;
  22717. if (this._isReadyToPlay) {
  22718. this._soundPanner.setOrientation(this._orientation.x, this._orientation.y, this._orientation.z);
  22719. }
  22720. };
  22721. Sound.prototype.play = function () {
  22722. if (this._isReadyToPlay) {
  22723. this._soundSource = this._audioEngine.audioContext.createBufferSource();
  22724. this._soundSource.buffer = this._audioBuffer;
  22725. this._soundPanner = this._audioEngine.audioContext.createPanner();
  22726. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  22727. this._soundPanner.connect(this._audioEngine.masterGain);
  22728. this._soundSource.connect(this._soundPanner);
  22729. this._soundSource.loop = this.loop;
  22730. this._soundSource.start(0);
  22731. }
  22732. };
  22733. Sound.prototype.stop = function () {
  22734. };
  22735. Sound.prototype.pause = function () {
  22736. };
  22737. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  22738. var _this = this;
  22739. meshToConnectTo.registerAfterWorldMatrixUpdate(function (connectedMesh) {
  22740. return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh);
  22741. });
  22742. };
  22743. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  22744. this.setPosition(connectedMesh.position);
  22745. };
  22746. Sound.prototype._soundLoaded = function (audioData) {
  22747. var _this = this;
  22748. this._isLoaded = true;
  22749. this._audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  22750. _this._audioBuffer = buffer;
  22751. _this._isReadyToPlay = true;
  22752. if (_this.autoplay)
  22753. _this.play();
  22754. if (_this._readyToPlayCallback)
  22755. _this._readyToPlayCallback();
  22756. }, function (error) {
  22757. BABYLON.Tools.Error("Error while decoding audio data: " + error.err);
  22758. });
  22759. };
  22760. return Sound;
  22761. })();
  22762. BABYLON.Sound = Sound;
  22763. })(BABYLON || (BABYLON = {}));